diff options
1181 files changed, 24398 insertions, 14336 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d09cdc --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# Exclude MacOS Finder files. +.DS_Store 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-mode.el b/Auxiliary/cmake-mode.el index 20def8b..f29b59b 100644 --- a/Auxiliary/cmake-mode.el +++ b/Auxiliary/cmake-mode.el @@ -114,6 +114,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 +233,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 +271,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 index 624a8c4..9ffc1e8 100644 --- a/Auxiliary/cmake-syntax.vim +++ b/Auxiliary/cmake-syntax.vim @@ -1,16 +1,7 @@ -" ============================================================================= -" -" Program: CMake - Cross-Platform Makefile Generator -" Module: $RCSfile$ -" Language: VIM -" Date: $Date$ -" Version: $Revision$ -" -" ============================================================================= - +" vim: set nowrap: " Vim syntax file " Language: CMake -" Author: Andy Cedilnik <andy.cedilnik@kitware.com> +" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, Nicholas Hutchinson <nshutchinson@gmail.com>, Patrick Boettcher <patrick.boettcher@posteo.de> " Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com> " Last Change: $Date$ " Version: $Revision$ @@ -19,71 +10,550 @@ " 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") +if exists("b:current_syntax") finish endif -syn case ignore syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained -syn region cmakeComment start="#" end="$" contains=cmakeTodo +syn region cmakeComment start="#" end="$" contains=cmakeTodo,@Spell +syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo,@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 + \ 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,cmakeOperators + \ contains=CONTAINED,cmakeTodo 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 + +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_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_DEBUG ARCHIVE_OUTPUT_DIRECTORY_RELEASE ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_DEBUG ARCHIVE_OUTPUT_NAME_RELEASE ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_MOC_OPTIONS AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTOUIC AUTOUIC_OPTIONS BINARY_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_DEFINITIONS_DEBUG COMPILE_DEFINITIONS_RELEASE COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_NAME_DEBUG COMPILE_PDB_NAME_RELEASE COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_DEBUG COMPILE_PDB_OUTPUT_DIRECTORY_RELEASE COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXCLUDE_FROM_DEFAULT_BUILD_DEBUG EXCLUDE_FROM_DEFAULT_BUILD_RELEASE EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_IMPLIB_DEBUG IMPORTED_IMPLIB_RELEASE IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LINK_INTERFACE_MULTIPLICITY_DEBUG IMPORTED_LINK_INTERFACE_MULTIPLICITY_RELEASE IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG IMPORTED_LOCATION_RELEASE IMPORTED_NO_SONAME IMPORTED_NO_SONAME_DEBUG IMPORTED_NO_SONAME_RELEASE IMPORTED_SONAME IMPORTED_SONAME_DEBUG IMPORTED_SONAME_RELEASE IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_DEBUG INTERPROCEDURAL_OPTIMIZATION_RELEASE IN_TRY_COMPILE JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_DEBUG LIBRARY_OUTPUT_DIRECTORY_RELEASE LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_DEBUG LIBRARY_OUTPUT_NAME_RELEASE LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_FLAGS_DEBUG LINK_FLAGS_RELEASE LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_DEBUG LINK_INTERFACE_LIBRARIES_RELEASE LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_DEBUG LINK_INTERFACE_MULTIPLICITY_RELEASE LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LISTFILE_STACK LOCATION LOCATION_DEBUG LOCATION_RELEASE MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MAP_IMPORTED_CONFIG_DEBUG MAP_IMPORTED_CONFIG_RELEASE MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OSX_ARCHITECTURES_DEBUG OSX_ARCHITECTURES_RELEASE OUTPUT_NAME OUTPUT_NAME_DEBUG OUTPUT_NAME_RELEASE PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_NAME_DEBUG PDB_NAME_RELEASE PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_DEBUG PDB_OUTPUT_DIRECTORY_RELEASE POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_DEBUG RUNTIME_OUTPUT_DIRECTORY_RELEASE RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_DEBUG RUNTIME_OUTPUT_NAME_RELEASE RUN_SERIAL SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_DEBUG STATIC_LIBRARY_FLAGS_RELEASE STRINGS SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TIMEOUT TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EXPLICIT_FILE_TYPE XCODE_LAST_KNOWN_FILE_TYPE XCTEST + \ 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 CMAKE_<LANG>_COMPILER_LOADED CMAKE_<LANG>_COMPILER_TARGET CMAKE_<LANG>_COMPILER_VERSION CMAKE_<LANG>_COMPILE_OBJECT CMAKE_<LANG>_CREATE_SHARED_LIBRARY CMAKE_<LANG>_CREATE_SHARED_MODULE CMAKE_<LANG>_CREATE_STATIC_LIBRARY CMAKE_<LANG>_FLAGS CMAKE_<LANG>_FLAGS_DEBUG CMAKE_<LANG>_FLAGS_MINSIZEREL CMAKE_<LANG>_FLAGS_RELEASE CMAKE_<LANG>_FLAGS_RELWITHDEBINFO CMAKE_<LANG>_GHS_KERNEL_FLAGS_DEBUG CMAKE_<LANG>_GHS_KERNEL_FLAGS_MINSIZEREL CMAKE_<LANG>_GHS_KERNEL_FLAGS_RELEASE CMAKE_<LANG>_GHS_KERNEL_FLAGS_RELWITHDEBINFO CMAKE_<LANG>_IGNORE_EXTENSIONS CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES CMAKE_<LANG>_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES CMAKE_<LANG>_INCLUDE_WHAT_YOU_USE CMAKE_<LANG>_LIBRARY_ARCHITECTURE CMAKE_<LANG>_LINKER_PREFERENCE CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES CMAKE_<LANG>_LINK_EXECUTABLE CMAKE_<LANG>_OUTPUT_EXTENSION CMAKE_<LANG>_PLATFORM_ID CMAKE_<LANG>_SIMULATE_ID CMAKE_<LANG>_SIMULATE_VERSION CMAKE_<LANG>_SIZEOF_DATA_PTR CMAKE_<LANG>_SOURCE_FILE_EXTENSIONS CMAKE_<LANG>_VISIBILITY_PRESET CMAKE_ABSOLUTE_DESTINATION_FILES CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS CMAKE_ANDROID_API CMAKE_ANDROID_API_MIN CMAKE_ANDROID_ARCH CMAKE_ANDROID_ASSETS_DIRECTORIES CMAKE_ANDROID_GUI CMAKE_ANDROID_JAR_DEPENDENCIES CMAKE_ANDROID_JAR_DIRECTORIES CMAKE_ANDROID_JAVA_SOURCE_DIR CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES CMAKE_ANDROID_PROCESS_MAX CMAKE_ANDROID_PROGUARD CMAKE_ANDROID_PROGUARD_CONFIG_PATH CMAKE_ANDROID_SECURE_PROPS_PATH CMAKE_ANDROID_SKIP_ANT_STEP CMAKE_ANDROID_STL_TYPE CMAKE_APPBUNDLE_PATH CMAKE_AR CMAKE_ARCHIVE_OUTPUT_DIRECTORY CMAKE_ARCHIVE_OUTPUT_DIRECTORY_<CONFIG> CMAKE_ARGC CMAKE_ARGV0 CMAKE_AUTOMOC CMAKE_AUTOMOC_MOC_OPTIONS CMAKE_AUTOMOC_RELAXED_MODE CMAKE_AUTORCC CMAKE_AUTORCC_OPTIONS CMAKE_AUTOUIC CMAKE_AUTOUIC_OPTIONS CMAKE_BACKWARDS_COMPATIBILITY CMAKE_BINARY_DIR CMAKE_BUILD_TOOL CMAKE_BUILD_TYPE CMAKE_BUILD_WITH_INSTALL_RPATH CMAKE_CACHEFILE_DIR CMAKE_CACHE_MAJOR_VERSION CMAKE_CACHE_MINOR_VERSION CMAKE_CACHE_PATCH_VERSION CMAKE_CFG_INTDIR CMAKE_CL_64 CMAKE_COLOR_MAKEFILE CMAKE_COMMAND CMAKE_COMPILER_2005 CMAKE_COMPILER_IS_GNU<LANG> CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY_<CONFIG> CMAKE_CONFIGURATION_TYPES CMAKE_CROSSCOMPILING CMAKE_CROSSCOMPILING_EMULATOR CMAKE_CMAKE_COMMAND CMAKE_CPACK_COMMAND CMAKE_CTEST_COMMAND CMAKE_CURRENT_BINARY_DIR CMAKE_CURRENT_LIST_DIR CMAKE_CURRENT_LIST_FILE CMAKE_CURRENT_LIST_LINE CMAKE_CURRENT_SOURCE_DIR CMAKE_CXX_COMPILE_FEATURES CMAKE_CXX_EXTENSIONS CMAKE_CXX_STANDARD CMAKE_CXX_STANDARD_REQUIRED CMAKE_C_COMPILE_FEATURES CMAKE_C_EXTENSIONS CMAKE_C_STANDARD CMAKE_C_STANDARD_REQUIRED CMAKE_DEBUG_POSTFIX CMAKE_DEBUG_TARGET_PROPERTIES CMAKE_DISABLE_FIND_PACKAGE_<PackageName> CMAKE_DL_LIBS CMAKE_EDIT_COMMAND CMAKE_ENABLE_EXPORTS CMAKE_ERROR_DEPRECATED CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_EXECUTABLE_SUFFIX CMAKE_EXE_LINKER_FLAGS CMAKE_EXE_LINKER_FLAGS_<CONFIG> CMAKE_EXPORT_COMPILE_COMMANDS CMAKE_EXPORT_NO_PACKAGE_REGISTRY CMAKE_EXTRA_GENERATOR CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES CMAKE_FIND_APPBUNDLE CMAKE_FIND_FRAMEWORK CMAKE_FIND_LIBRARY_PREFIXES CMAKE_FIND_LIBRARY_SUFFIXES CMAKE_FIND_NO_INSTALL_PREFIX CMAKE_FIND_PACKAGE_NAME CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_WARN_NO_MODULE CMAKE_FIND_ROOT_PATH CMAKE_FIND_ROOT_PATH_MODE_INCLUDE CMAKE_FIND_ROOT_PATH_MODE_LIBRARY CMAKE_FIND_ROOT_PATH_MODE_PACKAGE CMAKE_FIND_ROOT_PATH_MODE_PROGRAM CMAKE_FRAMEWORK_PATH CMAKE_Fortran_FORMAT CMAKE_Fortran_MODDIR_DEFAULT CMAKE_Fortran_MODDIR_FLAG CMAKE_Fortran_MODOUT_FLAG CMAKE_Fortran_MODULE_DIRECTORY CMAKE_GENERATOR CMAKE_GENERATOR_PLATFORM CMAKE_GENERATOR_TOOLSET CMAKE_GNUtoMS CMAKE_HOME_DIRECTORY CMAKE_HOST_APPLE CMAKE_HOST_SYSTEM CMAKE_HOST_SYSTEM_NAME CMAKE_HOST_SYSTEM_PROCESSOR CMAKE_HOST_SYSTEM_VERSION CMAKE_HOST_UNIX CMAKE_HOST_WIN32 CMAKE_IGNORE_PATH CMAKE_IMPORT_LIBRARY_PREFIX CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE_INCLUDE_CURRENT_DIR CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE CMAKE_INCLUDE_DIRECTORIES_BEFORE CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE CMAKE_INCLUDE_PATH CMAKE_INSTALL_DEFAULT_COMPONENT_NAME CMAKE_INSTALL_MESSAGE CMAKE_INSTALL_NAME_DIR CMAKE_INSTALL_PREFIX CMAKE_INSTALL_RPATH CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE_INTERNAL_PLATFORM_ABI CMAKE_IOS_INSTALL_COMBINED CMAKE_JOB_POOL_COMPILE CMAKE_JOB_POOL_LINK CMAKE_LIBRARY_ARCHITECTURE CMAKE_LIBRARY_ARCHITECTURE_REGEX CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE_LIBRARY_OUTPUT_DIRECTORY_<CONFIG> CMAKE_LIBRARY_PATH CMAKE_LIBRARY_PATH_FLAG CMAKE_LINK_DEF_FILE_FLAG CMAKE_LINK_DEPENDS_NO_SHARED CMAKE_LINK_INTERFACE_LIBRARIES CMAKE_LINK_LIBRARY_FILE_FLAG CMAKE_LINK_LIBRARY_FLAG CMAKE_LINK_LIBRARY_SUFFIX CMAKE_LINK_SEARCH_END_STATIC CMAKE_LINK_SEARCH_START_STATIC CMAKE_MACOSX_BUNDLE CMAKE_MACOSX_RPATH CMAKE_MAJOR_VERSION CMAKE_MAKE_PROGRAM CMAKE_MAP_IMPORTED_CONFIG_<CONFIG> CMAKE_MATCH_COUNT CMAKE_MFC_FLAG CMAKE_MINIMUM_REQUIRED_VERSION CMAKE_MINOR_VERSION CMAKE_MODULE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS_<CONFIG> CMAKE_MODULE_PATH CMAKE_NOT_USING_CONFIG_FLAGS CMAKE_NO_BUILTIN_CHRPATH CMAKE_NO_SYSTEM_FROM_IMPORTED CMAKE_OBJECT_PATH_MAX CMAKE_OSX_ARCHITECTURES CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT CMAKE_PARENT_LIST_FILE CMAKE_PATCH_VERSION CMAKE_PDB_OUTPUT_DIRECTORY CMAKE_PDB_OUTPUT_DIRECTORY_<CONFIG> CMAKE_POLICY_DEFAULT_CMP<NNNN> CMAKE_POLICY_WARNING_CMP<NNNN> CMAKE_POSITION_INDEPENDENT_CODE CMAKE_PREFIX_PATH CMAKE_PROGRAM_PATH CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE CMAKE_PROJECT_NAME CMAKE_RANLIB CMAKE_ROOT CMAKE_RUNTIME_OUTPUT_DIRECTORY CMAKE_RUNTIME_OUTPUT_DIRECTORY_<CONFIG> CMAKE_SCRIPT_MODE_FILE CMAKE_SHARED_LIBRARY_PREFIX CMAKE_SHARED_LIBRARY_SUFFIX CMAKE_SHARED_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS_<CONFIG> CMAKE_SHARED_MODULE_PREFIX CMAKE_SHARED_MODULE_SUFFIX CMAKE_SIZEOF_VOID_P CMAKE_SKIP_BUILD_RPATH CMAKE_SKIP_INSTALL_ALL_DEPENDENCY CMAKE_SKIP_INSTALL_RPATH CMAKE_SKIP_INSTALL_RULES CMAKE_SKIP_RPATH CMAKE_SOURCE_DIR CMAKE_STAGING_PREFIX CMAKE_STANDARD_LIBRARIES CMAKE_STATIC_LIBRARY_PREFIX CMAKE_STATIC_LIBRARY_SUFFIX CMAKE_STATIC_LINKER_FLAGS CMAKE_STATIC_LINKER_FLAGS_<CONFIG> CMAKE_SYSROOT CMAKE_SYSTEM CMAKE_SYSTEM_APPBUNDLE_PATH CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE_SYSTEM_IGNORE_PATH CMAKE_SYSTEM_INCLUDE_PATH CMAKE_SYSTEM_LIBRARY_PATH CMAKE_SYSTEM_NAME CMAKE_SYSTEM_PREFIX_PATH CMAKE_SYSTEM_PROCESSOR CMAKE_SYSTEM_PROGRAM_PATH CMAKE_SYSTEM_VERSION CMAKE_TOOLCHAIN_FILE CMAKE_TRY_COMPILE_CONFIGURATION CMAKE_TWEAK_VERSION CMAKE_USER_MAKE_RULES_OVERRIDE CMAKE_USER_MAKE_RULES_OVERRIDE_<LANG> CMAKE_USE_RELATIVE_PATHS CMAKE_VERBOSE_MAKEFILE CMAKE_VERSION CMAKE_VISIBILITY_INLINES_HIDDEN CMAKE_VS_DEVENV_COMMAND CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD CMAKE_VS_INTEL_Fortran_PROJECT_VERSION CMAKE_VS_MSBUILD_COMMAND CMAKE_VS_MSDEV_COMMAND CMAKE_VS_NsightTegra_VERSION CMAKE_VS_PLATFORM_NAME CMAKE_VS_PLATFORM_TOOLSET CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION CMAKE_WARN_DEPRECATED CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_WIN32_EXECUTABLE CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS CMAKE_XCODE_ATTRIBUTE_<an-attribute> CMAKE_XCODE_PLATFORM_TOOLSET CPACK_ABSOLUTE_DESTINATION_FILES CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CPACK_INCLUDE_TOPLEVEL_DIRECTORY CPACK_INSTALL_SCRIPT CPACK_PACKAGING_INSTALL_PREFIX CPACK_SET_DESTDIR CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CTEST_BINARY_DIRECTORY CTEST_BUILD_COMMAND CTEST_BUILD_NAME CTEST_BZR_COMMAND CTEST_BZR_UPDATE_OPTIONS CTEST_CHANGE_ID CTEST_CHECKOUT_COMMAND CTEST_CONFIGURATION_TYPE CTEST_CONFIGURE_COMMAND CTEST_COVERAGE_COMMAND CTEST_COVERAGE_EXTRA_FLAGS CTEST_CURL_OPTIONS CTEST_CUSTOM_COVERAGE_EXCLUDE CTEST_CUSTOM_ERROR_EXCEPTION CTEST_CUSTOM_ERROR_MATCH CTEST_CUSTOM_ERROR_POST_CONTEXT CTEST_CUSTOM_ERROR_PRE_CONTEXT CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MEMCHECK_IGNORE CTEST_CUSTOM_POST_MEMCHECK CTEST_CUSTOM_POST_TEST CTEST_CUSTOM_PRE_MEMCHECK CTEST_CUSTOM_PRE_TEST CTEST_CUSTOM_TEST_IGNORE CTEST_CUSTOM_WARNING_EXCEPTION CTEST_CUSTOM_WARNING_MATCH CTEST_CVS_CHECKOUT CTEST_CVS_COMMAND CTEST_CVS_UPDATE_OPTIONS CTEST_DROP_LOCATION CTEST_DROP_METHOD CTEST_DROP_SITE CTEST_DROP_SITE_CDASH CTEST_DROP_SITE_PASSWORD CTEST_DROP_SITE_USER CTEST_EXTRA_COVERAGE_GLOB CTEST_GIT_COMMAND CTEST_GIT_UPDATE_CUSTOM CTEST_GIT_UPDATE_OPTIONS CTEST_HG_COMMAND CTEST_HG_UPDATE_OPTIONS CTEST_MEMORYCHECK_COMMAND CTEST_MEMORYCHECK_COMMAND_OPTIONS CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTEST_MEMORYCHECK_TYPE CTEST_NIGHTLY_START_TIME CTEST_P4_CLIENT CTEST_P4_COMMAND CTEST_P4_OPTIONS CTEST_P4_UPDATE_OPTIONS CTEST_SCP_COMMAND CTEST_SITE CTEST_SOURCE_DIRECTORY CTEST_SVN_COMMAND CTEST_SVN_OPTIONS CTEST_SVN_UPDATE_OPTIONS CTEST_TEST_LOAD CTEST_TEST_TIMEOUT CTEST_TRIGGER_SITE CTEST_UPDATE_COMMAND CTEST_UPDATE_OPTIONS CTEST_UPDATE_VERSION_ONLY CTEST_USE_LAUNCHERS CYGWIN ENV EXECUTABLE_OUTPUT_PATH GHS-MULTI LIBRARY_OUTPUT_PATH MINGW MSVC MSVC10 MSVC11 MSVC12 MSVC14 MSVC60 MSVC70 MSVC71 MSVC80 MSVC90 MSVC_IDE MSVC_VERSION PROJECT_BINARY_DIR PROJECT_NAME PROJECT_SOURCE_DIR PROJECT_VERSION PROJECT_VERSION_MAJOR PROJECT_VERSION_MINOR PROJECT_VERSION_PATCH PROJECT_VERSION_TWEAK UNIX WIN32 WINCE WINDOWS_PHONE WINDOWS_STORE XCODE_VERSION + \ 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 GIT_REPOSITORY GIT_SUBMODULES GIT_TAG HG_REPOSITORY HG_TAG INDEPENDENT INDEPENDENT_STEP_TARGETS INSTALL_COMMAND INSTALL_DIR JOB_POOLS LIST_SEPARATOR LOG LOG_BUILD LOG_CONFIGURE LOG_DOWNLOAD LOG_INSTALL LOG_TEST LOG_UPDATE NO_DEPENDS PATCH_COMMAND PREFIX PROPERTY SOURCE_DIR STAMP_DIR STEP_TARGETS SVN_ SVN_PASSWORD SVN_REPOSITORY SVN_REVISION SVN_TRUST_CERT SVN_USERNAME TEST_AFTER_INSTALL TEST_BEFORE_INSTALL TEST_COMMAND TEST_EXCLUDE_FROM_MAIN TIMEOUT TLS_CAINFO TLS_VERIFY TMP_DIR UPDATE_COMMAND UPDATE_DISCONNECTED URL URL_HASH USES_TERMINAL USES_TERMINAL_BUILD USES_TERMINAL_CONFIGURE USES_TERMINAL_DOWNLOAD USES_TERMINAL_INSTALL USES_TERMINAL_TEST USES_TERMINAL_UPDATE WORKING_DIRECTORY _COMMAND _DIR + \ contained + +syn keyword cmakeKWadd_compile_options + \ COMPILE_OPTIONS \ 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 CTEST_UPDATE CTEST_UPLOAD DEFINE_PROPERTY ELSE ELSEIF ENABLE_LANGUAGE ENABLE_TESTING ENDFOREACH ENDFUNCTION ENDIF ENDMACRO ENDWHILE EXEC_PROGRAM EXECUTE_PROCESS EXPORT EXPORT_LIBRARY_DEPENDENCIES FILE FIND_FILE FIND_LIBRARY FIND_PACKAGE FIND_PATH FIND_PROGRAM FLTK_WRAP_UI FOREACH FUNCTION GET_CMAKE_PROPERTY GET_DIRECTORY_PROPERTY GET_FILENAME_COMPONENT GET_PROPERTY GET_SOURCE_FILE_PROPERTY GET_TARGET_PROPERTY GET_TEST_PROPERTY IF INCLUDE INCLUDE_DIRECTORIES INCLUDE_EXTERNAL_MSPROJECT INCLUDE_REGULAR_EXPRESSION INSTALL INSTALL_FILES INSTALL_PROGRAMS INSTALL_TARGETS LINK_DIRECTORIES LINK_LIBRARIES LIST LOAD_CACHE LOAD_COMMAND MACRO MAKE_DIRECTORY MARK_AS_ADVANCED MATH MESSAGE OPTION OUTPUT_REQUIRED_FILES PROJECT QT_WRAP_CPP QT_WRAP_UI REMOVE REMOVE_DEFINITIONS RETURN SEPARATE_ARGUMENTS SET SET_DIRECTORY_PROPERTIES SET_PROPERTY SET_SOURCE_FILES_PROPERTIES SET_TARGET_PROPERTIES SET_TESTS_PROPERTIES SITE_NAME SOURCE_GROUP STRING SUBDIR_DEPENDS SUBDIRS TARGET_COMPILE_DEFINITIONS TARGET_COMPILE_FEATURES TARGET_COMPILE_OPTIONS TARGET_INCLUDE_DIRECTORIES TARGET_LINK_LIBRARIES TARGET_SOURCES TRY_COMPILE TRY_RUN UNSET USE_MANGLED_MESA UTILITY_SOURCE VARIABLE_REQUIRES VARIABLE_WATCH WHILE WRITE_FILE +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 DBAR DFOO + \ 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 OFF OFFSET OLD ON OUTPUT PATH PATTERN PERMISSIONS PROCESS READ REGEX RELATIVE RELATIVE_PATH RELEASE REMOVE REMOVE_RECURSE RENAME RESULT_VARIABLE SHOW_PROGRESS SORT SSL STATUS STRINGS TIMEOUT TIMESTAMP TLS TLS_CAINFO TLS_VERIFY TO_CMAKE_PATH TO_NATIVE_PATH UPLOAD USE_SOURCE_PERMISSIONS UTC UTF WRITE + \ 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_VERSION_MAJOR PACKAGE_FIND_VERSION_MINOR PACKAGE_FIND_VERSION_PATCH PACKAGE_FIND_VERSION_TWEAK PACKAGE_VERSION PACKAGE_VERSION_COMPATIBLE PACKAGE_VERSION_EXACT PACKAGE_VERSION_UNSUITABLE PATH PATHS PATH_SUFFIXES QUIET REQUIRED TRUE _CONFIG _CONSIDERED_CONFIGS _CONSIDERED_VERSIONS _DIR _FIND_COMPONENTS _FIND_QUIETLY _FIND_REQUIRED _FIND_REQUIRED_ _FIND_VERSION _FIND_VERSION_COUNT _FIND_VERSION_EXACT _FIND_VERSION_MAJOR _FIND_VERSION_MINOR _FIND_VERSION_PATCH _FIND_VERSION_TWEAK _FOUND _VERSION _VERSION_COUNT _VERSION_MAJOR _VERSION_MINOR _VERSION_PATCH _VERSION_TWEAK + \ 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 OWNER_WRITE PATTERN PERMISSIONS POST_INSTALL_SCRIPT PRE_INSTALL_SCRIPT PRIVATE_HEADER PROGRAMS PUBLIC_HEADER REGEX RENAME RESOURCE RUNTIME SCRIPT SETGID SETUID SOVERSION TARGETS TRUE USE_SOURCE_PERMISSIONS VERSION WORLD_EXECUTE WORLD_READ WORLD_WRITE + \ 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 cmakeKWremove_definitions + \ DBAR DFOO + \ 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_COMPILER_ID GNU VERSION_LESS CXX_COMPILER_VERSION OLD_COMPILER OLD_COMPILER CMAKE_CXX_COMPILER_VERSION CONFIGURATION CONFIG CONFIG PLATFORM_ID C_COMPILER_ID CMAKE_ LANG _COMPILER_ID CXX_COMPILER_ID CMAKE_ LANG _COMPILER_ID C_COMPILER_VERSION CMAKE_ LANG _COMPILER_VERSION CXX_COMPILER_VERSION CMAKE_ LANG _COMPILER_VERSION TARGET_FILE TARGET_FILE_NAME TARGET_FILE_DIR TARGET_LINKER_FILE TARGET_LINKER_FILE_NAME TARGET_LINKER_FILE_DIR TARGET_SONAME_FILE TARGET_SONAME_FILE_NAME TARGET_SONAME_FILE_DIR TARGET_PDB_FILE PDB_NAME PDB_OUTPUT_DIRECTORY PDB_NAME_ CONFIG PDB_OUTPUT_DIRECTORY_ CONFIG TARGET_PDB_FILE_NAME TARGET_PDB_FILE_DIR TARGET_PROPERTY TARGET_PROPERTY INSTALL_PREFIX EXPORT COMPILE_LANGUAGE JOIN TARGET_PROPERTY INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES BOOL JOIN TARGET_PROPERTY INCLUDE_DIRECTORIES JOIN ANGLE COMMA SEMICOLON TARGET_NAME LINK_ONLY INTERFACE_LINK_LIBRARIES INSTALL_INTERFACE EXPORT BUILD_INTERFACE LOWER_CASE UPPER_CASE MAKE_C_IDENTIFIER TARGET_OBJECTS OBJECT_LIBRARY SHELL_PATH MSYS + \ contained + +syn case ignore +syn keyword cmakeCommand + \ add_compile_options add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_subdirectory add_test aux_source_directory break build_command cmake_host_system_information cmake_minimum_required cmake_parse_arguments cmake_policy configure_file continue create_test_sourcelist ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ctest_test ctest_update ctest_upload define_property enable_language enable_testing endfunction endmacro execute_process export file find_file find_library find_package find_path find_program fltk_wrap_ui function get_cmake_property get_directory_property get_filename_component get_property get_source_file_property get_target_property get_test_property include include_directories include_external_msproject include_regular_expression install link_directories list load_cache load_command macro mark_as_advanced math message option project qt_wrap_cpp qt_wrap_ui remove_definitions return separate_arguments set set_directory_properties set_property set_source_files_properties set_target_properties set_tests_properties site_name source_group string target_compile_definitions target_compile_features target_compile_options target_include_directories target_link_libraries target_sources try_compile try_run unset variable_watch + \ 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 -" 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 +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 Keyword +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 -let b:current_syntax = "cmake" +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 cmakeKWremove_definitions 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 -"EOF" +let b:current_syntax = "cmake" diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake index 3203279..34bb6bb 100644 --- a/CMakeCPack.cmake +++ b/CMakeCPack.cmake @@ -70,6 +70,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 +90,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) @@ -108,9 +113,9 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake") 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() @@ -166,7 +171,7 @@ if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake") set(CPACK_PACKAGE_CONTACT "cmake@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() diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in index 59ae224..1d61613 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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 787f319..ae5990e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,6 +28,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 +67,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 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/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/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..19a095a 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. diff --git a/Help/generator/Ninja.rst b/Help/generator/Ninja.rst index d94e5f6..ef0e28b 100644 --- a/Help/generator/Ninja.rst +++ b/Help/generator/Ninja.rst @@ -7,6 +7,17 @@ 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. 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..afaccc6 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 ------ 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-modules.7.rst b/Help/manual/cmake-modules.7.rst index 62910cf..e905ef4 100644 --- a/Help/manual/cmake-modules.7.rst +++ b/Help/manual/cmake-modules.7.rst @@ -60,6 +60,7 @@ All Modules /module/CPackIFW /module/CPackNSIS /module/CPackPackageMaker + /module/CPackProductBuild /module/CPackRPM /module/CPack /module/CPackWIX @@ -120,6 +121,7 @@ All Modules /module/FindHTMLHelp /module/FindIce /module/FindIcotool + /module/FindICU /module/FindImageMagick /module/FindIntl /module/FindITK @@ -209,6 +211,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..0f1bfad 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 @@ -217,6 +218,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 +276,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 @@ -341,9 +344,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-variables.7.rst b/Help/manual/cmake-variables.7.rst index 85b8eae..1138b82 100644 --- a/Help/manual/cmake-variables.7.rst +++ b/Help/manual/cmake-variables.7.rst @@ -253,7 +253,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 +277,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 +297,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 @@ -343,10 +352,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 diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst index 65153af..8f7c336 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. 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/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_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_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/dev/0-sample-topic.rst b/Help/release/dev/0-sample-topic.rst new file mode 100644 index 0000000..e4cc01e --- /dev/null +++ b/Help/release/dev/0-sample-topic.rst @@ -0,0 +1,7 @@ +0-sample-topic +-------------- + +* This is a sample release note for the change in a topic. + Developers should add similar notes for each topic branch + making a noteworthy change. Each document should be named + and titled to match the topic name to avoid merge conflicts. diff --git a/Help/release/dev/FindBISON-report-file.rst b/Help/release/dev/FindBISON-report-file.rst new file mode 100644 index 0000000..0b59128 --- /dev/null +++ b/Help/release/dev/FindBISON-report-file.rst @@ -0,0 +1,5 @@ +FindBISON-report-file +--------------------- + +* The :module:`FindBISON` module ``BISON_TARGET`` macro learned a new + ``REPORT_FILE`` option to specify the bison ``--report-file=`` option. diff --git a/Help/release/dev/FindOpenCL-imported-target.rst b/Help/release/dev/FindOpenCL-imported-target.rst new file mode 100644 index 0000000..259c745 --- /dev/null +++ b/Help/release/dev/FindOpenCL-imported-target.rst @@ -0,0 +1,4 @@ +FindOpenCL-imported-target +-------------------------- + +* The :module:`FindOpenCL` module now provides imported targets. diff --git a/Help/release/dev/FindOpenMP-updates.rst b/Help/release/dev/FindOpenMP-updates.rst new file mode 100644 index 0000000..cb29a71 --- /dev/null +++ b/Help/release/dev/FindOpenMP-updates.rst @@ -0,0 +1,5 @@ +FindOpenMP-updates +------------------ + +* The :module:`FindOpenMP` module learned to detect the OpenMP + version (specification date) from the compiler. diff --git a/Help/release/dev/FindVulkan.rst b/Help/release/dev/FindVulkan.rst new file mode 100644 index 0000000..bb5447e --- /dev/null +++ b/Help/release/dev/FindVulkan.rst @@ -0,0 +1,4 @@ +FindVulkan +---------- + +* A :module:`FindVulkan` module was added. diff --git a/Help/release/dev/GenerateExportHeader-custom-content.rst b/Help/release/dev/GenerateExportHeader-custom-content.rst new file mode 100644 index 0000000..161261c --- /dev/null +++ b/Help/release/dev/GenerateExportHeader-custom-content.rst @@ -0,0 +1,6 @@ +GenerateExportHeader-custom-content +----------------------------------- + +* 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. diff --git a/Help/release/dev/add-extra-boolean-comparisons.rst b/Help/release/dev/add-extra-boolean-comparisons.rst new file mode 100644 index 0000000..a928994 --- /dev/null +++ b/Help/release/dev/add-extra-boolean-comparisons.rst @@ -0,0 +1,6 @@ +add-extra-boolean-comparisons +----------------------------- + +* The :command:`if` command gained new boolean comparison operations + ``LESS_EQUAL``, ``GREATER_EQUAL``, ``STRLESS_EQUAL``, ``STRGREATER_EQUAL``, + ``VERSION_LESS_EQUAL``, and ``VERSION_GREATER_EQUAL``. diff --git a/Help/release/dev/aix-clang.rst b/Help/release/dev/aix-clang.rst new file mode 100644 index 0000000..2ff53bf --- /dev/null +++ b/Help/release/dev/aix-clang.rst @@ -0,0 +1,4 @@ +aix-clang +--------- + +* The Clang compiler is now supported on AIX. diff --git a/Help/release/dev/app-framework-bundle-extension.rst b/Help/release/dev/app-framework-bundle-extension.rst new file mode 100644 index 0000000..01855a2 --- /dev/null +++ b/Help/release/dev/app-framework-bundle-extension.rst @@ -0,0 +1,5 @@ +app-framework-bundle-extension +------------------------------ + +* On Apple platforms the :prop_tgt:`BUNDLE_EXTENSION` now also applies to + Frameworks and App Bundles. diff --git a/Help/release/dev/ccmake-vim-navigation.rst b/Help/release/dev/ccmake-vim-navigation.rst new file mode 100644 index 0000000..8fc1416 --- /dev/null +++ b/Help/release/dev/ccmake-vim-navigation.rst @@ -0,0 +1,4 @@ +ccmake-vim-navigation +--------------------- + +* :manual:`ccmake(1)` learned to support vim-like navigation bindings. diff --git a/Help/release/dev/cmake-trace-source.rst b/Help/release/dev/cmake-trace-source.rst new file mode 100644 index 0000000..9b17f6c --- /dev/null +++ b/Help/release/dev/cmake-trace-source.rst @@ -0,0 +1,4 @@ +cmake-trace-source +------------------ + +* The :manual:`cmake(1)` command learned a ``--trace-source=<file>`` option. diff --git a/Help/release/dev/find-lib32.rst b/Help/release/dev/find-lib32.rst new file mode 100644 index 0000000..00818dc --- /dev/null +++ b/Help/release/dev/find-lib32.rst @@ -0,0 +1,7 @@ +find-lib32 +---------- + +* 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. diff --git a/Help/release/dev/findicu.rst b/Help/release/dev/findicu.rst new file mode 100644 index 0000000..0950327 --- /dev/null +++ b/Help/release/dev/findicu.rst @@ -0,0 +1,5 @@ +findicu +------- + +* A :module:`FindICU` module was introduced to find the International + Components for Unicode (ICU) libraries and programs. diff --git a/Help/release/dev/java-export-targets.rst b/Help/release/dev/java-export-targets.rst new file mode 100644 index 0000000..5b70e97 --- /dev/null +++ b/Help/release/dev/java-export-targets.rst @@ -0,0 +1,6 @@ +java-export-targets +------------------- + +* 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. diff --git a/Help/release/dev/link_what_you_use.rst b/Help/release/dev/link_what_you_use.rst new file mode 100644 index 0000000..8d1e598 --- /dev/null +++ b/Help/release/dev/link_what_you_use.rst @@ -0,0 +1,7 @@ +link_what_you_use +----------------- + +* 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``. diff --git a/Help/release/dev/ninja-directory-targets.rst b/Help/release/dev/ninja-directory-targets.rst new file mode 100644 index 0000000..c4269d8 --- /dev/null +++ b/Help/release/dev/ninja-directory-targets.rst @@ -0,0 +1,8 @@ +ninja-directory-targets +----------------------- + +* 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`. diff --git a/Help/release/dev/productbuild.rst b/Help/release/dev/productbuild.rst new file mode 100644 index 0000000..ebe213b --- /dev/null +++ b/Help/release/dev/productbuild.rst @@ -0,0 +1,5 @@ +productbuild +------------ + +* CPack gained a ``productbuild`` generator on OS X, configured by + the :module:`CPackProductBuild` module. diff --git a/Help/release/dev/toolchain-flag-init.rst b/Help/release/dev/toolchain-flag-init.rst new file mode 100644 index 0000000..37e363d --- /dev/null +++ b/Help/release/dev/toolchain-flag-init.rst @@ -0,0 +1,16 @@ +toolchain-flag-init +------------------- + +* :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. diff --git a/Help/release/dev/try_compile-config-flags.rst b/Help/release/dev/try_compile-config-flags.rst new file mode 100644 index 0000000..ebfd6a4 --- /dev/null +++ b/Help/release/dev/try_compile-config-flags.rst @@ -0,0 +1,7 @@ +try_compile-config-flags +------------------------ + +* 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`. diff --git a/Help/release/dev/vs-natvis.rst b/Help/release/dev/vs-natvis.rst new file mode 100644 index 0000000..7cc9844 --- /dev/null +++ b/Help/release/dev/vs-natvis.rst @@ -0,0 +1,5 @@ +vs-natvis +--------- + +* :ref:`Visual Studio Generators` for VS 2010 and above learned to + place ``.natvis`` source files into VS project files properly. diff --git a/Help/release/dev/vs-sdk-refs.rst b/Help/release/dev/vs-sdk-refs.rst new file mode 100644 index 0000000..55232e3 --- /dev/null +++ b/Help/release/dev/vs-sdk-refs.rst @@ -0,0 +1,5 @@ +vs-sdk-refs +----------- + +* A :prop_tgt:`VS_SDK_REFERENCES` target property was added to tell + :ref:`Visual Studio Generators` to reference the named SDKs. diff --git a/Help/release/dev/vs-tool-override.rst b/Help/release/dev/vs-tool-override.rst new file mode 100644 index 0000000..e1177c8 --- /dev/null +++ b/Help/release/dev/vs-tool-override.rst @@ -0,0 +1,5 @@ +vs-tool-override +---------------- + +* 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. diff --git a/Help/release/dev/windows-export-all-from-exe.rst b/Help/release/dev/windows-export-all-from-exe.rst new file mode 100644 index 0000000..48c16ec --- /dev/null +++ b/Help/release/dev/windows-export-all-from-exe.rst @@ -0,0 +1,5 @@ +windows-export-all-from-exe +--------------------------- + +* The :prop_tgt:`WINDOWS_EXPORT_ALL_SYMBOLS` target property now applies + to executable targets with the :prop_tgt:`ENABLE_EXPORTS` property set. diff --git a/Help/release/dev/wix-custom-install-dir.rst b/Help/release/dev/wix-custom-install-dir.rst new file mode 100644 index 0000000..cd12a88 --- /dev/null +++ b/Help/release/dev/wix-custom-install-dir.rst @@ -0,0 +1,7 @@ +wix-custom-install-dir +---------------------- + +* 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. diff --git a/Help/release/dev/wix-disabled-components.rst b/Help/release/dev/wix-disabled-components.rst new file mode 100644 index 0000000..a7e4d5f --- /dev/null +++ b/Help/release/dev/wix-disabled-components.rst @@ -0,0 +1,6 @@ +wix-disabled-components +----------------------- + +* The CPack WIX generator now supports + :variable:`CPACK_COMPONENT_<compName>_DISABLED`. + This can be used to deselect a component from being installed by default. diff --git a/Help/release/dev/wix-root-description.rst b/Help/release/dev/wix-root-description.rst new file mode 100644 index 0000000..24afed2 --- /dev/null +++ b/Help/release/dev/wix-root-description.rst @@ -0,0 +1,7 @@ +wix-root-description +-------------------- + +* 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. diff --git a/Help/release/dev/xcode-file-attributes.rst b/Help/release/dev/xcode-file-attributes.rst new file mode 100644 index 0000000..35824fa --- /dev/null +++ b/Help/release/dev/xcode-file-attributes.rst @@ -0,0 +1,6 @@ +xcode-file-attributes +--------------------- + +* 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. diff --git a/Help/release/index.rst b/Help/release/index.rst index 92c3b63..e93b880 100644 --- a/Help/release/index.rst +++ b/Help/release/index.rst @@ -5,6 +5,8 @@ CMake Release Notes This file should include the adjacent "dev.txt" file in development versions but not in release versions. +.. include:: dev.txt + Releases ======== 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_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_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_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/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/CMakeASMInformation.cmake b/Modules/CMakeASMInformation.cmake index 0e547c4..1bb16ac 100644 --- a/Modules/CMakeASMInformation.cmake +++ b/Modules/CMakeASMInformation.cmake @@ -76,10 +76,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/CMakeBackwardCompatibilityCXX.cmake b/Modules/CMakeBackwardCompatibilityCXX.cmake index f1db46e..f4044e5 100644 --- a/Modules/CMakeBackwardCompatibilityCXX.cmake +++ b/Modules/CMakeBackwardCompatibilityCXX.cmake @@ -50,7 +50,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/CMakeCInformation.cmake b/Modules/CMakeCInformation.cmake index fa87ca8..98eedc4 100644 --- a/Modules/CMakeCInformation.cmake +++ b/Modules/CMakeCInformation.cmake @@ -111,10 +111,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/CMakeCXXInformation.cmake b/Modules/CMakeCXXInformation.cmake index b35280f..07e4f39 100644 --- a/Modules/CMakeCXXInformation.cmake +++ b/Modules/CMakeCXXInformation.cmake @@ -206,10 +206,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/CMakeCommonLanguageInclude.cmake b/Modules/CMakeCommonLanguageInclude.cmake index fa025a8..8bf7288 100644 --- a/Modules/CMakeCommonLanguageInclude.cmake +++ b/Modules/CMakeCommonLanguageInclude.cmake @@ -16,11 +16,15 @@ # 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..17e5302 100644 --- a/Modules/CMakeCompilerIdDetection.cmake +++ b/Modules/CMakeCompilerIdDetection.cmake @@ -120,18 +120,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/CMakeDetermineCCompiler.cmake b/Modules/CMakeDetermineCCompiler.cmake index f8c6303..73d9fb3 100644 --- a/Modules/CMakeDetermineCCompiler.cmake +++ b/Modules/CMakeDetermineCCompiler.cmake @@ -34,6 +34,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) diff --git a/Modules/CMakeDetermineCXXCompiler.cmake b/Modules/CMakeDetermineCXXCompiler.cmake index 3c9bbc2..063b68e 100644 --- a/Modules/CMakeDetermineCXXCompiler.cmake +++ b/Modules/CMakeDetermineCXXCompiler.cmake @@ -33,6 +33,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) diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake index 465989d..64d9bed 100644 --- a/Modules/CMakeDetermineCompilerId.cmake +++ b/Modules/CMakeDetermineCompilerId.cmake @@ -365,14 +365,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 +493,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..596fc5f 100644 --- a/Modules/CMakeDetermineFortranCompiler.cmake +++ b/Modules/CMakeDetermineFortranCompiler.cmake @@ -20,6 +20,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 +141,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 +172,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/CMakeFindFrameworks.cmake b/Modules/CMakeFindFrameworks.cmake index 6a8bcd4..80eb003 100644 --- a/Modules/CMakeFindFrameworks.cmake +++ b/Modules/CMakeFindFrameworks.cmake @@ -3,6 +3,10 @@ # ------------------- # # helper module to find OSX frameworks +# +# This module reads hints about search locations from variables:: +# +# CMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS - Extra directories #============================================================================= # Copyright 2003-2009 Kitware, Inc. @@ -24,9 +28,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/CMakeFortranInformation.cmake b/Modules/CMakeFortranInformation.cmake index 1fd0972..45dbfcc 100644 --- a/Modules/CMakeFortranInformation.cmake +++ b/Modules/CMakeFortranInformation.cmake @@ -173,10 +173,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/CMakeIOSInstallCombined.cmake b/Modules/CMakeIOSInstallCombined.cmake index 1256f56..234322c 100644 --- a/Modules/CMakeIOSInstallCombined.cmake +++ b/Modules/CMakeIOSInstallCombined.cmake @@ -237,20 +237,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/CMakePackageConfigHelpers.cmake b/Modules/CMakePackageConfigHelpers.cmake index 5e5302f..828ea9e 100644 --- a/Modules/CMakePackageConfigHelpers.cmake +++ b/Modules/CMakePackageConfigHelpers.cmake @@ -280,7 +280,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 +294,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 +306,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 +319,7 @@ endmacro() ") endif() - set(PACKAGE_INIT "${PACKAGE_INIT} + string(APPEND PACKAGE_INIT " ####################################################################################") configure_file("${_inputFile}" "${_outputFile}" @ONLY) diff --git a/Modules/CMakeParseImplicitLinkInfo.cmake b/Modules/CMakeParseImplicitLinkInfo.cmake index ef9a2eb..f6d07e5 100644 --- a/Modules/CMakeParseImplicitLinkInfo.cmake +++ b/Modules/CMakeParseImplicitLinkInfo.cmake @@ -32,7 +32,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 +44,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 +56,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 +124,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 +151,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..61a0909 100644 --- a/Modules/CMakePrintHelpers.cmake +++ b/Modules/CMakePrintHelpers.cmake @@ -55,9 +55,9 @@ 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 +132,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/CMakeRCInformation.cmake b/Modules/CMakeRCInformation.cmake index 94abd4b..60276e2 100644 --- a/Modules/CMakeRCInformation.cmake +++ b/Modules/CMakeRCInformation.cmake @@ -28,9 +28,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..85d3143 100644 --- a/Modules/CMakeSwiftInformation.cmake +++ b/Modules/CMakeSwiftInformation.cmake @@ -13,6 +13,7 @@ # 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/CPack.cmake b/Modules/CPack.cmake index 77f854d..675b38b 100644 --- a/Modules/CPack.cmake +++ b/Modules/CPack.cmake @@ -332,7 +332,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 +455,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 +484,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) @@ -531,6 +533,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 diff --git a/Modules/CPackComponent.cmake b/Modules/CPackComponent.cmake index 038a717..6552a2d 100644 --- a/Modules/CPackComponent.cmake +++ b/Modules/CPackComponent.cmake @@ -75,9 +75,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 # @@ -360,6 +368,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 +417,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 +509,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/CPackIFW.cmake b/Modules/CPackIFW.cmake index 083fc28..ebc5c90 100644 --- a/Modules/CPackIFW.cmake +++ b/Modules/CPackIFW.cmake @@ -571,7 +571,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() @@ -604,7 +604,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 +645,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 +687,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() diff --git a/Modules/CPackProductBuild.cmake b/Modules/CPackProductBuild.cmake new file mode 100644 index 0000000..6545a3a --- /dev/null +++ b/Modules/CPackProductBuild.cmake @@ -0,0 +1,38 @@ +#.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.) +# + +#============================================================================= +# 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/CPackRPM.cmake b/Modules/CPackRPM.cmake index 9cc496f..c195746 100644 --- a/Modules/CPackRPM.cmake +++ b/Modules/CPackRPM.cmake @@ -761,7 +761,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 +779,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() @@ -859,7 +859,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 +954,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 +971,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 +998,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 +1018,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 +1030,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 +1052,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 +1217,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) @@ -1346,7 +1348,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 +1407,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 @@ -1524,13 +1526,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 +1685,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 +1708,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 +1729,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}") diff --git a/Modules/CPackWIX.cmake b/Modules/CPackWIX.cmake index 3c90561..08ff0cb 100644 --- a/Modules/CPackWIX.cmake +++ b/Modules/CPackWIX.cmake @@ -237,6 +237,34 @@ # * ARPURLUPDATEINFO - Update information URL # * ARPHELPTELEPHONE - Help and support telephone number # * ARPSIZE - Size (in kilobytes) of the application +# +# .. variable:: CPACK_WIX_ROOT_FEATURE_TITLE +# +# Sets the name of the root install feature in the WIX installer. Same as +# CPACK_COMPONENT_<compName>_DISPLAY_NAME for components. +# +# .. variable:: CPACK_WIX_ROOT_FEATURE_DESCRIPTION +# +# Sets the description of the root install feature in the WIX installer. Same as +# CPACK_COMPONENT_<compName>_DESCRIPTION for components. +# +# .. variable:: CPACK_WIX_SKIP_PROGRAM_FOLDER +# +# If this variable is set to true, the default install location +# of the generated package will be CPACK_PACKAGE_INSTALL_DIRECTORY directly. +# The install location will not be located relatively below +# ProgramFiles or ProgramFiles64. +# +# .. note:: +# Installers created with this feature do not take differences +# between the system on which the installer is created +# and the system on which the installer might be used into account. +# +# It is 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. +# #============================================================================= # Copyright 2014-2015 Kitware, Inc. diff --git a/Modules/CTest.cmake b/Modules/CTest.cmake index a27eb4b..ce725c5 100644 --- a/Modules/CTest.cmake +++ b/Modules/CTest.cmake @@ -224,16 +224,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/CTestUseLaunchers.cmake b/Modules/CTestUseLaunchers.cmake index c79119f..1a57d00 100644 --- a/Modules/CTestUseLaunchers.cmake +++ b/Modules/CTestUseLaunchers.cmake @@ -59,7 +59,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/CheckIncludeFile.cmake b/Modules/CheckIncludeFile.cmake index ef1e39d..cfbc28f 100644 --- a/Modules/CheckIncludeFile.cmake +++ b/Modules/CheckIncludeFile.cmake @@ -60,7 +60,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..59df7cb 100644 --- a/Modules/CheckIncludeFileCXX.cmake +++ b/Modules/CheckIncludeFileCXX.cmake @@ -59,7 +59,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..3657c95 100644 --- a/Modules/CheckIncludeFiles.cmake +++ b/Modules/CheckIncludeFiles.cmake @@ -55,11 +55,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/CheckPrototypeDefinition.cmake b/Modules/CheckPrototypeDefinition.cmake index e203d4c..b9345e7 100644 --- a/Modules/CheckPrototypeDefinition.cmake +++ b/Modules/CheckPrototypeDefinition.cmake @@ -75,8 +75,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/CheckStructHasMember.cmake b/Modules/CheckStructHasMember.cmake index 6c15205..e9e5a18 100644 --- a/Modules/CheckStructHasMember.cmake +++ b/Modules/CheckStructHasMember.cmake @@ -54,7 +54,7 @@ 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..a62d1e1 100644 --- a/Modules/CheckSymbolExists.cmake +++ b/Modules/CheckSymbolExists.cmake @@ -71,11 +71,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..827905b 100644 --- a/Modules/CheckTypeSize.cmake +++ b/Modules/CheckTypeSize.cmake @@ -97,17 +97,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 +157,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/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@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/CrayPrgEnv.cmake b/Modules/Compiler/CrayPrgEnv.cmake index fa39b00..9f8befd 100644 --- a/Modules/Compiler/CrayPrgEnv.cmake +++ b/Modules/Compiler/CrayPrgEnv.cmake @@ -56,6 +56,8 @@ macro(__CrayPrgEnv_setup lang test_src compiler_cmd link_cmd) message(STATUS "Cray Programming Environment $ENV{CRAYPE_VERSION} ${lang}") elseif(DEFINED ENV{ASYNCPE_VERSION}) message(STATUS "Cray XT Programming Environment $ENV{ASYNCPE_VERSION} ${lang}") + else() + message(STATUS "Cray Programming Environment (unknown version) ${lang}") endif() # Flags for the Cray wrappers 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..fc848ac 100644 --- a/Modules/Compiler/GNU-Fortran.cmake +++ b/Modules/Compiler/GNU-Fortran.cmake @@ -5,8 +5,8 @@ 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..4d2fe5b 100644 --- a/Modules/Compiler/GNU.cmake +++ b/Modules/Compiler/GNU.cmake @@ -25,7 +25,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 +45,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/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 eb9602a..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>") @@ -16,14 +15,14 @@ endif() if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.0) set(CMAKE_C11_STANDARD_COMPILE_OPTION "${_std}=c11") - set(CMAKE_C11_EXTENSION_COMPILE_OPTION "${_std}=c11") + set(CMAKE_C11_EXTENSION_COMPILE_OPTION "${_std}=gnu11") endif() -if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.1) +if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.0) set(CMAKE_C90_STANDARD_COMPILE_OPTION "${_std}=c89") - set(CMAKE_C90_EXTENSION_COMPILE_OPTION "${_std}=c89") + set(CMAKE_C90_EXTENSION_COMPILE_OPTION "${_std}=gnu89") set(CMAKE_C99_STANDARD_COMPILE_OPTION "${_std}=c99") - set(CMAKE_C99_EXTENSION_COMPILE_OPTION "${_std}=c99") + set(CMAKE_C99_EXTENSION_COMPILE_OPTION "${_std}=gnu99") endif() if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.1) 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..ef7aa3a 100644 --- a/Modules/Compiler/Intel-Fortran.cmake +++ b/Modules/Compiler/Intel-Fortran.cmake @@ -1,10 +1,7 @@ -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") diff --git a/Modules/Compiler/Intel.cmake b/Modules/Compiler/Intel.cmake new file mode 100644 index 0000000..8c3942c --- /dev/null +++ b/Modules/Compiler/Intel.cmake @@ -0,0 +1,36 @@ + +#============================================================================= +# Copyright 2002-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(__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/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..51069c2 100644 --- a/Modules/Compiler/PGI.cmake +++ b/Modules/Compiler/PGI.cmake @@ -23,11 +23,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..09ee2ba 100644 --- a/Modules/Compiler/PathScale.cmake +++ b/Modules/Compiler/PathScale.cmake @@ -23,9 +23,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/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..a0e07d4 100644 --- a/Modules/Compiler/SunPro-Fortran.cmake +++ b/Modules/Compiler/SunPro-Fortran.cmake @@ -10,11 +10,11 @@ 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") 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..1f2b145 100644 --- a/Modules/Compiler/XL.cmake +++ b/Modules/Compiler/XL.cmake @@ -29,10 +29,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/Dart.cmake b/Modules/Dart.cmake index db487d8..90298d6 100644 --- a/Modules/Dart.cmake +++ b/Modules/Dart.cmake @@ -119,7 +119,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..f5ac959 100644 --- a/Modules/DeployQt4.cmake +++ b/Modules/DeployQt4.cmake @@ -247,7 +247,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 +263,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/ExternalData.cmake b/Modules/ExternalData.cmake index a3f460d..a0bffe7 100644 --- a/Modules/ExternalData.cmake +++ b/Modules/ExternalData.cmake @@ -473,10 +473,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 +696,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 +717,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 +971,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 +988,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..91d74e0 100644 --- a/Modules/ExternalProject-download.cmake.in +++ b/Modules/ExternalProject-download.cmake.in @@ -114,48 +114,56 @@ 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 + ) + + 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.cmake b/Modules/ExternalProject.cmake index 2ff18fc..fc01976 100644 --- a/Modules/ExternalProject.cmake +++ b/Modules/ExternalProject.cmake @@ -69,8 +69,8 @@ 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`` @@ -993,6 +993,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}\") @@ -1117,8 +1118,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 +1133,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}") + list(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() @@ -1332,16 +1333,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 +1668,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 +1862,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 +1885,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}) diff --git a/Modules/FeatureSummary.cmake b/Modules/FeatureSummary.cmake index dc31086..764a5f7 100644 --- a/Modules/FeatureSummary.cmake +++ b/Modules/FeatureSummary.cmake @@ -411,23 +411,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() @@ -527,7 +527,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() diff --git a/Modules/FindBISON.cmake b/Modules/FindBISON.cmake index 69293f5..6b1c7bd 100644 --- a/Modules/FindBISON.cmake +++ b/Modules/FindBISON.cmake @@ -23,7 +23,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 +40,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 +64,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 @@ -120,35 +126,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 +192,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 +216,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 +249,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/FindBZip2.cmake b/Modules/FindBZip2.cmake index 6af42dd..b670025 100644 --- a/Modules/FindBZip2.cmake +++ b/Modules/FindBZip2.cmake @@ -37,7 +37,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) diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake index 67d71d0..1f03841 100644 --- a/Modules/FindBoost.cmake +++ b/Modules/FindBoost.cmake @@ -209,6 +209,7 @@ # Copyright 2007 Mike Jackson # Copyright 2008 Andreas Pakulat <apaku@gmx.de> # Copyright 2008-2012 Philip Lowman <philip@yhbt.com> +# Copyright 2016 Alex Turbov <i.zaufi@gmail.com> # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. @@ -442,24 +443,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") @@ -805,6 +808,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 +869,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 # #------------------------------------------------------------------------------- @@ -1143,8 +1181,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 +1204,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 +1221,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 +1299,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 +1358,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 +1640,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 +1738,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 +1745,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/FindCUDA.cmake b/Modules/FindCUDA.cmake index 48bb554..d7c9d8a 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,7 +299,7 @@ # 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+ @@ -563,8 +579,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 +596,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 +631,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 +643,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 +690,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 +706,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 @@ -705,19 +743,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 +778,20 @@ if(CUDA_VERSION VERSION_EQUAL "3.0") CUDA_CUDARTEMU_LIBRARY ) endif() -if(NOT CUDA_VERSION VERSION_LESS "5.5") + +if(CUDA_USE_STATIC_CUDA_RUNTIME AND 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. 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) + set(CUDA_CUDART_LIBRARY_VAR CUDA_CUDART_LIBRARY) endif() if(CUDA_USE_STATIC_CUDA_RUNTIME) @@ -772,12 +817,12 @@ 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. - 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.") - endif() + endif() + if (UNIX AND NOT APPLE AND CUDA_VERSION VERSION_LESS "7.0") + # Before CUDA 7.0, there was librt that has things such as, clock_gettime, shm_open, and shm_unlink. + 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.") endif() endif() endif() @@ -955,12 +1000,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 ) @@ -986,6 +1032,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 @@ -1278,13 +1325,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 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..ff1f515 100644 --- a/Modules/FindCUDA/run_nvcc.cmake +++ b/Modules/FindCUDA/run_nvcc.cmake @@ -95,7 +95,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..d516831 --- /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_bin}") + 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])$") + 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 PTX for the concrete BIN + 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 PTX for the concrete BIN, we assume PTX=BIN + 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/FindCups.cmake b/Modules/FindCups.cmake index 51eb7c5..6f70455 100644 --- a/Modules/FindCups.cmake +++ b/Modules/FindCups.cmake @@ -55,7 +55,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/FindEXPAT.cmake b/Modules/FindEXPAT.cmake index 653094c..70fc35b 100644 --- a/Modules/FindEXPAT.cmake +++ b/Modules/FindEXPAT.cmake @@ -41,7 +41,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/FindFreetype.cmake b/Modules/FindFreetype.cmake index 7d46d15..35dc17d 100644 --- a/Modules/FindFreetype.cmake +++ b/Modules/FindFreetype.cmake @@ -51,9 +51,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 +63,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 +80,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 +135,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 +160,6 @@ find_package_handle_standard_args( ) mark_as_advanced( - FREETYPE_LIBRARY FREETYPE_INCLUDE_DIR_freetype2 FREETYPE_INCLUDE_DIR_ft2build ) diff --git a/Modules/FindGIF.cmake b/Modules/FindGIF.cmake index 7bbb8cf..6fbe9e9 100644 --- a/Modules/FindGIF.cmake +++ b/Modules/FindGIF.cmake @@ -2,12 +2,18 @@ # 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) @@ -29,7 +35,7 @@ # 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 +67,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..7413289 100644 --- a/Modules/FindGLEW.cmake +++ b/Modules/FindGLEW.cmake @@ -35,20 +35,45 @@ # 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/FindGTest.cmake b/Modules/FindGTest.cmake index a7ffcfe..72032c7 100644 --- a/Modules/FindGTest.cmake +++ b/Modules/FindGTest.cmake @@ -226,13 +226,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 +233,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 +250,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 +257,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/FindHDF5.cmake b/Modules/FindHDF5.cmake index 50e1892..a898386 100644 --- a/Modules/FindHDF5.cmake +++ b/Modules/FindHDF5.cmake @@ -332,7 +332,7 @@ macro( _HDF5_parse_compile_line set( RE " -D([^ ]*)") string( REGEX MATCHALL "${RE}" definition_flags "${${compile_line_var}}" ) foreach( DEF IN LISTS definition_flags ) - string( REGEX REPLACE "${RE}" "\\1" DEF "${DEF}" ) + string( STRIP "${DEF}" DEF ) list( APPEND ${definitions} ${DEF} ) endforeach() diff --git a/Modules/FindICU.cmake b/Modules/FindICU.cmake new file mode 100644 index 0000000..ade39b8 --- /dev/null +++ b/Modules/FindICU.cmake @@ -0,0 +1,359 @@ +#.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@codelibre.net> + +#============================================================================= +# Copyright 2014-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.) + +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..2bd39e8 100644 --- a/Modules/FindIce.cmake +++ b/Modules/FindIce.cmake @@ -141,6 +141,8 @@ function(_Ice_FIND) set(ice_versions 3 3.6 + 3.6.2 + 3.6.1 3.6.0 3.5 3.5.1 @@ -360,12 +362,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") - mark_as_advanced("${component_cache}") + DOC "Ice ${component} library (release)") + find_library("${component_cache_debug}" "${component}d" + HINTS ${ice_roots} + PATH_SUFFIXES ${ice_library_suffixes} + 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 +448,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 +457,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/FindJNI.cmake b/Modules/FindJNI.cmake index 3ceab39..658d6ca 100644 --- a/Modules/FindJNI.cmake +++ b/Modules/FindJNI.cmake @@ -312,8 +312,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/FindJava.cmake b/Modules/FindJava.cmake index c643d9b..424ae30 100644 --- a/Modules/FindJava.cmake +++ b/Modules/FindJava.cmake @@ -8,6 +8,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 +55,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. # # diff --git a/Modules/FindLua.cmake b/Modules/FindLua.cmake index 4e00a92..f105f3d 100644 --- a/Modules/FindLua.cmake +++ b/Modules/FindLua.cmake @@ -49,34 +49,37 @@ 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 +96,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 +189,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/FindMPI.cmake b/Modules/FindMPI.cmake index fbc6795..4f78623 100644 --- a/Modules/FindMPI.cmake +++ b/Modules/FindMPI.cmake @@ -327,7 +327,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 +376,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 +398,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/FindOpenCL.cmake b/Modules/FindOpenCL.cmake index 4d3ed84..6acda55 100644 --- a/Modules/FindOpenCL.cmake +++ b/Modules/FindOpenCL.cmake @@ -4,7 +4,16 @@ # # 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 @@ -20,7 +29,7 @@ # #============================================================================= -# Copyright 2014 Matthaeus G. Chajdas +# Copyright 2014-2016 Matthaeus G. Chajdas # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. @@ -44,7 +53,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 +143,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/FindOpenMP.cmake b/Modules/FindOpenMP.cmake index ee4bdd6..a788832 100644 --- a/Modules/FindOpenMP.cmake +++ b/Modules/FindOpenMP.cmake @@ -12,17 +12,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 +# The following internal variables are set, if detected: # +# ``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. # -# -# Supported compilers can be found at -# http://openmp.org/wp/openmp-compilers/ +# The specification dates are formatted as integers of the form +# ``CCYYMM`` where these represent the decimal digits of the century, +# year, and month. #============================================================================= # Copyright 2009 Kitware, Inc. @@ -122,6 +132,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 +232,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 +274,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 +313,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 +335,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..10b62ff 100644 --- a/Modules/FindOpenSSL.cmake +++ b/Modules/FindOpenSSL.cmake @@ -328,11 +328,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 +399,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 +406,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 +427,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 +434,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/FindPHP4.cmake b/Modules/FindPHP4.cmake index 25fff8c..7eab161 100644 --- a/Modules/FindPHP4.cmake +++ b/Modules/FindPHP4.cmake @@ -58,8 +58,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 +82,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..d0dd870 100644 --- a/Modules/FindPNG.cmake +++ b/Modules/FindPNG.cmake @@ -126,13 +126,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 +133,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..96590cb 100644 --- a/Modules/FindPackageHandleStandardArgs.cmake +++ b/Modules/FindPackageHandleStandardArgs.cmake @@ -169,10 +169,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 +253,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 +277,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 +368,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/FindPkgConfig.cmake b/Modules/FindPkgConfig.cmake index b79e9df..b6156dd 100644 --- a/Modules/FindPkgConfig.cmake +++ b/Modules/FindPkgConfig.cmake @@ -200,7 +200,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 +316,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..32a3f0a 100644 --- a/Modules/FindPostgreSQL.cmake +++ b/Modules/FindPostgreSQL.cmake @@ -186,7 +186,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/FindProtobuf.cmake b/Modules/FindProtobuf.cmake index 8042073..8a2e4e7 100644 --- a/Modules/FindProtobuf.cmake +++ b/Modules/FindProtobuf.cmake @@ -129,6 +129,10 @@ function(PROTOBUF_GENERATE_CPP SRCS HDRS) set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif() + if(DEFINED PROTOBUF_IMPORT_DIRS AND NOT DEFINED Protobuf_IMPORT_DIRS) + set(Protobuf_IMPORT_DIRS "${PROTOBUF_IMPORT_DIRS}") + endif() + if(DEFINED Protobuf_IMPORT_DIRS) foreach(DIR ${Protobuf_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) @@ -144,6 +148,10 @@ function(PROTOBUF_GENERATE_CPP SRCS HDRS) foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(FIL_WE ${FIL} NAME_WE) + get_filename_component(FIL_DIR ${FIL} DIRECTORY) + if(FIL_DIR) + set(FIL_WE "${FIL_DIR}/${FIL_WE}") + endif() list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc") list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h") @@ -183,6 +191,10 @@ function(PROTOBUF_GENERATE_PYTHON SRCS) set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif() + if(DEFINED PROTOBUF_IMPORT_DIRS AND NOT DEFINED Protobuf_IMPORT_DIRS) + set(Protobuf_IMPORT_DIRS "${PROTOBUF_IMPORT_DIRS}") + endif() + if(DEFINED Protobuf_IMPORT_DIRS) foreach(DIR ${Protobuf_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) @@ -197,6 +209,10 @@ function(PROTOBUF_GENERATE_PYTHON SRCS) foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(FIL_WE ${FIL} NAME_WE) + get_filename_component(FIL_DIR ${FIL} DIRECTORY) + if(FIL_DIR) + set(FIL_WE "${FIL_DIR}/${FIL_WE}") + endif() list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py") add_custom_command( diff --git a/Modules/FindQt4.cmake b/Modules/FindQt4.cmake index d167a13..7c41b99 100644 --- a/Modules/FindQt4.cmake +++ b/Modules/FindQt4.cmake @@ -764,7 +764,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/FindSDL_sound.cmake b/Modules/FindSDL_sound.cmake index 494d358..b378c34 100644 --- a/Modules/FindSDL_sound.cmake +++ b/Modules/FindSDL_sound.cmake @@ -123,7 +123,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 +173,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/FindTIFF.cmake b/Modules/FindTIFF.cmake index e600498..6c760db 100644 --- a/Modules/FindTIFF.cmake +++ b/Modules/FindTIFF.cmake @@ -98,13 +98,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 +105,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/FindVulkan.cmake b/Modules/FindVulkan.cmake new file mode 100644 index 0000000..b335f5f --- /dev/null +++ b/Modules/FindVulkan.cmake @@ -0,0 +1,85 @@ +#.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 +# + +#============================================================================= +# Copyright 2016 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.) + +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/FindXalanC.cmake b/Modules/FindXalanC.cmake index 016b7aa..f5061d3 100644 --- a/Modules/FindXalanC.cmake +++ b/Modules/FindXalanC.cmake @@ -143,13 +143,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 +150,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..25e79d1 100644 --- a/Modules/FindXercesC.cmake +++ b/Modules/FindXercesC.cmake @@ -122,13 +122,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 +129,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..f4dc5ae 100644 --- a/Modules/FindZLIB.cmake +++ b/Modules/FindZLIB.cmake @@ -96,7 +96,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 +110,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/FindwxWidgets.cmake b/Modules/FindwxWidgets.cmake index 8c07e6c..2974b9e 100644 --- a/Modules/FindwxWidgets.cmake +++ b/Modules/FindwxWidgets.cmake @@ -854,7 +854,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..e405257 100644 --- a/Modules/FindwxWindows.cmake +++ b/Modules/FindwxWindows.cmake @@ -650,7 +650,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..ae01541 100644 --- a/Modules/FortranCInterface.cmake +++ b/Modules/FortranCInterface.cmake @@ -270,7 +270,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 +279,7 @@ ${_desc_${macro}} # Generate symbol mangling definitions. if(SYMBOLS) - set(HEADER_CONTENT "${HEADER_CONTENT} + string(APPEND HEADER_CONTENT " /*--------------------------------------------------------------------------*/ /* Mangle some symbols automatically. */ ") @@ -300,7 +300,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 +314,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/GenerateExportHeader.cmake b/Modules/GenerateExportHeader.cmake index 6389d30..735a0d7 100644 --- a/Modules/GenerateExportHeader.cmake +++ b/Modules/GenerateExportHeader.cmake @@ -20,6 +20,7 @@ # [NO_DEPRECATED_MACRO_NAME <no_deprecated_macro_name>] # [DEFINE_NO_DEPRECATED] # [PREFIX_NAME <prefix_name>] +# [CUSTOM_CONTENT_FROM_VARIABLE <variable>] # ) # # @@ -60,8 +61,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 +81,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 @@ -288,7 +291,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 +364,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 +415,6 @@ 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}" PARENT_SCOPE) endif() endfunction() diff --git a/Modules/GetPrerequisites.cmake b/Modules/GetPrerequisites.cmake index fb7bf93..58f5a92 100644 --- a/Modules/GetPrerequisites.cmake +++ b/Modules/GetPrerequisites.cmake @@ -751,9 +751,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 +800,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/MatlabTestsRedirect.cmake b/Modules/MatlabTestsRedirect.cmake index 77b7afe..0ef4c3e 100644 --- a/Modules/MatlabTestsRedirect.cmake +++ b/Modules/MatlabTestsRedirect.cmake @@ -46,7 +46,7 @@ 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() diff --git a/Modules/NSIS.template.in b/Modules/NSIS.template.in index 92a3142..c66a89b 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" ;---------------------------------------- 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.cmake b/Modules/Platform/AIX-GNU.cmake index d6f5331..df97ab1 100644 --- a/Modules/Platform/AIX-GNU.cmake +++ b/Modules/Platform/AIX-GNU.cmake @@ -21,9 +21,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) diff --git a/Modules/Platform/AIX-XL.cmake b/Modules/Platform/AIX-XL.cmake index 5470441..3be095e 100644 --- a/Modules/Platform/AIX-XL.cmake +++ b/Modules/Platform/AIX-XL.cmake @@ -21,9 +21,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/BlueGeneQ-base.cmake b/Modules/Platform/BlueGeneQ-base.cmake index 9372166..dc066b7 100644 --- a/Modules/Platform/BlueGeneQ-base.cmake +++ b/Modules/Platform/BlueGeneQ-base.cmake @@ -110,7 +110,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/Windows-CXX.cmake b/Modules/Platform/CYGWIN-Determine-CXX.cmake index bf37f79..bf37f79 100644 --- a/Modules/Platform/Windows-CXX.cmake +++ b/Modules/Platform/CYGWIN-Determine-CXX.cmake diff --git a/Modules/Platform/CYGWIN-GNU.cmake b/Modules/Platform/CYGWIN-GNU.cmake index 1a46c10..5090c08 100644 --- a/Modules/Platform/CYGWIN-GNU.cmake +++ b/Modules/Platform/CYGWIN-GNU.cmake @@ -19,7 +19,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/CrayLinuxEnvironment.cmake b/Modules/Platform/CrayLinuxEnvironment.cmake index 97771a2..a1a3d3f 100644 --- a/Modules/Platform/CrayLinuxEnvironment.cmake +++ b/Modules/Platform/CrayLinuxEnvironment.cmake @@ -8,14 +8,22 @@ if(DEFINED ENV{CRAYOS_VERSION}) set(CMAKE_SYSTEM_VERSION "$ENV{CRAYOS_VERSION}") elseif(DEFINED ENV{XTOS_VERSION}) set(CMAKE_SYSTEM_VERSION "$ENV{XTOS_VERSION}") -else() - message(FATAL_ERROR "Neither the CRAYOS_VERSION or XTOS_VERSION environment variables are defined. This platform file should be used inside the Cray Linux Environment for targeting compute nodes (NIDs)") +elseif(EXISTS /etc/opt/cray/release/cle-release) + file(STRINGS /etc/opt/cray/release/cle-release release REGEX "^RELEASE=.*") + string(REGEX REPLACE "^RELEASE=(.*)$" "\\1" CMAKE_SYSTEM_VERSION "${release}") + unset(release) +elseif(EXISTS /etc/opt/cray/release/clerelease) + file(READ /etc/opt/cray/release/clerelease CMAKE_SYSTEM_VERSION) endif() # Guard against multiple messages if(NOT __CrayLinuxEnvironment_message) - set(__CrayLinuxEnvironment_message 1) - message(STATUS "Cray Linux Environment ${CMAKE_SYSTEM_VERSION}") + set(__CrayLinuxEnvironment_message 1 CACHE INTERNAL "") + if(NOT CMAKE_SYSTEM_VERSION) + message(STATUS "CrayLinuxEnvironment: Unable to determine CLE version. This platform file should only be used from inside the Cray Linux Environment for targeting compute nodes (NIDs).") + else() + message(STATUS "Cray Linux Environment ${CMAKE_SYSTEM_VERSION}") + endif() endif() # All cray systems are x86 CPUs and have been for quite some time diff --git a/Modules/Platform/Darwin-CXX.cmake b/Modules/Platform/Darwin-Determine-CXX.cmake index bf37f79..bf37f79 100644 --- a/Modules/Platform/Darwin-CXX.cmake +++ b/Modules/Platform/Darwin-Determine-CXX.cmake 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-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..398d6fb 100644 --- a/Modules/Platform/HP-UX-HP.cmake +++ b/Modules/Platform/HP-UX-HP.cmake @@ -27,7 +27,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 index b594dae..b594dae 100644 --- a/Modules/Platform/Linux-CXX.cmake +++ b/Modules/Platform/Linux-Determine-CXX.cmake 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.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/UnixPaths.cmake b/Modules/Platform/UnixPaths.cmake index 20ee1d1..d6c3d41 100644 --- a/Modules/Platform/UnixPaths.cmake +++ b/Modules/Platform/UnixPaths.cmake @@ -93,5 +93,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/CYGWIN-CXX.cmake b/Modules/Platform/Windows-Determine-CXX.cmake index bf37f79..bf37f79 100644 --- a/Modules/Platform/CYGWIN-CXX.cmake +++ b/Modules/Platform/Windows-Determine-CXX.cmake diff --git a/Modules/Platform/Windows-Embarcadero.cmake b/Modules/Platform/Windows-Embarcadero.cmake index 102e3a6..43ae2a3 100644 --- a/Modules/Platform/Windows-Embarcadero.cmake +++ b/Modules/Platform/Windows-Embarcadero.cmake @@ -64,15 +64,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 +128,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-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-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake index 6c254ed..723c69e 100644 --- a/Modules/Platform/Windows-MSVC.cmake +++ b/Modules/Platform/Windows-MSVC.cmake @@ -166,10 +166,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") @@ -235,9 +237,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 +249,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 +289,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_.*") + # 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 +314,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-wcl386.cmake b/Modules/Platform/Windows-OpenWatcom.cmake index 3bc5444..7419fe4 100644 --- a/Modules/Platform/Windows-wcl386.cmake +++ b/Modules/Platform/Windows-OpenWatcom.cmake @@ -1,3 +1,23 @@ + +#============================================================================= +# Copyright 2002-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(__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") @@ -12,14 +32,14 @@ else() set(CMAKE_LIB_QUIET "-q") endif() -set(CMAKE_EXE_LINKER_FLAGS_INIT) +string(APPEND 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") +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) - set(CMAKE_${type}_LINKER_FLAGS_DEBUG_INIT "debug all opt map") - set(CMAKE_${type}_LINKER_FLAGS_RELWITHDEBINFO_INIT "debug all opt map") + 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 @@ -32,13 +52,13 @@ 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") +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) - 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") + 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) 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/Qt4Macros.cmake b/Modules/Qt4Macros.cmake index 3b0a6cc..4b066b74 100644 --- a/Modules/Qt4Macros.cmake +++ b/Modules/Qt4Macros.cmake @@ -441,14 +441,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/UseJava.cmake b/Modules/UseJava.cmake index 7b3416e..f4b5e52 100644 --- a/Modules/UseJava.cmake +++ b/Modules/UseJava.cmake @@ -217,6 +217,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 +241,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>] @@ -396,7 +427,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 +488,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 +522,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 +594,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 +602,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 +648,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 +771,13 @@ function(INSTALL_JAR _TARGET_NAME) PROPERTY INSTALL_FILES ) + set_property( + TARGET + ${_TARGET_NAME} + PROPERTY + INSTALL_DESTINATION + ${_DESTINATION} + ) if (__FILES) install( @@ -1288,3 +1350,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/UseSWIG.cmake b/Modules/UseSWIG.cmake index d757f65..2631ca1 100644 --- a/Modules/UseSWIG.cmake +++ b/Modules/UseSWIG.cmake @@ -163,15 +163,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..597b4ec 100644 --- a/Modules/Use_wxWindows.cmake +++ b/Modules/Use_wxWindows.cmake @@ -68,7 +68,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..4d16482 100644 --- a/Modules/UsewxWidgets.cmake +++ b/Modules/UsewxWidgets.cmake @@ -90,7 +90,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/WriteCompilerDetectionHeader.cmake b/Modules/WriteCompilerDetectionHeader.cmake index 2669a84..4b829e5 100644 --- a/Modules/WriteCompilerDetectionHeader.cmake +++ b/Modules/WriteCompilerDetectionHeader.cmake @@ -282,9 +282,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 +349,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 +406,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 +466,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 +477,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 +487,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 +497,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 +507,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 +521,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 +539,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 +551,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 +561,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 +571,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 +583,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 +593,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 +608,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 +628,7 @@ function(write_compiler_detection_header endif() endforeach() - set(file_content "${file_content}#endif\n") + string(APPEND file_content "#endif\n") endforeach() @@ -637,7 +637,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 +653,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/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 - +@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) + +@__targetdefs__@ +cmake_policy(POP) 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/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..a790994 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -364,6 +364,7 @@ set(SRCS cmake.cxx cmake.h + cm_auto_ptr.hxx cm_get_date.h cm_get_date.c cm_sha2.h @@ -529,11 +530,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) @@ -717,7 +721,9 @@ if(APPLE) CPack/cmCPackBundleGenerator.cxx CPack/cmCPackDragNDropGenerator.cxx CPack/cmCPackOSXX11Generator.cxx + CPack/cmCPackPKGGenerator.cxx CPack/cmCPackPackageMakerGenerator.cxx + CPack/cmCPackProductBuildGenerator.cxx ) endif() @@ -743,6 +749,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 +759,17 @@ endif() # Build CMake executable add_executable(cmake cmakemain.cxx cmcmd.cxx cmcmd.h ${MANIFEST_FILE}) +list(APPEND _tools cmake) target_link_libraries(cmake CMakeLib) # 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 +788,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 c1395e5..58b0448 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 1) -#set(CMake_VERSION_RC 0) +set(CMake_VERSION_PATCH 20160815) +#set(CMake_VERSION_RC 1) diff --git a/Source/CMakeVersionCompute.cmake b/Source/CMakeVersionCompute.cmake index 496d6cf..3bdcfd6 100644 --- a/Source/CMakeVersionCompute.cmake +++ b/Source/CMakeVersionCompute.cmake @@ -3,6 +3,7 @@ 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() @@ -12,9 +13,16 @@ 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..bc5975e 100644 --- a/Source/CMakeVersionSource.cmake +++ b/Source/CMakeVersionSource.cmake @@ -23,7 +23,9 @@ 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) + else() + set(CMake_VERSION_IS_DIRTY 0) endif() endif() endif() diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx index c1ff526..4a5eb90 100644 --- a/Source/CPack/IFW/cmCPackIFWGenerator.cxx +++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx @@ -101,8 +101,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 @@ -178,8 +179,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 +347,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 +392,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 +469,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 +496,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 +528,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 +536,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 +558,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 +569,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..12f2ca6 100644 --- a/Source/CPack/IFW/cmCPackIFWGenerator.h +++ b/Source/CPack/IFW/cmCPackIFWGenerator.h @@ -46,7 +46,7 @@ public: /** * Destruct IFW generator */ - virtual ~cmCPackIFWGenerator(); + ~cmCPackIFWGenerator() CM_OVERRIDE; /** * Compare \a version with QtIFW framework version @@ -70,18 +70,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 +92,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 +104,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..13a3613 100644 --- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx +++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx @@ -33,13 +33,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 @@ -343,6 +343,7 @@ void cmCPackIFWInstaller::GeneratePackageFiles() void cmCPackIFWInstaller::WriteGeneratedByToStrim(cmXMLWriter& xout) { - if (Generator) + if (Generator) { Generator->WriteGeneratedByToStrim(xout); + } } diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx index ad153d1..5db06e6 100644 --- a/Source/CPack/IFW/cmCPackIFWPackage.cxx +++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx @@ -71,8 +71,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 +96,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 +129,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"); @@ -189,8 +191,9 @@ int cmCPackIFWPackage::ConfigureFromOptions() int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component) { - if (!component) + if (!component) { return 0; + } // Restore defaul configuration DefaultConfiguration(); @@ -284,8 +287,9 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component) int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group) { - if (!group) + if (!group) { return 0; + } // Restore defaul configuration DefaultConfiguration(); @@ -418,7 +422,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 +478,7 @@ void cmCPackIFWPackage::GeneratePackageFile() void cmCPackIFWPackage::WriteGeneratedByToStrim(cmXMLWriter& xout) { - if (Generator) + if (Generator) { Generator->WriteGeneratedByToStrim(xout); + } } diff --git a/Source/CPack/IFW/cmCPackIFWRepository.cxx b/Source/CPack/IFW/cmCPackIFWRepository.cxx index 45b47cd..fcb1c77 100644 --- a/Source/CPack/IFW/cmCPackIFWRepository.cxx +++ b/Source/CPack/IFW/cmCPackIFWRepository.cxx @@ -35,7 +35,7 @@ cmCPackIFWRepository::cmCPackIFWRepository() : Update(None) - , Generator(0) + , Generator(CM_NULLPTR) { } @@ -45,16 +45,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 +63,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 +89,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 +177,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 +192,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 +248,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 +336,7 @@ void cmCPackIFWRepository::WriteRepositoryUpdates(cmXMLWriter& xout) void cmCPackIFWRepository::WriteGeneratedByToStrim(cmXMLWriter& xout) { - if (Generator) + if (Generator) { Generator->WriteGeneratedByToStrim(xout); + } } diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx index 19204a2..a233e76 100644 --- a/Source/CPack/OSXScriptLauncher.cxx +++ b/Source/CPack/OSXScriptLauncher.cxx @@ -72,7 +72,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..d7f69a1 100644 --- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx +++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx @@ -18,6 +18,7 @@ #include <cmGeneratedFileStream.h> #include <cmInstalledFile.h> #include <cmSystemTools.h> +#include <cmUuid.h> #include "cmWIXDirectoriesSourceWriter.h" #include "cmWIXFeaturesSourceWriter.h" @@ -90,7 +91,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 +116,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)); @@ -254,7 +255,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 +266,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(); } @@ -403,7 +404,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( @@ -441,6 +442,11 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles() cmWIXFilesSourceWriter fileDefinitions(this->Logger, fileDefinitionsFilename); + // if install folder is supposed to be set absolutely, the default + // component guid "*" cannot be used + fileDefinitions.GenerateComponentGuids = + cmSystemTools::IsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER")); + fileDefinitions.BeginElement("Fragment"); std::string featureDefinitionsFilename = @@ -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 { @@ -1019,7 +1035,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 +1060,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/cmWIXAccessControlList.cxx b/Source/CPack/WiX/cmWIXAccessControlList.cxx index 043cdff..bbbd92d 100644 --- a/Source/CPack/WiX/cmWIXAccessControlList.cxx +++ b/Source/CPack/WiX/cmWIXAccessControlList.cxx @@ -127,7 +127,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/cmWIXDirectoriesSourceWriter.cxx b/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx index 60ecae6..97e3a51 100644 --- a/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx +++ b/Source/CPack/WiX/cmWIXDirectoriesSourceWriter.cxx @@ -52,8 +52,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 +73,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 +81,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/cmWIXFeaturesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx index 16dd0ab..1747b62 100644 --- a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx +++ b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx @@ -86,6 +86,10 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponent( AddAttribute("Display", "hidden"); } + if (component.IsDisabledByDefault) { + AddAttribute("Level", "2"); + } + EndElement("Feature"); } diff --git a/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx index 1341fa5..dde9635 100644 --- a/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx +++ b/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx @@ -16,6 +16,9 @@ #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> @@ -23,6 +26,7 @@ cmWIXFilesSourceWriter::cmWIXFilesSourceWriter(cmCPackLog* logger, std::string const& filename) : cmWIXSourceWriter(logger, filename) + , GenerateComponentGuids(false) { } @@ -31,7 +35,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 +130,20 @@ std::string cmWIXFilesSourceWriter::EmitComponentFile( std::string componentId = std::string("CM_C") + id; std::string fileId = std::string("CM_F") + id; + std::string guid = "*"; + if (this->GenerateComponentGuids) { + std::string md5 = cmSystemTools::ComputeStringMD5(componentId); + cmUuid uuid; + std::vector<unsigned char> ns; + guid = uuid.FromMd5(ns, md5); + } + 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..eeb84cb 100644 --- a/Source/CPack/WiX/cmWIXFilesSourceWriter.h +++ b/Source/CPack/WiX/cmWIXFilesSourceWriter.h @@ -47,6 +47,8 @@ public: std::string const& id, std::string const& filePath, cmWIXPatch& patch, cmInstalledFile const* installedFile); + + bool GenerateComponentGuids; }; #endif diff --git a/Source/CPack/WiX/cmWIXPatchParser.cxx b/Source/CPack/WiX/cmWIXPatchParser.cxx index b750dcf..449a70b 100644 --- a/Source/CPack/WiX/cmWIXPatchParser.cxx +++ b/Source/CPack/WiX/cmWIXPatchParser.cxx @@ -88,7 +88,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/cmCPack7zGenerator.h b/Source/CPack/cmCPack7zGenerator.h index f5a323f..ddbcc34 100644 --- a/Source/CPack/cmCPack7zGenerator.h +++ b/Source/CPack/cmCPack7zGenerator.h @@ -27,10 +27,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..b1f6864 100644 --- a/Source/CPack/cmCPackArchiveGenerator.cxx +++ b/Source/CPack/cmCPackArchiveGenerator.cxx @@ -68,7 +68,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); @@ -139,7 +139,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 @@ -246,7 +246,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] @@ -269,9 +269,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..a018ebd 100644 --- a/Source/CPack/cmCPackArchiveGenerator.h +++ b/Source/CPack/cmCPackArchiveGenerator.h @@ -32,14 +32,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 +55,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 +67,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..9276e3a 100644 --- a/Source/CPack/cmCPackBundleGenerator.cxx +++ b/Source/CPack/cmCPackBundleGenerator.cxx @@ -232,12 +232,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..c6fa408 100644 --- a/Source/CPack/cmCPackBundleGenerator.h +++ b/Source/CPack/cmCPackBundleGenerator.h @@ -29,12 +29,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.h b/Source/CPack/cmCPackComponentGroup.h index 5361d95..01a9e76 100644 --- a/Source/CPack/cmCPackComponentGroup.h +++ b/Source/CPack/cmCPackComponentGroup.h @@ -43,7 +43,7 @@ class cmCPackComponent { public: cmCPackComponent() - : Group(0) + : Group(CM_NULLPTR) , IsRequired(true) , IsHidden(false) , IsDisabledByDefault(false) @@ -117,7 +117,7 @@ class cmCPackComponentGroup { public: cmCPackComponentGroup() - : ParentGroup(0) + : ParentGroup(CM_NULLPTR) { } diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx index 1ad4152..3edc430 100644 --- a/Source/CPack/cmCPackDebGenerator.cxx +++ b/Source/CPack/cmCPackDebGenerator.cxx @@ -57,9 +57,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 +133,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 +174,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; @@ -675,11 +675,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,7 +692,7 @@ 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; @@ -830,8 +826,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 +838,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 +879,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 +891,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 +917,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..bcdc509 100644 --- a/Source/CPack/cmCPackDebGenerator.h +++ b/Source/CPack/cmCPackDebGenerator.h @@ -28,7 +28,7 @@ public: * Construct generator */ cmCPackDebGenerator(); - virtual ~cmCPackDebGenerator(); + ~cmCPackDebGenerator() CM_OVERRIDE; static bool CanGenerate() { @@ -45,7 +45,7 @@ public: } protected: - virtual int InitializeInternal(); + int InitializeInternal() CM_OVERRIDE; /** * This method factors out the work done in component packaging case. */ @@ -62,11 +62,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..640e437 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.cxx +++ b/Source/CPack/cmCPackDragNDropGenerator.cxx @@ -235,7 +235,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); diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h index 1392b21..a5f89f6 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.h +++ b/Source/CPack/cmCPackDragNDropGenerator.h @@ -29,17 +29,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..58a2243 100644 --- a/Source/CPack/cmCPackGenerator.cxx +++ b/Source/CPack/cmCPackGenerator.cxx @@ -34,14 +34,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) @@ -251,8 +251,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 +624,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 +816,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 +831,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 += ";"; @@ -1073,11 +1075,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 +1181,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 +1358,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 +1426,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..23e4bb7 100644 --- a/Source/CPack/cmCPackGenerator.h +++ b/Source/CPack/cmCPackGenerator.h @@ -101,7 +101,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 +136,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..0f0268f 100644 --- a/Source/CPack/cmCPackGeneratorFactory.cxx +++ b/Source/CPack/cmCPackGeneratorFactory.cxx @@ -28,6 +28,7 @@ #include "cmCPackDragNDropGenerator.h" #include "cmCPackOSXX11Generator.h" #include "cmCPackPackageMakerGenerator.h" +#include "cmCPackProductBuildGenerator.h" #endif #ifdef __CYGWIN__ @@ -122,6 +123,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 +151,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 +164,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..f0ed57a 100644 --- a/Source/CPack/cmCPackGeneratorFactory.h +++ b/Source/CPack/cmCPackGeneratorFactory.h @@ -28,7 +28,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..339323e 100644 --- a/Source/CPack/cmCPackLog.cxx +++ b/Source/CPack/cmCPackLog.cxx @@ -28,13 +28,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 +48,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..77f0f0b 100644 --- a/Source/CPack/cmCPackLog.h +++ b/Source/CPack/cmCPackLog.h @@ -42,7 +42,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..d8ff907 100644 --- a/Source/CPack/cmCPackNSISGenerator.cxx +++ b/Source/CPack/cmCPackNSISGenerator.cxx @@ -212,7 +212,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 +301,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 +327,7 @@ int cmCPackNSISGenerator::InitializeInternal() "NSIS Generator cannot work with CPACK_INCLUDE_TOPLEVEL_DIRECTORY set. " "This option will be reset to 0 (for this generator only)." << std::endl); - this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", 0); + this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", CM_NULLPTR); } cmCPackLogger(cmCPackLog::LOG_DEBUG, "cmCPackNSISGenerator::Initialize()" @@ -399,8 +400,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 +518,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 +623,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 "; @@ -873,7 +875,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. diff --git a/Source/CPack/cmCPackNSISGenerator.h b/Source/CPack/cmCPackNSISGenerator.h index fa52902..4923cf0 100644 --- a/Source/CPack/cmCPackNSISGenerator.h +++ b/Source/CPack/cmCPackNSISGenerator.h @@ -36,27 +36,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 +73,7 @@ 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); /// 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..c0d2553 100644 --- a/Source/CPack/cmCPackOSXX11Generator.cxx +++ b/Source/CPack/cmCPackOSXX11Generator.cxx @@ -158,11 +158,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 +180,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 +248,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 +276,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..d1d6789 100644 --- a/Source/CPack/cmCPackOSXX11Generator.h +++ b/Source/CPack/cmCPackOSXX11Generator.h @@ -32,10 +32,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..19b587a --- /dev/null +++ b/Source/CPack/cmCPackPKGGenerator.cxx @@ -0,0 +1,367 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software 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 "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.c_str()); + + 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.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 << 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.c_str(), dst.c_str()); + 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..d2135cc --- /dev/null +++ b/Source/CPack/cmCPackPKGGenerator.h @@ -0,0 +1,96 @@ +/*============================================================================ + 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. +============================================================================*/ + +#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..ce329ca 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.cxx +++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx @@ -17,6 +17,7 @@ #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmSystemTools.h" +#include "cmXMLWriter.h" #include "cmake.h" #include <cmsys/FStream.hxx> @@ -46,21 +47,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 +102,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 +110,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; } } @@ -152,7 +138,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 +148,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 = @@ -184,7 +170,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; } @@ -329,12 +315,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 +330,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 @@ -399,7 +383,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 +417,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 +465,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 +482,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 +507,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 +524,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 +582,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..d1314a4 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.h +++ b/Source/CPack/cmCPackPackageMakerGenerator.h @@ -13,7 +13,7 @@ #ifndef cmCPackPackageMakerGenerator_h #define cmCPackPackageMakerGenerator_h -#include "cmCPackGenerator.h" +#include "cmCPackPKGGenerator.h" class cmCPackComponent; @@ -23,46 +23,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 +53,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..c2a13d0 --- /dev/null +++ b/Source/CPack/cmCPackProductBuildGenerator.cxx @@ -0,0 +1,231 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software 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 "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.c_str()) || + !this->CopyCreateResourceFile("ReadMe", resDir.c_str()) || + !this->CopyCreateResourceFile("Welcome", resDir.c_str())) { + 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.c_str(), preflight, "preinstall"); + } + if (postflight) { + this->CopyInstallScript(scriptDir.c_str(), 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..fd2c090 --- /dev/null +++ b/Source/CPack/cmCPackProductBuildGenerator.h @@ -0,0 +1,58 @@ +/*============================================================================ + 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. +============================================================================*/ + +#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..2568d17 100644 --- a/Source/CPack/cmCPackRPMGenerator.cxx +++ b/Source/CPack/cmCPackRPMGenerator.cxx @@ -121,7 +121,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 @@ -228,11 +228,7 @@ int cmCPackRPMGenerator::PackageFiles() 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,7 +245,7 @@ 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; diff --git a/Source/CPack/cmCPackRPMGenerator.h b/Source/CPack/cmCPackRPMGenerator.h index b39f2c2..4baef08 100644 --- a/Source/CPack/cmCPackRPMGenerator.h +++ b/Source/CPack/cmCPackRPMGenerator.h @@ -32,7 +32,7 @@ public: * Construct generator */ cmCPackRPMGenerator(); - virtual ~cmCPackRPMGenerator(); + ~cmCPackRPMGenerator() CM_OVERRIDE; static bool CanGenerate() { @@ -49,8 +49,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 +67,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.h b/Source/CPack/cmCPackSTGZGenerator.h index 08152b5..94cc8aa 100644 --- a/Source/CPack/cmCPackSTGZGenerator.h +++ b/Source/CPack/cmCPackSTGZGenerator.h @@ -28,13 +28,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.h b/Source/CPack/cmCPackTGZGenerator.h index 408422b..cb7620c 100644 --- a/Source/CPack/cmCPackTGZGenerator.h +++ b/Source/CPack/cmCPackTGZGenerator.h @@ -27,10 +27,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.h b/Source/CPack/cmCPackTXZGenerator.h index 05052a1..87c92ef 100644 --- a/Source/CPack/cmCPackTXZGenerator.h +++ b/Source/CPack/cmCPackTXZGenerator.h @@ -27,10 +27,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.h b/Source/CPack/cmCPackTarBZip2Generator.h index 4033197..6fec882 100644 --- a/Source/CPack/cmCPackTarBZip2Generator.h +++ b/Source/CPack/cmCPackTarBZip2Generator.h @@ -26,10 +26,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.h b/Source/CPack/cmCPackTarCompressGenerator.h index 7ff9a0a..02926a2 100644 --- a/Source/CPack/cmCPackTarCompressGenerator.h +++ b/Source/CPack/cmCPackTarCompressGenerator.h @@ -26,10 +26,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.h b/Source/CPack/cmCPackZIPGenerator.h index 70e1a5f..1130826 100644 --- a/Source/CPack/cmCPackZIPGenerator.h +++ b/Source/CPack/cmCPackZIPGenerator.h @@ -27,10 +27,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..771519c 100644 --- a/Source/CPack/cpack.cxx +++ b/Source/CPack/cpack.cxx @@ -27,13 +27,13 @@ #include <cmsys/SystemTools.hxx> 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,7 +47,7 @@ static const char* cmDocumentationOptions[][2] = { { "-R <package version>", "override/define CPACK_PACKAGE_VERSION" }, { "-B <package directory>", "override/define CPACK_PACKAGE_DIRECTORY" }, { "--vendor <vendor name>", "override/define CPACK_PACKAGE_VENDOR" }, - { 0, 0 } + { CM_NULLPTR, CM_NULLPTR } }; int cpackUnknownArgument(const char*, void*) @@ -185,7 +185,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 +200,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 +209,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/CTest/cmCTestBZR.cxx b/Source/CTest/cmCTestBZR.cxx index dd53be8..0e08e1c 100644 --- a/Source/CTest/cmCTestBZR.cxx +++ b/Source/CTest/cmCTestBZR.cxx @@ -61,8 +61,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 +101,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 +126,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 +139,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 +183,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 +208,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**) CM_OVERRIDE { this->CData.clear(); if (name == "log") { @@ -238,12 +240,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 +275,7 @@ private: this->CData.clear(); } - virtual void ReportError(int, int, const char* msg) + void ReportError(int, int, const char* msg) CM_OVERRIDE { this->BZR->Log << "Error parsing bzr log xml: " << msg << "\n"; } @@ -293,7 +295,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 +326,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 +338,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 +381,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 +409,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 +433,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 +445,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 +467,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..0f05d38 100644 --- a/Source/CTest/cmCTestBZR.h +++ b/Source/CTest/cmCTestBZR.h @@ -24,20 +24,20 @@ 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; diff --git a/Source/CTest/cmCTestBatchTestHandler.cxx b/Source/CTest/cmCTestBatchTestHandler.cxx index 386c8d5..70f84cb 100644 --- a/Source/CTest/cmCTestBatchTestHandler.cxx +++ b/Source/CTest/cmCTestBatchTestHandler.cxx @@ -45,7 +45,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 +73,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..17cc234 100644 --- a/Source/CTest/cmCTestBatchTestHandler.h +++ b/Source/CTest/cmCTestBatchTestHandler.h @@ -28,13 +28,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..eddbddc 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.cxx +++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx @@ -72,7 +72,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(); } @@ -158,10 +158,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 +247,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 +302,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 +321,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 +347,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..2aa90a4 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.h +++ b/Source/CTest/cmCTestBuildAndTestHandler.h @@ -30,12 +30,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 +44,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..408a1a8 100644 --- a/Source/CTest/cmCTestBuildCommand.cxx +++ b/Source/CTest/cmCTestBuildCommand.cxx @@ -19,14 +19,14 @@ 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 +34,7 @@ cmCTestBuildCommand::~cmCTestBuildCommand() { if (this->GlobalGenerator) { delete this->GlobalGenerator; - this->GlobalGenerator = 0; + this->GlobalGenerator = CM_NULLPTR; } } @@ -43,7 +43,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 +91,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 +104,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 +145,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..92ae216 100644 --- a/Source/CTest/cmCTestBuildCommand.h +++ b/Source/CTest/cmCTestBuildCommand.h @@ -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..f96ef6d 100644 --- a/Source/CTest/cmCTestBuildHandler.cxx +++ b/Source/CTest/cmCTestBuildHandler.cxx @@ -92,7 +92,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 +107,7 @@ static const char* cmCTestErrorExceptions[] = { ":[ \\t]+Where:", "([^ :]+):([0-9]+): Warning", "------ Build started: .* ------", - 0 + CM_NULLPTR }; static const char* cmCTestWarningMatches[] = { @@ -132,7 +132,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 +152,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 +170,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() @@ -521,7 +521,7 @@ public: { } FragmentCompare() - : FTC(0) + : FTC(CM_NULLPTR) { } bool operator()(std::string const& l, std::string const& r) @@ -790,7 +790,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 +799,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 +851,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 +870,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 +880,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..8cc5f01 100644 --- a/Source/CTest/cmCTestBuildHandler.h +++ b/Source/CTest/cmCTestBuildHandler.h @@ -36,16 +36,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; } diff --git a/Source/CTest/cmCTestCVS.cxx b/Source/CTest/cmCTestCVS.cxx index 5ddafbb..37bdf9a 100644 --- a/Source/CTest/cmCTestCVS.cxx +++ b/Source/CTest/cmCTestCVS.cxx @@ -53,7 +53,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 +103,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 +140,7 @@ private: SectionType Section; Revision Rev; - virtual bool ProcessLine() + bool ProcessLine() CM_OVERRIDE { if (this->Line == ("=======================================" "======================================")) { @@ -229,7 +229,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..4d5e6a9 100644 --- a/Source/CTest/cmCTestCVS.h +++ b/Source/CTest/cmCTestCVS.h @@ -24,12 +24,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> diff --git a/Source/CTest/cmCTestCommand.h b/Source/CTest/cmCTestCommand.h index 22a2c8e..b0c9206 100644 --- a/Source/CTest/cmCTestCommand.h +++ b/Source/CTest/cmCTestCommand.h @@ -29,8 +29,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..a823704 100644 --- a/Source/CTest/cmCTestConfigureCommand.cxx +++ b/Source/CTest/cmCTestConfigureCommand.cxx @@ -18,7 +18,7 @@ cmCTestConfigureCommand::cmCTestConfigureCommand() { this->Arguments[ctc_OPTIONS] = "OPTIONS"; - this->Arguments[ctc_LAST] = 0; + this->Arguments[ctc_LAST] = CM_NULLPTR; this->Last = ctc_LAST; } @@ -35,7 +35,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 +55,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 +63,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 +90,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 +135,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 +144,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..a97f9f0 100644 --- a/Source/CTest/cmCTestConfigureCommand.h +++ b/Source/CTest/cmCTestConfigureCommand.h @@ -27,7 +27,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 +38,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.h b/Source/CTest/cmCTestConfigureHandler.h index 4c1a96b..a7de939 100644 --- a/Source/CTest/cmCTestConfigureHandler.h +++ b/Source/CTest/cmCTestConfigureHandler.h @@ -29,11 +29,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..86e3ce4 100644 --- a/Source/CTest/cmCTestCoverageCommand.cxx +++ b/Source/CTest/cmCTestCoverageCommand.cxx @@ -30,7 +30,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..ffd5fec 100644 --- a/Source/CTest/cmCTestCoverageCommand.h +++ b/Source/CTest/cmCTestCoverageCommand.h @@ -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..3f37f2a 100644 --- a/Source/CTest/cmCTestCoverageHandler.cxx +++ b/Source/CTest/cmCTestCoverageHandler.cxx @@ -76,7 +76,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 +90,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 +101,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 +702,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 +727,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 @@ -799,7 +789,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") { @@ -1020,7 +1011,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 +1376,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 +1780,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 +1808,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 +1881,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 +2120,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..60fea48 100644 --- a/Source/CTest/cmCTestCoverageHandler.h +++ b/Source/CTest/cmCTestCoverageHandler.h @@ -45,16 +45,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..b335e32 100644 --- a/Source/CTest/cmCTestCurl.cxx +++ b/Source/CTest/cmCTestCurl.cxx @@ -88,10 +88,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 +147,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 +160,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 +205,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 +219,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 +240,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/cmCTestEmptyBinaryDirectoryCommand.h b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h index e904d19..acacbcb 100644 --- a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h +++ b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h @@ -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..61dbe33 100644 --- a/Source/CTest/cmCTestGIT.cxx +++ b/Source/CTest/cmCTestGIT.cxx @@ -52,7 +52,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 +64,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 +94,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 +136,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 +171,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 +206,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 +222,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 +251,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 +260,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 +275,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 +286,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 +294,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 +304,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 +360,7 @@ protected: this->Changes.clear(); } - virtual bool ProcessLine() + bool ProcessLine() CM_OVERRIDE { if (this->Line[0] == ':') { this->DiffField = DiffFieldChange; @@ -513,7 +518,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 +616,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 +644,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..85298cb 100644 --- a/Source/CTest/cmCTestGIT.h +++ b/Source/CTest/cmCTestGIT.h @@ -24,15 +24,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,8 +41,8 @@ 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: diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx index 18caabe..7755ee9 100644 --- a/Source/CTest/cmCTestGenericHandler.cxx +++ b/Source/CTest/cmCTestGenericHandler.cxx @@ -19,7 +19,7 @@ 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 +77,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..9949c3a 100644 --- a/Source/CTest/cmCTestGenericHandler.h +++ b/Source/CTest/cmCTestGenericHandler.h @@ -74,7 +74,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.h b/Source/CTest/cmCTestGlobalVC.h index 9a5357f..7ea3440 100644 --- a/Source/CTest/cmCTestGlobalVC.h +++ b/Source/CTest/cmCTestGlobalVC.h @@ -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..eb3d611 100644 --- a/Source/CTest/cmCTestHG.cxx +++ b/Source/CTest/cmCTestHG.cxx @@ -41,7 +41,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 +65,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 +75,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 +101,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 +129,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 +154,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 +171,7 @@ public: { this->InitializeParser(); } - ~LogParser() { this->CleanupParser(); } + ~LogParser() CM_OVERRIDE { this->CleanupParser(); } private: cmCTestHG* HG; @@ -181,14 +182,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 +201,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 +261,7 @@ private: return output; } - virtual void ReportError(int, int, const char* msg) + void ReportError(int, int, const char* msg) CM_OVERRIDE { this->HG->Log << "Error parsing hg log xml: " << msg << "\n"; } @@ -287,7 +288,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 +304,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..c4ce08c 100644 --- a/Source/CTest/cmCTestHG.h +++ b/Source/CTest/cmCTestHG.h @@ -24,16 +24,16 @@ 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; diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx index 76f971d..e1361a1 100644 --- a/Source/CTest/cmCTestHandlerCommand.cxx +++ b/Source/CTest/cmCTestHandlerCommand.cxx @@ -20,7 +20,7 @@ cmCTestHandlerCommand::cmCTestHandlerCommand() size_t cc; this->Arguments.reserve(INIT_SIZE); for (cc = 0; cc < INIT_SIZE; ++cc) { - this->Arguments.push_back(0); + this->Arguments.push_back(CM_NULLPTR); } this->Arguments[ct_RETURN_VALUE] = "RETURN_VALUE"; this->Arguments[ct_SOURCE] = "SOURCE"; @@ -36,7 +36,7 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args, { // 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; diff --git a/Source/CTest/cmCTestHandlerCommand.h b/Source/CTest/cmCTestHandlerCommand.h index 7248832..0468bbc 100644 --- a/Source/CTest/cmCTestHandlerCommand.h +++ b/Source/CTest/cmCTestHandlerCommand.h @@ -30,8 +30,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); diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx index 4a408a2..3eed79e 100644 --- a/Source/CTest/cmCTestLaunch.cxx +++ b/Source/CTest/cmCTestLaunch.cxx @@ -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(); @@ -128,7 +128,7 @@ bool cmCTestLaunch::ParseArguments(int argc, const char* const* argv) return true; } else { this->RealArgC = 0; - this->RealArgV = 0; + this->RealArgV = CM_NULLPTR; std::cerr << "No launch/command separator ('--') found!\n"; return false; } @@ -227,9 +227,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 +243,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 +384,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 +594,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[]) @@ -616,7 +612,7 @@ int cmCTestLaunch::Main(int argc, const char* const argv[]) #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmake.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> void cmCTestLaunch::LoadConfig() { cmake cm; @@ -624,7 +620,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/cmCTestMemCheckCommand.h b/Source/CTest/cmCTestMemCheckCommand.h index 245892c..2ba33ae 100644 --- a/Source/CTest/cmCTestMemCheckCommand.h +++ b/Source/CTest/cmCTestMemCheckCommand.h @@ -29,7 +29,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 +40,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..dfa8a1a 100644 --- a/Source/CTest/cmCTestMemCheckHandler.cxx +++ b/Source/CTest/cmCTestMemCheckHandler.cxx @@ -42,7 +42,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 +61,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 +72,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&) 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 +241,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 +268,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 +499,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 +523,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())) { @@ -722,10 +723,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 +764,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput( } log = ostr.str(); - if (defects) { - return false; - } - return true; + return defects == 0; } bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput( @@ -904,10 +899,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 +991,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 +1024,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 +1056,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 +1064,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..a005d54 100644 --- a/Source/CTest/cmCTestMemCheckHandler.h +++ b/Source/CTest/cmCTestMemCheckHandler.h @@ -33,16 +33,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 +126,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..a4e0b95 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.cxx +++ b/Source/CTest/cmCTestMultiProcessHandler.cxx @@ -261,12 +261,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 +415,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 +453,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 +468,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 +485,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 +716,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); } diff --git a/Source/CTest/cmCTestP4.cxx b/Source/CTest/cmCTestP4.cxx index 07f9dad..d4a32f1 100644 --- a/Source/CTest/cmCTestP4.cxx +++ b/Source/CTest/cmCTestP4.cxx @@ -45,7 +45,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 +69,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 +92,7 @@ private: cmsys::RegularExpression RegexUser; cmCTestP4* P4; - bool ProcessLine() + bool ProcessLine() CM_OVERRIDE { if (this->RegexUser.find(this->Line)) { User NewUser; @@ -135,7 +135,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 +163,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 +225,7 @@ private: SectionType Section; Revision Rev; - virtual bool ProcessLine() + bool ProcessLine() CM_OVERRIDE { if (this->Line.empty()) { this->NextSection(); @@ -358,7 +358,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); @@ -418,7 +418,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 +426,9 @@ void cmCTestP4::LoadRevisions() ChangeLists.clear(); this->RunChild(&p4_changes[0], &out, &err); - if (ChangeLists.empty()) + if (ChangeLists.empty()) { return; + } // p4 describe -s ...@1111111,2222222 std::vector<char const*> p4_describe; @@ -437,7 +438,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 +457,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 +474,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 +525,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..84e4f96 100644 --- a/Source/CTest/cmCTestP4.h +++ b/Source/CTest/cmCTestP4.h @@ -27,7 +27,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,13 +54,13 @@ 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; diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.cxx b/Source/CTest/cmCTestReadCustomFilesCommand.cxx index 2613c1c..fec23e9 100644 --- a/Source/CTest/cmCTestReadCustomFilesCommand.cxx +++ b/Source/CTest/cmCTestReadCustomFilesCommand.cxx @@ -16,7 +16,7 @@ bool cmCTestReadCustomFilesCommand::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/CTest/cmCTestReadCustomFilesCommand.h b/Source/CTest/cmCTestReadCustomFilesCommand.h index 713fc66..6cce7c8 100644 --- a/Source/CTest/cmCTestReadCustomFilesCommand.h +++ b/Source/CTest/cmCTestReadCustomFilesCommand.h @@ -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..6b5e6ed 100644 --- a/Source/CTest/cmCTestRunScriptCommand.cxx +++ b/Source/CTest/cmCTestRunScriptCommand.cxx @@ -16,7 +16,7 @@ bool cmCTestRunScriptCommand::InitialPass(std::vector<std::string> const& args, cmExecutionStatus&) { - 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..9ea0999 100644 --- a/Source/CTest/cmCTestRunScriptCommand.h +++ b/Source/CTest/cmCTestRunScriptCommand.h @@ -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..9e3802a 100644 --- a/Source/CTest/cmCTestRunTest.cxx +++ b/Source/CTest/cmCTestRunTest.cxx @@ -24,12 +24,12 @@ 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; @@ -207,7 +207,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; @@ -537,7 +538,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 +577,7 @@ double cmCTestRunTest::ResolveTimeout() return timeout; } struct tm* lctime; - time_t current_time = time(0); + time_t current_time = time(CM_NULLPTR); lctime = gmtime(¤t_time); int gm_hour = lctime->tm_hour; time_t gm_time = mktime(lctime); diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx index a6885aa..eae0c6c 100644 --- a/Source/CTest/cmCTestSVN.cxx +++ b/Source/CTest/cmCTestSVN.cxx @@ -62,7 +62,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); @@ -206,7 +206,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 +271,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,7 +291,7 @@ 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); @@ -310,7 +311,7 @@ public: { this->InitializeParser(); } - ~LogParser() { this->CleanupParser(); } + ~LogParser() CM_OVERRIDE { this->CleanupParser(); } private: cmCTestSVN* SVN; cmCTestSVN::SVNInfo& SVNRepo; @@ -322,14 +323,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 +348,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 +372,7 @@ private: this->CData.clear(); } - virtual void ReportError(int, int, const char* msg) + void ReportError(int, int, const char* msg) CM_OVERRIDE { this->SVN->Log << "Error parsing svn log xml: " << msg << "\n"; } @@ -440,7 +441,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 +506,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)); diff --git a/Source/CTest/cmCTestSVN.h b/Source/CTest/cmCTestSVN.h index e596bdc..4f3eb88 100644 --- a/Source/CTest/cmCTestSVN.h +++ b/Source/CTest/cmCTestSVN.h @@ -26,14 +26,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); @@ -78,8 +78,8 @@ private: std::string LoadInfo(SVNInfo& svninfo); void LoadExternals(); - void LoadModifications(); - void LoadRevisions(); + void LoadModifications() CM_OVERRIDE; + void LoadRevisions() CM_OVERRIDE; void LoadRevisions(SVNInfo& svninfo); void GuessBase(SVNInfo& svninfo, std::vector<Change> const& changes); @@ -87,7 +87,7 @@ private: void DoRevisionSVN(Revision const& revision, std::vector<Change> const& changes); - void WriteXMLGlobal(cmXMLWriter& xml); + void WriteXMLGlobal(cmXMLWriter& xml) CM_OVERRIDE; // Parsing helper classes. class InfoParser; diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx index 6389a9d..b747c64 100644 --- a/Source/CTest/cmCTestScriptHandler.cxx +++ b/Source/CTest/cmCTestScriptHandler.cxx @@ -59,9 +59,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&) CM_OVERRIDE; // virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile &mf); // virtual void ScopeEnded(cmMakefile &mf); @@ -82,9 +82,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 +121,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 +200,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 +226,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; @@ -863,7 +863,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..4403030 100644 --- a/Source/CTest/cmCTestScriptHandler.h +++ b/Source/CTest/cmCTestScriptHandler.h @@ -71,7 +71,7 @@ public: /** * Run a dashboard using a specified confiuration script */ - int ProcessHandler(); + int ProcessHandler() CM_OVERRIDE; /* * Run a script @@ -104,9 +104,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..a6dd6bc 100644 --- a/Source/CTest/cmCTestSleepCommand.cxx +++ b/Source/CTest/cmCTestSleepCommand.cxx @@ -17,7 +17,7 @@ bool cmCTestSleepCommand::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/CTest/cmCTestSleepCommand.h b/Source/CTest/cmCTestSleepCommand.h index ff7f146..7981fa2 100644 --- a/Source/CTest/cmCTestSleepCommand.h +++ b/Source/CTest/cmCTestSleepCommand.h @@ -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..c64d16b 100644 --- a/Source/CTest/cmCTestStartCommand.cxx +++ b/Source/CTest/cmCTestStartCommand.cxx @@ -25,19 +25,19 @@ cmCTestStartCommand::cmCTestStartCommand() bool cmCTestStartCommand::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; } 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..e3f8f8b 100644 --- a/Source/CTest/cmCTestStartCommand.h +++ b/Source/CTest/cmCTestStartCommand.h @@ -27,7 +27,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 +41,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 +57,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..54da383 100644 --- a/Source/CTest/cmCTestSubmitCommand.cxx +++ b/Source/CTest/cmCTestSubmitCommand.cxx @@ -88,7 +88,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler() extraFiles.end()); if (!this->CTest->SubmitExtraFiles(newExtraFiles)) { this->SetError("problem submitting extra files."); - return 0; + return CM_NULLPTR; } } @@ -96,7 +96,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..7c3d6cd 100644 --- a/Source/CTest/cmCTestSubmitCommand.h +++ b/Source/CTest/cmCTestSubmitCommand.h @@ -38,7 +38,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 +46,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..67388ad 100644 --- a/Source/CTest/cmCTestSubmitHandler.cxx +++ b/Source/CTest/cmCTestSubmitHandler.cxx @@ -41,7 +41,7 @@ class cmCTestSubmitHandler::ResponseParser : public cmXMLParser { public: ResponseParser() { this->Status = STATUS_OK; } - ~ResponseParser() {} + ~ResponseParser() CM_OVERRIDE {} public: enum StatusType @@ -69,7 +69,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 +77,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()); @@ -150,7 +150,7 @@ void cmCTestSubmitHandler::Initialize() this->HTTPProxyAuth = ""; this->FTPProxy = ""; this->FTPProxyType = 0; - this->LogFile = 0; + this->LogFile = CM_NULLPTR; this->Files.clear(); } @@ -308,7 +308,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 +507,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 +776,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 +807,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 +845,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 +867,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 +879,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 +902,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 +913,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 +926,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 +943,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); @@ -999,12 +991,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..4cca6eb 100644 --- a/Source/CTest/cmCTestSubmitHandler.h +++ b/Source/CTest/cmCTestSubmitHandler.h @@ -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); diff --git a/Source/CTest/cmCTestTestCommand.cxx b/Source/CTest/cmCTestTestCommand.cxx index 7b437c6..1d064db 100644 --- a/Source/CTest/cmCTestTestCommand.cxx +++ b/Source/CTest/cmCTestTestCommand.cxx @@ -27,7 +27,7 @@ cmCTestTestCommand::cmCTestTestCommand() this->Arguments[ctt_SCHEDULE_RANDOM] = "SCHEDULE_RANDOM"; this->Arguments[ctt_STOP_TIME] = "STOP_TIME"; this->Arguments[ctt_TEST_LOAD] = "TEST_LOAD"; - this->Arguments[ctt_LAST] = 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..f652971 100644 --- a/Source/CTest/cmCTestTestCommand.h +++ b/Source/CTest/cmCTestTestCommand.h @@ -27,7 +27,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 +38,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..cd250fb 100644 --- a/Source/CTest/cmCTestTestHandler.cxx +++ b/Source/CTest/cmCTestTestHandler.cxx @@ -42,7 +42,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 +53,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&) 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); @@ -69,7 +69,7 @@ public: bool cmCTestSubdirCommand::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; } @@ -123,7 +123,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 +134,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&) 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); @@ -150,7 +150,7 @@ public: bool cmCTestAddSubdirectoryCommand::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; } @@ -197,7 +197,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 +208,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&, + cmExecutionStatus&) 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); @@ -237,7 +237,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 +248,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&, + cmExecutionStatus&) 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); @@ -336,7 +336,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 +550,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 +558,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; } @@ -936,7 +936,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(); @@ -1125,7 +1125,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 +1154,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 +1322,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 +1352,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 +1407,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 +1678,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) { diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h index 4b74ce0..a085a82 100644 --- a/Source/CTest/cmCTestTestHandler.h +++ b/Source/CTest/cmCTestTestHandler.h @@ -36,7 +36,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 +54,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 +90,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 diff --git a/Source/CTest/cmCTestUpdateCommand.cxx b/Source/CTest/cmCTestUpdateCommand.cxx index f1bae5d..bc06da6 100644 --- a/Source/CTest/cmCTestUpdateCommand.cxx +++ b/Source/CTest/cmCTestUpdateCommand.cxx @@ -83,12 +83,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..6b5bbab 100644 --- a/Source/CTest/cmCTestUpdateCommand.h +++ b/Source/CTest/cmCTestUpdateCommand.h @@ -27,7 +27,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 +38,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..ac7eb05 100644 --- a/Source/CTest/cmCTestUpdateHandler.cxx +++ b/Source/CTest/cmCTestUpdateHandler.cxx @@ -30,7 +30,7 @@ #include "cmCTestSVN.h" #include "cmCTestVC.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> //#include <cmsys/RegularExpression.hxx> #include <cmsys/Process.h> @@ -159,7 +159,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 +334,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..6733c8c 100644 --- a/Source/CTest/cmCTestUpdateHandler.h +++ b/Source/CTest/cmCTestUpdateHandler.h @@ -29,7 +29,7 @@ public: /* * The main entry point for this class */ - int ProcessHandler(); + int ProcessHandler() CM_OVERRIDE; cmCTestUpdateHandler(); @@ -48,7 +48,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..7393d21 100644 --- a/Source/CTest/cmCTestUploadCommand.cxx +++ b/Source/CTest/cmCTestUploadCommand.cxx @@ -21,7 +21,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); diff --git a/Source/CTest/cmCTestUploadCommand.h b/Source/CTest/cmCTestUploadCommand.h index 551be2b..923995d 100644 --- a/Source/CTest/cmCTestUploadCommand.h +++ b/Source/CTest/cmCTestUploadCommand.h @@ -30,7 +30,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,15 +41,15 @@ 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 { diff --git a/Source/CTest/cmCTestUploadHandler.h b/Source/CTest/cmCTestUploadHandler.h index 23ed35a..8b824d6 100644 --- a/Source/CTest/cmCTestUploadHandler.h +++ b/Source/CTest/cmCTestUploadHandler.h @@ -26,14 +26,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..3376588 100644 --- a/Source/CTest/cmCTestVC.cxx +++ b/Source/CTest/cmCTestVC.cxx @@ -65,7 +65,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"; diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h index 4ae38eb..eb85a236 100644 --- a/Source/CTest/cmCTestVC.h +++ b/Source/CTest/cmCTestVC.h @@ -104,8 +104,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 +121,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/cmParseCacheCoverage.h b/Source/CTest/cmParseCacheCoverage.h index bd331d0..65b1d10 100644 --- a/Source/CTest/cmParseCacheCoverage.h +++ b/Source/CTest/cmParseCacheCoverage.h @@ -28,7 +28,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..1a3fe3c 100644 --- a/Source/CTest/cmParseCoberturaCoverage.cxx +++ b/Source/CTest/cmParseCoberturaCoverage.cxx @@ -20,10 +20,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 +34,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 +46,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/cmParseGTMCoverage.h b/Source/CTest/cmParseGTMCoverage.h index bc2f2ec..4188689 100644 --- a/Source/CTest/cmParseGTMCoverage.h +++ b/Source/CTest/cmParseGTMCoverage.h @@ -28,7 +28,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..9325812 100644 --- a/Source/CTest/cmParseJacocoCoverage.cxx +++ b/Source/CTest/cmParseJacocoCoverage.cxx @@ -20,12 +20,12 @@ public: this->PackageName = ""; } - virtual ~XMLParser() {} + ~XMLParser() CM_OVERRIDE {} protected: - virtual void EndElement(const std::string&) {} + void EndElement(const std::string&) 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 +111,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/cmParseMumpsCoverage.cxx b/Source/CTest/cmParseMumpsCoverage.cxx index e5dd74a..d786d79 100644 --- a/Source/CTest/cmParseMumpsCoverage.cxx +++ b/Source/CTest/cmParseMumpsCoverage.cxx @@ -130,8 +130,8 @@ bool cmParseMumpsCoverage::FindMumpsFile(std::string const& routine, return true; } else { // try some alternate names - const char* tryname[] = { "GUX", "GTM", "ONT", 0 }; - for (int k = 0; tryname[k] != 0; k++) { + 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()) { diff --git a/Source/CTest/cmParsePHPCoverage.cxx b/Source/CTest/cmParsePHPCoverage.cxx index eb0d962..5ec2718 100644 --- a/Source/CTest/cmParsePHPCoverage.cxx +++ b/Source/CTest/cmParsePHPCoverage.cxx @@ -27,10 +27,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/cmProcess.cxx b/Source/CTest/cmProcess.cxx index db5151c..92fe642 100644 --- a/Source/CTest/cmProcess.cxx +++ b/Source/CTest/cmProcess.cxx @@ -16,7 +16,7 @@ cmProcess::cmProcess() { - this->Process = 0; + this->Process = CM_NULLPTR; this->Timeout = 0; this->TotalTime = 0; this->ExitValue = 0; @@ -52,7 +52,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()) { 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_features.cmake b/Source/Checks/cm_cxx_features.cmake new file mode 100644 index 0000000..6fde7b6 --- /dev/null +++ b/Source/Checks/cm_cxx_features.cmake @@ -0,0 +1,39 @@ + +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(nullptr) + cm_check_cxx_feature(override) + cm_check_cxx_feature(unordered_map) + cm_check_cxx_feature(unordered_set) +endif() 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_cxx11_unordered_map.cpp b/Source/Checks/cm_cxx_unordered_map.cxx index be3de25..be3de25 100644 --- a/Source/Checks/cm_cxx11_unordered_map.cpp +++ b/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..55599b6 100644 --- a/Source/CursesDialog/CMakeLists.txt +++ b/Source/CursesDialog/CMakeLists.txt @@ -48,4 +48,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..606c954 100644 --- a/Source/CursesDialog/ccmake.cxx +++ b/Source/CursesDialog/ccmake.cxx @@ -24,29 +24,30 @@ #include <form.h> 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" { @@ -176,7 +177,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..e36ac34 100644 --- a/Source/CursesDialog/cmCursesBoolWidget.cxx +++ b/Source/CursesDialog/cmCursesBoolWidget.cxx @@ -27,8 +27,9 @@ cmCursesBoolWidget::cmCursesBoolWidget(int width, int height, int left, bool cmCursesBoolWidget::HandleInput(int& key, cmCursesMainForm*, 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 { @@ -54,9 +55,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..d2899ee 100644 --- a/Source/CursesDialog/cmCursesBoolWidget.h +++ b/Source/CursesDialog/cmCursesBoolWidget.h @@ -25,7 +25,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..ea12756 100644 --- a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx +++ b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx @@ -32,7 +32,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 +50,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)) { @@ -111,6 +111,6 @@ const char* cmCursesCacheEntryComposite::GetValue() if (this->Label) { return this->Label->GetValue(); } else { - return 0; + return CM_NULLPTR; } } diff --git a/Source/CursesDialog/cmCursesDummyWidget.h b/Source/CursesDialog/cmCursesDummyWidget.h index 9a3df29..e6ca91e 100644 --- a/Source/CursesDialog/cmCursesDummyWidget.h +++ b/Source/CursesDialog/cmCursesDummyWidget.h @@ -25,7 +25,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/cmCursesForm.cxx b/Source/CursesDialog/cmCursesForm.cxx index aa4710f..b3320c9 100644 --- a/Source/CursesDialog/cmCursesForm.cxx +++ b/Source/CursesDialog/cmCursesForm.cxx @@ -16,7 +16,7 @@ bool cmCursesForm::Debug = false; cmCursesForm::cmCursesForm() { - this->Form = 0; + this->Form = CM_NULLPTR; } cmCursesForm::~cmCursesForm() @@ -24,7 +24,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/cmCursesLabelWidget.h b/Source/CursesDialog/cmCursesLabelWidget.h index c31a58c..ff645af 100644 --- a/Source/CursesDialog/cmCursesLabelWidget.h +++ b/Source/CursesDialog/cmCursesLabelWidget.h @@ -21,13 +21,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..48cc42c 100644 --- a/Source/CursesDialog/cmCursesLongMessageForm.cxx +++ b/Source/CursesDialog/cmCursesLongMessageForm.cxx @@ -32,8 +32,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 +54,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; @@ -110,7 +110,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 +119,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..a12ed2f 100644 --- a/Source/CursesDialog/cmCursesLongMessageForm.h +++ b/Source/CursesDialog/cmCursesLongMessageForm.h @@ -23,16 +23,16 @@ 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 +42,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..964f3af 100644 --- a/Source/CursesDialog/cmCursesMainForm.cxx +++ b/Source/CursesDialog/cmCursesMainForm.cxx @@ -36,8 +36,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 +64,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 +75,7 @@ cmCursesMainForm::~cmCursesMainForm() delete this->Entries; if (this->CMakeInstance) { delete this->CMakeInstance; - this->CMakeInstance = 0; + this->CMakeInstance = CM_NULLPTR; } } @@ -185,7 +185,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 +215,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 +244,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 +263,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 +345,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 +388,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 +434,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 +566,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 +583,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 +638,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*/ @@ -837,7 +837,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 +856,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 +891,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 +976,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 +1006,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) { @@ -1052,7 +1055,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 +1125,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 +1144,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 +1151,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..d17ee33 100644 --- a/Source/CursesDialog/cmCursesMainForm.h +++ b/Source/CursesDialog/cmCursesMainForm.h @@ -30,7 +30,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 +40,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 +67,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 +83,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.h b/Source/CursesDialog/cmCursesOptionsWidget.h index a17f2d5..f88b6bc 100644 --- a/Source/CursesDialog/cmCursesOptionsWidget.h +++ b/Source/CursesDialog/cmCursesOptionsWidget.h @@ -25,7 +25,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.h b/Source/CursesDialog/cmCursesPathWidget.h index 18d298a..cd26df6 100644 --- a/Source/CursesDialog/cmCursesPathWidget.h +++ b/Source/CursesDialog/cmCursesPathWidget.h @@ -23,9 +23,9 @@ public: * This method is called when different keys are pressed. The * subclass can have a special implementation handler for this. */ - 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/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx index 3707d0d..46b8b86 100644 --- a/Source/CursesDialog/cmCursesStringWidget.cxx +++ b/Source/CursesDialog/cmCursesStringWidget.cxx @@ -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]; @@ -97,11 +99,15 @@ bool cmCursesStringWidget::HandleInput(int& key, cmCursesMainForm* fm, } // 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') || diff --git a/Source/CursesDialog/cmCursesStringWidget.h b/Source/CursesDialog/cmCursesStringWidget.h index fc1b2ba..c8ca482 100644 --- a/Source/CursesDialog/cmCursesStringWidget.h +++ b/Source/CursesDialog/cmCursesStringWidget.h @@ -32,14 +32,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 +61,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..49f2795 100644 --- a/Source/CursesDialog/cmCursesWidget.cxx +++ b/Source/CursesDialog/cmCursesWidget.cxx @@ -23,7 +23,7 @@ cmCursesWidget::~cmCursesWidget() { if (this->Field) { free_field(this->Field); - this->Field = 0; + this->Field = CM_NULLPTR; } } diff --git a/Source/QtDialog/CMakeLists.txt b/Source/QtDialog/CMakeLists.txt index a906f4a..80c0dc0 100644 --- a/Source/QtDialog/CMakeLists.txt +++ b/Source/QtDialog/CMakeLists.txt @@ -36,6 +36,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 +156,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..ee3389c 100644 --- a/Source/QtDialog/CMakeSetup.cxx +++ b/Source/QtDialog/CMakeSetup.cxx @@ -22,6 +22,7 @@ #include <QString> #include <QTextCodec> #include <QTranslator> +#include <QtPlugin> #include <cmsys/CommandLineArguments.hxx> #include <cmsys/Encoding.hxx> #include <cmsys/SystemTools.hxx> @@ -44,6 +45,10 @@ 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 = diff --git a/Source/QtDialog/CMakeSetupDialog.cxx b/Source/QtDialog/CMakeSetupDialog.cxx index 712611d..fda3e58 100644 --- a/Source/QtDialog/CMakeSetupDialog.cxx +++ b/Source/QtDialog/CMakeSetupDialog.cxx @@ -830,17 +830,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 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..181cb77 100644 --- a/Source/bindexplib.cxx +++ b/Source/bindexplib.cxx @@ -244,9 +244,7 @@ public: *---------------------------------------------------------------------- */ void DumpObjFile() { - if(!HaveExportedObjects()) { - this->DumpExternalsObjects(); - } + this->DumpExternalsObjects(); } /* diff --git a/Source/cmAddCompileOptionsCommand.h b/Source/cmAddCompileOptionsCommand.h index 5c073c8..dba1acd 100644 --- a/Source/cmAddCompileOptionsCommand.h +++ b/Source/cmAddCompileOptionsCommand.h @@ -20,19 +20,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..400be77 100644 --- a/Source/cmAddCustomCommandCommand.cxx +++ b/Source/cmAddCustomCommandCommand.cxx @@ -30,7 +30,7 @@ bool cmAddCustomCommandCommand::InitialPass( std::string source, target, main_dependency, working; 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; diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h index ccbd50c..1164d46 100644 --- a/Source/cmAddCustomCommandCommand.h +++ b/Source/cmAddCustomCommandCommand.h @@ -26,19 +26,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..9dc7c59 100644 --- a/Source/cmAddCustomTargetCommand.cxx +++ b/Source/cmAddCustomTargetCommand.cxx @@ -47,7 +47,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..120d4d4 100644 --- a/Source/cmAddCustomTargetCommand.h +++ b/Source/cmAddCustomTargetCommand.h @@ -27,19 +27,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.h b/Source/cmAddDefinitionsCommand.h index 959ed64..b30001c 100644 --- a/Source/cmAddDefinitionsCommand.h +++ b/Source/cmAddDefinitionsCommand.h @@ -26,19 +26,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.h b/Source/cmAddDependenciesCommand.h index 202d072..c059ff2 100644 --- a/Source/cmAddDependenciesCommand.h +++ b/Source/cmAddDependenciesCommand.h @@ -25,19 +25,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.h b/Source/cmAddExecutableCommand.h index 1e3181f..133f5bf 100644 --- a/Source/cmAddExecutableCommand.h +++ b/Source/cmAddExecutableCommand.h @@ -26,19 +26,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.h b/Source/cmAddLibraryCommand.h index 0f0f768..20f1bc9 100644 --- a/Source/cmAddLibraryCommand.h +++ b/Source/cmAddLibraryCommand.h @@ -26,19 +26,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.h b/Source/cmAddSubDirectoryCommand.h index 786c8b0..ec1d2c8 100644 --- a/Source/cmAddSubDirectoryCommand.h +++ b/Source/cmAddSubDirectoryCommand.h @@ -27,19 +27,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.h b/Source/cmAddTestCommand.h index 295fb78..abff0c2 100644 --- a/Source/cmAddTestCommand.h +++ b/Source/cmAddTestCommand.h @@ -25,19 +25,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/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx index a0150ec..ceb7d31 100644 --- a/Source/cmArchiveWrite.cxx +++ b/Source/cmArchiveWrite.cxx @@ -151,9 +151,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 +229,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 +256,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()); } diff --git a/Source/cmArchiveWrite.h b/Source/cmArchiveWrite.h index 72d8f3a..f847d09 100644 --- a/Source/cmArchiveWrite.h +++ b/Source/cmArchiveWrite.h @@ -72,13 +72,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. */ diff --git a/Source/cmAuxSourceDirectoryCommand.h b/Source/cmAuxSourceDirectoryCommand.h index b5943f5..6301cb2 100644 --- a/Source/cmAuxSourceDirectoryCommand.h +++ b/Source/cmAuxSourceDirectoryCommand.h @@ -29,19 +29,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/cmBreakCommand.h b/Source/cmBreakCommand.h index 270d3e6..3b585e2 100644 --- a/Source/cmBreakCommand.h +++ b/Source/cmBreakCommand.h @@ -25,24 +25,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..9830867 100644 --- a/Source/cmBuildCommand.cxx +++ b/Source/cmBuildCommand.cxx @@ -36,8 +36,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 +56,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 +76,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 +91,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 +109,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..552e5ff 100644 --- a/Source/cmBuildCommand.h +++ b/Source/cmBuildCommand.h @@ -25,14 +25,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 +47,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.h b/Source/cmBuildNameCommand.h index 43c24b0..4a1641bd 100644 --- a/Source/cmBuildNameCommand.h +++ b/Source/cmBuildNameCommand.h @@ -18,11 +18,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..e4c74ec 100644 --- a/Source/cmCLocaleEnvironmentScope.cxx +++ b/Source/cmCLocaleEnvironmentScope.cxx @@ -31,8 +31,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 +46,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 +56,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/cmCMakeHostSystemInformationCommand.cxx b/Source/cmCMakeHostSystemInformationCommand.cxx index fbec6fd..fdbd5e7 100644 --- a/Source/cmCMakeHostSystemInformationCommand.cxx +++ b/Source/cmCMakeHostSystemInformationCommand.cxx @@ -84,7 +84,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..8e6f0f5 100644 --- a/Source/cmCMakeHostSystemInformationCommand.h +++ b/Source/cmCMakeHostSystemInformationCommand.h @@ -28,7 +28,7 @@ public: /** * This is a virtual constructor for the command. */ - virtual cmCommand* Clone() + cmCommand* Clone() CM_OVERRIDE { return new cmCMakeHostSystemInformationCommand; } @@ -37,18 +37,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.h b/Source/cmCMakeMinimumRequired.h index fc73e87..4231eb4 100644 --- a/Source/cmCMakeMinimumRequired.h +++ b/Source/cmCMakeMinimumRequired.h @@ -25,24 +25,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.h b/Source/cmCMakePolicyCommand.h index dbb91d5..fd4ab0a 100644 --- a/Source/cmCMakePolicyCommand.h +++ b/Source/cmCMakePolicyCommand.h @@ -26,24 +26,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.h b/Source/cmCPackPropertiesGenerator.h index 4372b87..4d092f6 100644 --- a/Source/cmCPackPropertiesGenerator.h +++ b/Source/cmCPackPropertiesGenerator.h @@ -29,9 +29,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..f97791a 100644 --- a/Source/cmCPluginAPI.cxx +++ b/Source/cmCPluginAPI.cxx @@ -218,8 +218,8 @@ void CCONV cmAddUtilityCommand(void* arg, const char* utilityName, } // Pass the call to the makefile instance. - mf->AddUtilityCommand(utilityName, (all ? false : true), 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 +257,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 +291,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 +333,8 @@ void CCONV cmAddCustomCommandToTarget(void* arg, const char* target, // Pass the call to the makefile instance. std::vector<std::string> no_byproducts; std::vector<std::string> no_depends; - const char* no_comment = 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 +414,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 +453,7 @@ int CCONV cmGetTotalArgumentSize(int argc, char** argv) struct cmCPluginAPISourceFile { cmCPluginAPISourceFile() - : RealSourceFile(0) + : RealSourceFile(CM_NULLPTR) { } cmSourceFile* RealSourceFile; @@ -525,7 +525,7 @@ void CCONV* cmGetSource(void* arg, const char* name) } return (void*)i->second; } else { - return 0; + return CM_NULLPTR; } } @@ -534,7 +534,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. diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx index bc36c5a..8a856a8 100644 --- a/Source/cmCTest.cxx +++ b/Source/cmCTest.cxx @@ -51,7 +51,7 @@ #include <math.h> #include <stdlib.h> -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> #include <cm_zlib.h> #include <cmsys/Base64.h> @@ -70,7 +70,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 +88,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 +134,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(¤ttime); // return ::CleanString(ctime(¤ttime)); char current_time[1024]; @@ -244,7 +244,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 +288,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 +298,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 +348,7 @@ cmCTest::cmCTest() cmCTest::~cmCTest() { cmDeleteAll(this->TestingHandlers); - this->SetOutputLogFileName(0); + this->SetOutputLogFileName(CM_NULLPTR); } void cmCTest::SetParallelLevel(int level) @@ -365,11 +366,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 +472,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 +513,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 +538,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 +560,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, @@ -860,7 +858,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 +869,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 +884,7 @@ int cmCTest::ExecuteHandler(const char* shandler) return handler->ProcessHandler(); } -int cmCTest::ProcessTests() +int cmCTest::ProcessSteps() { int res = 0; bool notest = true; @@ -1020,7 +1018,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 +1027,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 +1055,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 +1080,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 +1163,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 +1191,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 +1209,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 +1219,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 +1243,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); @@ -2018,7 +2016,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 +2042,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 +2068,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 +2087,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 +2359,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 +2409,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(¤t_time); int gm_hour = lctime->tm_hour; time_t gm_time = mktime(lctime); @@ -2459,7 +2493,7 @@ bool cmCTest::GetProduceXML() const char* cmCTest::GetSpecificTrack() { if (this->SpecificTrack.empty()) { - return 0; + return CM_NULLPTR; } return this->SpecificTrack.c_str(); } @@ -2525,7 +2559,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 +2568,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 +2589,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 +2606,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 +2648,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 +2662,7 @@ static const char* cmCTestStringLogType[] = { "DEBUG", "HANDLER_VERBOSE_OUTPUT", "WARNING", "ERROR_MESSAGE", - 0 }; + CM_NULLPTR }; #ifdef cerr #undef cerr diff --git a/Source/cmCTest.h b/Source/cmCTest.h index 65ecaa4..b6657c9 100644 --- a/Source/cmCTest.h +++ b/Source/cmCTest.h @@ -53,6 +53,13 @@ class cmXMLWriter; #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 +126,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 +136,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 +169,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 +214,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 +236,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 +258,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 +287,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 +330,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 +342,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 +362,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 +376,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 +424,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 +440,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 +450,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 +478,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 +519,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 +583,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..bdd7303 100644 --- a/Source/cmCacheManager.cxx +++ b/Source/cmCacheManager.cxx @@ -71,8 +71,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 +179,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 +447,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 +462,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 +540,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,6 +564,11 @@ 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 { @@ -605,7 +616,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 +653,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..2331867 100644 --- a/Source/cmCacheManager.h +++ b/Source/cmCacheManager.h @@ -38,6 +38,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 +61,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 +113,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 +128,7 @@ public: { cmCacheManager::CacheIterator it = this->GetCacheIterator(key.c_str()); if (it.IsAtEnd()) { - return 0; + return CM_NULLPTR; } return it.GetValue(); } @@ -169,7 +171,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..515699d 100644 --- a/Source/cmCallVisualStudioMacro.cxx +++ b/Source/cmCallVisualStudioMacro.cxx @@ -105,8 +105,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/cmCommand.h b/Source/cmCommand.h index 0157293..a5f20e6 100644 --- a/Source/cmCommand.h +++ b/Source/cmCommand.h @@ -38,14 +38,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/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx index a4f3c7d..42fb105 100644 --- a/Source/cmCommandArgumentParserHelper.cxx +++ b/Source/cmCommandArgumentParserHelper.cxx @@ -25,7 +25,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,12 +71,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)); + return this->AddString(cmSystemTools::EscapeQuotes(str.c_str())); } else { - return ptr; + return this->AddString(str); } } return this->EmptyVariable; @@ -96,13 +96,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 +125,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)); @@ -176,7 +176,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)); } diff --git a/Source/cmCommandArgumentsHelper.cxx b/Source/cmCommandArgumentsHelper.cxx index c336bc5..1345bd5 100644 --- a/Source/cmCommandArgumentsHelper.cxx +++ b/Source/cmCommandArgumentsHelper.cxx @@ -21,11 +21,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 +45,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()); @@ -69,7 +69,7 @@ bool cmCommandArgument::MayFollow(const cmCommandArgument* current) const 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 +77,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 +105,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 +117,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 +134,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 +216,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 +227,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 +246,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..9133148 100644 --- a/Source/cmCommandArgumentsHelper.h +++ b/Source/cmCommandArgumentsHelper.h @@ -43,7 +43,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 +95,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 +108,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 +118,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 +126,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 +137,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 +154,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/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx index c630971..7ad18f0 100644 --- a/Source/cmCommonTargetGenerator.cxx +++ b/Source/cmCommonTargetGenerator.cxx @@ -19,17 +19,14 @@ #include "cmSourceFile.h" #include "cmSystemTools.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) { } @@ -91,99 +88,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 +115,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 +135,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; @@ -367,7 +197,8 @@ std::string cmCommonTargetGenerator::GetManifests() 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)); + (*mi)->GetFullPath(), this->LocalGenerator->GetWorkingDirectory(), + cmOutputConverter::SHELL)); } return cmJoin(manifests, " "); diff --git a/Source/cmCommonTargetGenerator.h b/Source/cmCommonTargetGenerator.h index c9645e7..0bafde9 100644 --- a/Source/cmCommonTargetGenerator.h +++ b/Source/cmCommonTargetGenerator.h @@ -28,8 +28,7 @@ class cmSourceFile; class cmCommonTargetGenerator { public: - cmCommonTargetGenerator(cmOutputConverter::RelativeRoot wd, - cmGeneratorTarget* gt); + cmCommonTargetGenerator(cmGeneratorTarget* gt); virtual ~cmCommonTargetGenerator(); std::string const& GetConfigName() const; @@ -45,7 +44,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,15 +53,6 @@ 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); @@ -71,9 +60,6 @@ protected: 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/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx index 2129394..fffb77d 100644 --- a/Source/cmComputeLinkDepends.cxx +++ b/Source/cmComputeLinkDepends.cxx @@ -194,7 +194,7 @@ cmComputeLinkDepends::cmComputeLinkDepends(const cmGeneratorTarget* target, this->OldLinkDirMode = false; // No computation has been done. - this->CCG = 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..4a33aff 100644 --- a/Source/cmComputeLinkDepends.h +++ b/Source/cmComputeLinkDepends.h @@ -44,7 +44,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..7db5df3 100644 --- a/Source/cmComputeLinkInformation.cxx +++ b/Source/cmComputeLinkInformation.cxx @@ -262,7 +262,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 +274,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 +283,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 +561,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 +693,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 +705,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 +724,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 +1606,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..023c781 100644 --- a/Source/cmComputeLinkInformation.h +++ b/Source/cmComputeLinkInformation.h @@ -38,7 +38,7 @@ public: Item() : Value() , IsPath(true) - , Target(0) + , Target(CM_NULLPTR) { } Item(Item const& item) @@ -47,7 +47,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..ff7eb0b 100644 --- a/Source/cmComputeTargetDepends.cxx +++ b/Source/cmComputeTargetDepends.cxx @@ -291,7 +291,7 @@ void cmComputeTargetDepends::AddInterfaceDepends( // within the project. if (dependee && dependee->GetType() == cmState::EXECUTABLE && !dependee->IsExecutableWithExports()) { - dependee = 0; + dependee = CM_NULLPTR; } if (dependee) { @@ -355,7 +355,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/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx index 7006b62..d7532b3 100644 --- a/Source/cmConditionEvaluator.cxx +++ b/Source/cmConditionEvaluator.cxx @@ -21,12 +21,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 +37,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, @@ -130,7 +136,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()); @@ -486,7 +492,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 +565,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 +578,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 +592,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 +617,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/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in index 62128a7..7e48b2d 100644 --- a/Source/cmConfigure.cmake.h.in +++ b/Source/cmConfigure.cmake.h.in @@ -9,10 +9,43 @@ implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ +#ifndef cmConfigure_h +#define 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 + #cmakedefine HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE #cmakedefine HAVE_UNSETENV #cmakedefine CMAKE_USE_ELF_PARSER #cmakedefine CMAKE_USE_MACH_PARSER #cmakedefine CMAKE_ENCODING_UTF8 -#cmakedefine CMake_HAVE_CXX11_UNORDERED_MAP +#cmakedefine CMake_HAVE_CXX_NULLPTR +#cmakedefine CMake_HAVE_CXX_OVERRIDE +#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.h b/Source/cmConfigureFileCommand.h index 79f00bc..1da65c8 100644 --- a/Source/cmConfigureFileCommand.h +++ b/Source/cmConfigureFileCommand.h @@ -19,24 +19,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.h b/Source/cmContinueCommand.h index 63ae59d..6fa9af2 100644 --- a/Source/cmContinueCommand.h +++ b/Source/cmContinueCommand.h @@ -25,24 +25,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..e9367b1 100644 --- a/Source/cmCoreTryCompile.cxx +++ b/Source/cmCoreTryCompile.cxx @@ -77,7 +77,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 +334,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( diff --git a/Source/cmCreateTestSourceList.h b/Source/cmCreateTestSourceList.h index cfaca2e..2025ecd 100644 --- a/Source/cmCreateTestSourceList.h +++ b/Source/cmCreateTestSourceList.h @@ -25,19 +25,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..9bd07a3 100644 --- a/Source/cmCryptoHash.cxx +++ b/Source/cmCryptoHash.cxx @@ -15,26 +15,58 @@ #include <cmsys/FStream.hxx> #include <cmsys/MD5.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); + return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashMD5); } else if (strcmp(algo, "SHA1") == 0) { - return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA1); + return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA1); } else if (strcmp(algo, "SHA224") == 0) { - return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA224); + return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA224); } else if (strcmp(algo, "SHA256") == 0) { - return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA256); + return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA256); } else if (strcmp(algo, "SHA384") == 0) { - return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA384); + return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA384); } else if (strcmp(algo, "SHA512") == 0) { - return cmsys::auto_ptr<cmCryptoHash>(new cmCryptoHashSHA512); + return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA512); } else { - return cmsys::auto_ptr<cmCryptoHash>(0); + 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; + } else if (input >= 'a' && input <= 'f') { + output = char(input - 'a' + 0xA); + return true; + } else 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 +74,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 +138,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 +156,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..4e92b06 100644 --- a/Source/cmCryptoHash.h +++ b/Source/cmCryptoHash.h @@ -14,20 +14,56 @@ #include "cmStandardIncludes.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> +/** + * @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 +72,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 +92,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.h b/Source/cmCurl.h index eac7f13..26bf94e 100644 --- a/Source/cmCurl.h +++ b/Source/cmCurl.h @@ -16,6 +16,6 @@ #include "cm_curl.h" -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..7533369 100644 --- a/Source/cmCustomCommand.cxx +++ b/Source/cmCustomCommand.cxx @@ -13,7 +13,7 @@ #include "cmMakefile.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> cmCustomCommand::cmCustomCommand() : Backtrace() @@ -38,7 +38,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 +69,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; } diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx index 99bb601..6165bcf 100644 --- a/Source/cmCustomCommandGenerator.cxx +++ b/Source/cmCustomCommandGenerator.cxx @@ -45,7 +45,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 +66,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 +145,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/cmCustomCommandLines.h b/Source/cmCustomCommandLines.h new file mode 100644 index 0000000..c67550e --- /dev/null +++ b/Source/cmCustomCommandLines.h @@ -0,0 +1,38 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software 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 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.h b/Source/cmDefinePropertyCommand.h index 4248bbe..9cc19c4 100644 --- a/Source/cmDefinePropertyCommand.h +++ b/Source/cmDefinePropertyCommand.h @@ -17,19 +17,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..e0fb59b 100644 --- a/Source/cmDefinitions.cxx +++ b/Source/cmDefinitions.cxx @@ -41,7 +41,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..8f1813c 100644 --- a/Source/cmDefinitions.h +++ b/Source/cmDefinitions.h @@ -17,7 +17,7 @@ #include "cmLinkedTree.h" #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" @@ -92,7 +92,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..b25e3ce 100644 --- a/Source/cmDepends.cxx +++ b/Source/cmDepends.cxx @@ -23,7 +23,7 @@ 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]) @@ -140,7 +140,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 +182,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 +242,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 +261,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..0e1cbb9 100644 --- a/Source/cmDepends.h +++ b/Source/cmDepends.h @@ -29,7 +29,7 @@ class cmDepends public: /** Instances need to know the build directory name and the relative path from the build directory to the target file. */ - cmDepends(cmLocalGenerator* lg = 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..18e123e 100644 --- a/Source/cmDependsC.cxx +++ b/Source/cmDependsC.cxx @@ -29,7 +29,7 @@ #define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: " cmDependsC::cmDependsC() - : ValidDeps(0) + : ValidDeps(CM_NULLPTR) { } @@ -105,7 +105,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 +158,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 +175,7 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, break; } } + } } // Complain if the file cannot be found and matches the complain @@ -268,31 +269,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 +312,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 +344,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..bde07b7 100644 --- a/Source/cmDependsC.h +++ b/Source/cmDependsC.h @@ -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 38e319d..9ea1e48 100644 --- a/Source/cmDependsFortran.cxx +++ b/Source/cmDependsFortran.cxx @@ -53,7 +53,7 @@ public: }; cmDependsFortran::cmDependsFortran() - : Internal(0) + : Internal(CM_NULLPTR) { } @@ -633,8 +633,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 +654,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; diff --git a/Source/cmDependsFortran.h b/Source/cmDependsFortran.h index 5ff0b6c..f4385eb 100644 --- a/Source/cmDependsFortran.h +++ b/Source/cmDependsFortran.h @@ -34,7 +34,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 +48,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 +59,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.h b/Source/cmDependsJava.h index 44723fa..5bb3039 100644 --- a/Source/cmDependsJava.h +++ b/Source/cmDependsJava.h @@ -25,17 +25,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/cmDependsJavaParserHelper.cxx b/Source/cmDependsJavaParserHelper.cxx index bd3ee4d..79c4669 100644 --- a/Source/cmDependsJavaParserHelper.cxx +++ b/Source/cmDependsJavaParserHelper.cxx @@ -35,7 +35,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 +44,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 +59,7 @@ void cmDependsJavaParserHelper::DeallocateParserType(char** pt) if (!*pt) { return; } - *pt = 0; + *pt = CM_NULLPTR; this->UnionsAvailable--; } @@ -160,13 +160,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 +191,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 +222,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 +303,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 +326,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..6ff0245 100644 --- a/Source/cmDependsJavaParserHelper.h +++ b/Source/cmDependsJavaParserHelper.h @@ -48,7 +48,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 +69,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..919a45e 100644 --- a/Source/cmDocumentation.cxx +++ b/Source/cmDocumentation.cxx @@ -49,12 +49,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 +137,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 { @@ -420,7 +420,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 +434,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 +447,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 +461,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()); diff --git a/Source/cmDocumentation.h b/Source/cmDocumentation.h index dd99ca8..ac36c8b 100644 --- a/Source/cmDocumentation.h +++ b/Source/cmDocumentation.h @@ -39,7 +39,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..f50839e --- /dev/null +++ b/Source/cmDocumentationEntry.h @@ -0,0 +1,45 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software 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 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/cmDynamicLoader.cxx b/Source/cmDynamicLoader.cxx index 7d0bbdc..4c31733f 100644 --- a/Source/cmDynamicLoader.cxx +++ b/Source/cmDynamicLoader.cxx @@ -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/cmELF.cxx b/Source/cmELF.cxx index 26f1a44..266b786 100644 --- a/Source/cmELF.cxx +++ b/Source/cmELF.cxx @@ -13,8 +13,8 @@ #include "cmELF.h" +#include <cm_auto_ptr.hxx> #include <cmsys/FStream.hxx> -#include <cmsys/auto_ptr.hxx> // Include the ELF format information system header. #if defined(__OpenBSD__) @@ -46,6 +46,9 @@ 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> @@ -107,7 +110,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 +146,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 +217,7 @@ struct cmELFTypes32 }; // Configure the implementation template for 64-bit ELF files. +#ifndef _SCO_DS struct cmELFTypes64 { typedef Elf64_Ehdr ELF_Ehdr; @@ -223,6 +227,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 +242,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 +502,7 @@ private: this->NeedSwap) { ByteSwap(x); } - return this->Stream ? true : false; + return !this->Stream.fail(); } bool Read(ELF_Dyn& x) { @@ -505,7 +510,7 @@ private: this->NeedSwap) { ByteSwap(x); } - return this->Stream ? true : false; + return !this->Stream.fail(); } bool LoadSectionHeader(ELF_Half i) @@ -537,8 +542,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 +678,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 +689,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 +711,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 +740,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 +751,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 +805,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; } @@ -879,7 +889,7 @@ cmELF::StringEntry const* cmELF::GetSOName() this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary) { return this->Internal->GetSOName(); } else { - return 0; + return CM_NULLPTR; } } @@ -890,7 +900,7 @@ cmELF::StringEntry const* cmELF::GetRPath() this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) { return this->Internal->GetRPath(); } else { - return 0; + return CM_NULLPTR; } } @@ -901,7 +911,7 @@ cmELF::StringEntry const* cmELF::GetRunPath() this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) { return this->Internal->GetRunPath(); } else { - return 0; + return CM_NULLPTR; } } diff --git a/Source/cmElseCommand.h b/Source/cmElseCommand.h index 815825e..9acf4d8 100644 --- a/Source/cmElseCommand.h +++ b/Source/cmElseCommand.h @@ -25,24 +25,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.h b/Source/cmElseIfCommand.h index d0ffa5d..19c1885 100644 --- a/Source/cmElseIfCommand.h +++ b/Source/cmElseIfCommand.h @@ -25,24 +25,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.h b/Source/cmEnableLanguageCommand.h index 657e4e5..31b6095 100644 --- a/Source/cmEnableLanguageCommand.h +++ b/Source/cmEnableLanguageCommand.h @@ -28,19 +28,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.h b/Source/cmEnableTestingCommand.h index a518f18..8c8ffbf 100644 --- a/Source/cmEnableTestingCommand.h +++ b/Source/cmEnableTestingCommand.h @@ -33,19 +33,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.h b/Source/cmEndForEachCommand.h index ebc794f..b2c47b2 100644 --- a/Source/cmEndForEachCommand.h +++ b/Source/cmEndForEachCommand.h @@ -25,20 +25,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 +47,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.h b/Source/cmEndFunctionCommand.h index b69dec0..856fdc5 100644 --- a/Source/cmEndFunctionCommand.h +++ b/Source/cmEndFunctionCommand.h @@ -25,20 +25,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 +47,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.h b/Source/cmEndIfCommand.h index 457dfd3..13cf6f6 100644 --- a/Source/cmEndIfCommand.h +++ b/Source/cmEndIfCommand.h @@ -25,24 +25,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.h b/Source/cmEndMacroCommand.h index 615e8dc..e176eaf 100644 --- a/Source/cmEndMacroCommand.h +++ b/Source/cmEndMacroCommand.h @@ -25,20 +25,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 +47,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.h b/Source/cmEndWhileCommand.h index 5eda7af..6b72514 100644 --- a/Source/cmEndWhileCommand.h +++ b/Source/cmEndWhileCommand.h @@ -25,20 +25,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 +47,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..58bbc31 100644 --- a/Source/cmExecProgramCommand.cxx +++ b/Source/cmExecProgramCommand.cxx @@ -90,7 +90,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 +209,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 +219,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 +229,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..7cd4f9f 100644 --- a/Source/cmExecProgramCommand.h +++ b/Source/cmExecProgramCommand.h @@ -27,30 +27,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..d97b25f 100644 --- a/Source/cmExecuteProcessCommand.cxx +++ b/Source/cmExecuteProcessCommand.cxx @@ -161,7 +161,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, return false; } else { // Add the null terminating pointer to the command argument list. - cmds[i].push_back(0); + cmds[i].push_back(CM_NULLPTR); } } @@ -228,7 +228,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 +246,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..61687ef 100644 --- a/Source/cmExecuteProcessCommand.h +++ b/Source/cmExecuteProcessCommand.h @@ -26,24 +26,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/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx index 8ca7a11..a53d285 100644 --- a/Source/cmExportBuildFileGenerator.cxx +++ b/Source/cmExportBuildFileGenerator.cxx @@ -18,8 +18,8 @@ cmExportBuildFileGenerator::cmExportBuildFileGenerator() { - this->LG = 0; - this->ExportSet = 0; + this->LG = CM_NULLPTR; + this->ExportSet = CM_NULLPTR; } void cmExportBuildFileGenerator::Compute(cmLocalGenerator* lg) diff --git a/Source/cmExportBuildFileGenerator.h b/Source/cmExportBuildFileGenerator.h index be3c70a..417e8c9 100644 --- a/Source/cmExportBuildFileGenerator.h +++ b/Source/cmExportBuildFileGenerator.h @@ -50,14 +50,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 +70,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..fc62492 100644 --- a/Source/cmExportCommand.cxx +++ b/Source/cmExportCommand.cxx @@ -35,7 +35,7 @@ cmExportCommand::cmExportCommand() , Filename(&Helper, "FILE", &ArgumentGroup) , ExportOld(&Helper, "EXPORT_LINK_INTERFACE_LIBRARIES", &ArgumentGroup) { - this->ExportSet = 0; + this->ExportSet = CM_NULLPTR; } // cmExportCommand @@ -50,10 +50,10 @@ 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); + 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); } @@ -327,11 +327,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..0a149af 100644 --- a/Source/cmExportCommand.h +++ b/Source/cmExportCommand.h @@ -30,19 +30,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); diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx index 736c7da..e00af5e 100644 --- a/Source/cmExportFileGenerator.cxx +++ b/Source/cmExportFileGenerator.cxx @@ -25,8 +25,8 @@ #include "cmVersion.h" #include <assert.h> +#include <cm_auto_ptr.hxx> #include <cmsys/FStream.hxx> -#include <cmsys/auto_ptr.hxx> static std::string cmExportFileGeneratorEscape(std::string const& str) { @@ -69,15 +69,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; @@ -93,7 +93,7 @@ bool cmExportFileGenerator::GenerateImportFile() // Protect that file against use with older CMake versions. /* clang-format off */ - os << "# Generated by CMake " << cmVersion::GetCMakeVersion() << "\n\n"; + 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"; @@ -393,7 +393,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); diff --git a/Source/cmExportInstallFileGenerator.h b/Source/cmExportInstallFileGenerator.h index 723b6e5..68960db 100644 --- a/Source/cmExportInstallFileGenerator.h +++ b/Source/cmExportInstallFileGenerator.h @@ -52,16 +52,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, @@ -82,7 +82,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..b422a2c 100644 --- a/Source/cmExportLibraryDependenciesCommand.cxx +++ b/Source/cmExportLibraryDependenciesCommand.cxx @@ -16,7 +16,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&) @@ -53,13 +53,13 @@ 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; @@ -152,7 +152,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..4b3dc92 100644 --- a/Source/cmExportLibraryDependenciesCommand.h +++ b/Source/cmExportLibraryDependenciesCommand.h @@ -18,13 +18,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/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx index 5a826f2..2916e6b 100644 --- a/Source/cmExportTryCompileFileGenerator.cxx +++ b/Source/cmExportTryCompileFileGenerator.cxx @@ -63,9 +63,10 @@ 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"); diff --git a/Source/cmExportTryCompileFileGenerator.h b/Source/cmExportTryCompileFileGenerator.h index 26f4db1..1d13711 100644 --- a/Source/cmExportTryCompileFileGenerator.h +++ b/Source/cmExportTryCompileFileGenerator.h @@ -28,15 +28,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 +45,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/cmExprParserHelper.cxx b/Source/cmExprParserHelper.cxx index 2ba9b8d..0771a4e 100644 --- a/Source/cmExprParserHelper.cxx +++ b/Source/cmExprParserHelper.cxx @@ -21,7 +21,7 @@ int cmExpr_yyparse(yyscan_t yyscanner); cmExprParserHelper::cmExprParserHelper() { this->FileLine = -1; - this->FileName = 0; + this->FileName = CM_NULLPTR; } cmExprParserHelper::~cmExprParserHelper() diff --git a/Source/cmExternalMakefileProjectGenerator.cxx b/Source/cmExternalMakefileProjectGenerator.cxx index 0e42d75..a527e50 100644 --- a/Source/cmExternalMakefileProjectGenerator.cxx +++ b/Source/cmExternalMakefileProjectGenerator.cxx @@ -33,28 +33,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..6ae5533 100644 --- a/Source/cmExternalMakefileProjectGenerator.h +++ b/Source/cmExternalMakefileProjectGenerator.h @@ -35,11 +35,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 +50,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 +59,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 + { + T* p = new T; + p->SetName(GetName()); + return p; + } }; #endif diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx index 589bf53..3a9bb9b 100644 --- a/Source/cmExtraCodeBlocksGenerator.cxx +++ b/Source/cmExtraCodeBlocksGenerator.cxx @@ -36,24 +36,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() @@ -248,7 +254,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 +295,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 +312,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 +328,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 +382,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 +521,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 +529,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; } } @@ -659,11 +667,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 +679,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"; @@ -733,7 +741,7 @@ std::string cmExtraCodeBlocksGenerator::BuildMakeCommand( const std::string& makeFlags) { std::string command = make; - if (makeFlags.size() > 0) { + if (!makeFlags.empty()) { command += " "; command += makeFlags; } diff --git a/Source/cmExtraCodeBlocksGenerator.h b/Source/cmExtraCodeBlocksGenerator.h index fe4f513..b39080c 100644 --- a/Source/cmExtraCodeBlocksGenerator.h +++ b/Source/cmExtraCodeBlocksGenerator.h @@ -28,20 +28,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..eda6867 100644 --- a/Source/cmExtraCodeLiteGenerator.cxx +++ b/Source/cmExtraCodeLiteGenerator.cxx @@ -27,24 +27,30 @@ #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."; -} - 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() @@ -407,7 +413,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..e20e745 100644 --- a/Source/cmExtraCodeLiteGenerator.h +++ b/Source/cmExtraCodeLiteGenerator.h @@ -36,20 +36,9 @@ protected: 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, diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx index f24e7fb..8091bcf 100644 --- a/Source/cmExtraEclipseCDT4Generator.cxx +++ b/Source/cmExtraEclipseCDT4Generator.cxx @@ -46,16 +46,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,11 +54,26 @@ 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( @@ -129,7 +134,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 +213,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 +223,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 +317,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 +347,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;"; diff --git a/Source/cmExtraEclipseCDT4Generator.h b/Source/cmExtraEclipseCDT4Generator.h index 0cef071..4b585c3 100644 --- a/Source/cmExtraEclipseCDT4Generator.h +++ b/Source/cmExtraEclipseCDT4Generator.h @@ -35,24 +35,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 +70,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..4e72504 100644 --- a/Source/cmExtraKateGenerator.cxx +++ b/Source/cmExtraKateGenerator.cxx @@ -22,24 +22,28 @@ #include <cmsys/SystemTools.hxx> -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 +141,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..3d16052 100644 --- a/Source/cmExtraKateGenerator.h +++ b/Source/cmExtraKateGenerator.h @@ -26,20 +26,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..b6bad60 100644 --- a/Source/cmExtraSublimeTextGenerator.cxx +++ b/Source/cmExtraSublimeTextGenerator.cxx @@ -38,24 +38,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 +140,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 +161,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 +178,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: @@ -204,7 +211,7 @@ void cmExtraSublimeTextGenerator::AppendTarget( MapSourceFileFlags& sourceFileFlags, bool firstTarget) { - if (target != 0) { + if (target != CM_NULLPTR) { std::vector<cmSourceFile*> sourceFiles; target->GetSourceFiles(sourceFiles, makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); @@ -314,27 +321,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 +339,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..c087825 100644 --- a/Source/cmExtraSublimeTextGenerator.h +++ b/Source/cmExtraSublimeTextGenerator.h @@ -27,23 +27,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..03ee31e 100644 --- a/Source/cmFLTKWrapUICommand.cxx +++ b/Source/cmFLTKWrapUICommand.cxx @@ -73,8 +73,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..72b468e 100644 --- a/Source/cmFLTKWrapUICommand.h +++ b/Source/cmFLTKWrapUICommand.h @@ -28,14 +28,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 +43,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..835b118 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -34,12 +34,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__) @@ -231,17 +231,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 +257,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 +330,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 +526,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; @@ -901,9 +901,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 +958,7 @@ struct cmFileCopier , MatchlessFiles(true) , FilePermissions(0) , DirPermissions(0) - , CurrentMatchRule(0) + , CurrentMatchRule(CM_NULLPTR) , UseGivenPermissionsFile(false) , UseGivenPermissionsDir(false) , UseSourcePermissions(true) @@ -1609,13 +1609,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 +1642,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 +1659,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 +1672,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 +1871,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 +1943,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 +2033,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 +2097,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 +2439,7 @@ public: inline void release(void) { - this->Easy = 0; + this->Easy = CM_NULLPTR; return; } @@ -2478,7 +2479,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO"); std::string expectedHash; std::string hashMatchMSG; - cmsys::auto_ptr<cmCryptoHash> hash; + CM_AUTO_PTR<cmCryptoHash> hash; bool showProgress = false; while (i != args.end()) { @@ -2534,7 +2535,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 +2556,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; @@ -2934,7 +2935,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 +2972,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, diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h index 84bb456..9121d3c 100644 --- a/Source/cmFileCommand.h +++ b/Source/cmFileCommand.h @@ -26,24 +26,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/cmFileTimeComparison.cxx b/Source/cmFileTimeComparison.cxx index 7efe194..9d63505 100644 --- a/Source/cmFileTimeComparison.cxx +++ b/Source/cmFileTimeComparison.cxx @@ -13,7 +13,7 @@ // 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> @@ -47,13 +47,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, diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx index 638c1d1..d255ceb 100644 --- a/Source/cmFindCommon.cxx +++ b/Source/cmFindCommon.cxx @@ -234,13 +234,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..0f8d826 100644 --- a/Source/cmFindCommon.h +++ b/Source/cmFindCommon.h @@ -27,7 +27,7 @@ class cmFindCommon : public cmCommand { public: cmFindCommon(); - ~cmFindCommon(); + ~cmFindCommon() CM_OVERRIDE; cmTypeMacro(cmFindCommon, cmCommand); protected: diff --git a/Source/cmFindFileCommand.h b/Source/cmFindFileCommand.h index 74b01f1..68bd5b9 100644 --- a/Source/cmFindFileCommand.h +++ b/Source/cmFindFileCommand.h @@ -29,8 +29,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..3094fcf 100644 --- a/Source/cmFindLibraryCommand.cxx +++ b/Source/cmFindLibraryCommand.cxx @@ -40,11 +40,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"); } } diff --git a/Source/cmFindLibraryCommand.h b/Source/cmFindLibraryCommand.h index a08e151..813decd 100644 --- a/Source/cmFindLibraryCommand.h +++ b/Source/cmFindLibraryCommand.h @@ -28,24 +28,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..260079b 100644 --- a/Source/cmFindPackageCommand.cxx +++ b/Source/cmFindPackageCommand.cxx @@ -43,6 +43,7 @@ cmFindPackageCommand::cmFindPackageCommand() this->UseConfigFiles = true; this->UseFindModules = true; this->DebugMode = false; + this->UseLib32Paths = false; this->UseLib64Paths = false; this->PolicyScope = true; this->VersionMajor = 0; @@ -110,6 +111,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( @@ -664,16 +672,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 +776,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 +1077,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 +1199,7 @@ public: cmSystemTools::RemoveFile(this->File); } } - void Release() { this->File = 0; } + void Release() { this->File = CM_NULLPTR; } }; void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir, @@ -1489,9 +1500,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 +1515,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 +1526,7 @@ class cmFileList public: cmFileList() : First() - , Last(0) + , Last(CM_NULLPTR) { } virtual ~cmFileList() {} @@ -1540,7 +1551,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,7 +1566,7 @@ public: } private: - bool Visit(std::string const& fullPath) + bool Visit(std::string const& fullPath) CM_OVERRIDE { if (this->UseSuffixes) { return this->FPC->SearchDirectory(fullPath); @@ -1605,14 +1616,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 +1645,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 +1655,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; } @@ -1668,7 +1679,7 @@ public: 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; @@ -1695,9 +1706,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 +1734,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 +1763,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 +1788,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 +1807,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 +1831,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 +1853,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; } }; @@ -1907,6 +1917,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"); } diff --git a/Source/cmFindPackageCommand.h b/Source/cmFindPackageCommand.h index eff6b80..087107e 100644 --- a/Source/cmFindPackageCommand.h +++ b/Source/cmFindPackageCommand.h @@ -29,24 +29,24 @@ public: /** * 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 +148,7 @@ private: bool NoUserRegistry; bool NoSystemRegistry; bool DebugMode; + bool UseLib32Paths; bool UseLib64Paths; bool PolicyScope; std::string LibraryArchitecture; @@ -159,6 +160,21 @@ private: { 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..d71fc1a 100644 --- a/Source/cmFindPathCommand.cxx +++ b/Source/cmFindPathCommand.cxx @@ -117,7 +117,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 ""; diff --git a/Source/cmFindPathCommand.h b/Source/cmFindPathCommand.h index e14626a..52ce3b0 100644 --- a/Source/cmFindPathCommand.h +++ b/Source/cmFindPathCommand.h @@ -28,24 +28,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.h b/Source/cmFindProgramCommand.h index 3f2ac0e..1953f59 100644 --- a/Source/cmFindProgramCommand.h +++ b/Source/cmFindProgramCommand.h @@ -29,24 +29,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..c6e5f06 100644 --- a/Source/cmForEachCommand.cxx +++ b/Source/cmForEachCommand.cxx @@ -11,7 +11,7 @@ ============================================================================*/ #include "cmForEachCommand.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf) : Makefile(mf) @@ -36,8 +36,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; } @@ -184,7 +183,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..887e6e9 100644 --- a/Source/cmForEachCommand.h +++ b/Source/cmForEachCommand.h @@ -21,10 +21,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 +41,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/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx index 934e928..a72204a 100644 --- a/Source/cmFortranParserImpl.cxx +++ b/Source/cmFortranParserImpl.cxx @@ -65,7 +65,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,7 +84,7 @@ bool cmFortranParser_FilePush(cmFortranParser* parser, const char* fname) std::string dir = cmSystemTools::GetParentDirectory(fname); cmFortranFile f(file, current, dir); YY_BUFFER_STATE buffer = - cmFortran_yy_create_buffer(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; diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx index de9887e..40c54db 100644 --- a/Source/cmFunctionCommand.cxx +++ b/Source/cmFunctionCommand.cxx @@ -20,7 +20,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 +28,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 +47,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 +65,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); diff --git a/Source/cmFunctionCommand.h b/Source/cmFunctionCommand.h index 08f7f0f..2c7a884 100644 --- a/Source/cmFunctionCommand.h +++ b/Source/cmFunctionCommand.h @@ -20,10 +20,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 +37,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..c35a1bc 100644 --- a/Source/cmGeneratedFileStream.cxx +++ b/Source/cmGeneratedFileStream.cxx @@ -42,7 +42,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 +56,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 +71,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..3480c5b 100644 --- a/Source/cmGeneratedFileStream.h +++ b/Source/cmGeneratedFileStream.h @@ -99,7 +99,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..983bfb4 100644 --- a/Source/cmGeneratorExpression.cxx +++ b/Source/cmGeneratorExpression.cxx @@ -26,14 +26,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 : "")); diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h index 71fbba3..2f91608 100644 --- a/Source/cmGeneratorExpression.h +++ b/Source/cmGeneratorExpression.h @@ -17,8 +17,8 @@ #include "cmListFileCache.h" +#include <cm_auto_ptr.hxx> #include <cmsys/RegularExpression.hxx> -#include <cmsys/auto_ptr.hxx> class cmGeneratorTarget; class cmLocalGenerator; @@ -47,9 +47,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 +80,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/cmGeneratorExpressionDAGChecker.h b/Source/cmGeneratorExpressionDAGChecker.h index 28ca824..6b7fe9a 100644 --- a/Source/cmGeneratorExpressionDAGChecker.h +++ b/Source/cmGeneratorExpressionDAGChecker.h @@ -63,7 +63,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..c01c4fc 100644 --- a/Source/cmGeneratorExpressionEvaluationFile.cxx +++ b/Source/cmGeneratorExpressionEvaluationFile.cxx @@ -23,9 +23,8 @@ 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 +39,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 +55,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 +96,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 +134,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..52ba2d8 100644 --- a/Source/cmGeneratorExpressionEvaluationFile.h +++ b/Source/cmGeneratorExpressionEvaluationFile.h @@ -14,7 +14,7 @@ #include "cmGeneratorExpression.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> #include <sys/types.h> class cmLocalGenerator; @@ -24,9 +24,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 +41,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.h b/Source/cmGeneratorExpressionEvaluator.h index 7ca62c5..58e732b 100644 --- a/Source/cmGeneratorExpressionEvaluator.h +++ b/Source/cmGeneratorExpressionEvaluator.h @@ -52,12 +52,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 +85,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/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx index e750551..6e2b16a 100644 --- a/Source/cmGeneratorExpressionNode.cxx +++ b/Source/cmGeneratorExpressionNode.cxx @@ -24,7 +24,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 +42,14 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return std::string(); } @@ -59,12 +59,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return parameters.front(); } @@ -113,7 +113,7 @@ static const struct NotNode : public cmGeneratorExpressionNode std::string Evaluate(const std::vector<std::string>& parameters, cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker*) const + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { if (*parameters.begin() != "0" && *parameters.begin() != "1") { reportError( @@ -129,12 +129,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return !cmSystemTools::IsOff(parameters.begin()->c_str()) ? "1" : "0"; } @@ -144,12 +144,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return *parameters.begin() == parameters[1] ? "1" : "0"; } @@ -159,12 +159,12 @@ 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*) const CM_OVERRIDE { char* pEnd; @@ -236,12 +236,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return cmSystemTools::LowerCase(parameters.front()); } @@ -251,12 +251,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return cmSystemTools::UpperCase(parameters.front()); } @@ -266,12 +266,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return cmSystemTools::MakeCidentifier(parameters.front()); } @@ -281,12 +281,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return ">"; } @@ -296,12 +296,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return ","; } @@ -311,12 +311,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return ";"; } @@ -326,7 +326,7 @@ 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, @@ -381,6 +381,7 @@ static const struct CCompilerIdNode : public CompilerIdNode cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, cmGeneratorExpressionDAGChecker* dagChecker) const + CM_OVERRIDE { if (!context->HeadTarget) { reportError( @@ -402,6 +403,7 @@ static const struct CXXCompilerIdNode : public CompilerIdNode cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, cmGeneratorExpressionDAGChecker* dagChecker) const + CM_OVERRIDE { if (!context->HeadTarget) { reportError( @@ -419,7 +421,7 @@ 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, @@ -460,6 +462,7 @@ static const struct CCompilerVersionNode : public CompilerVersionNode cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, cmGeneratorExpressionDAGChecker* dagChecker) const + CM_OVERRIDE { if (!context->HeadTarget) { reportError( @@ -481,6 +484,7 @@ static const struct CxxCompilerVersionNode : public CompilerVersionNode cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, cmGeneratorExpressionDAGChecker* dagChecker) const + CM_OVERRIDE { if (!context->HeadTarget) { reportError( @@ -498,12 +502,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { const char* platformId = context->LG->GetMakefile()->GetSafeDefinition("CMAKE_SYSTEM_NAME"); @@ -526,12 +530,12 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, parameters.front().c_str(), @@ -541,16 +545,35 @@ 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*, + const GeneratorExpressionContent*, + cmGeneratorExpressionDAGChecker*) 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, parameters.front().c_str(), @@ -560,16 +583,35 @@ 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*, + const GeneratorExpressionContent*, + cmGeneratorExpressionDAGChecker*) 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, parameters.front().c_str(), @@ -583,10 +625,10 @@ static const struct LinkOnlyNode : public cmGeneratorExpressionNode { LinkOnlyNode() {} - std::string Evaluate(const std::vector<std::string>& parameters, - cmGeneratorExpressionContext*, - const GeneratorExpressionContent*, - cmGeneratorExpressionDAGChecker* dagChecker) const + std::string Evaluate( + const std::vector<std::string>& parameters, cmGeneratorExpressionContext*, + const GeneratorExpressionContent*, + cmGeneratorExpressionDAGChecker* dagChecker) const CM_OVERRIDE { if (!dagChecker->GetTransitivePropertiesOnly()) { return parameters.front(); @@ -599,12 +641,12 @@ 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>&, cmGeneratorExpressionContext* context, const GeneratorExpressionContent*, - cmGeneratorExpressionDAGChecker*) const + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { context->HadContextSensitiveCondition = true; return context->Config; @@ -615,15 +657,16 @@ 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*) 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 +685,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 +716,14 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { std::vector<std::string> list; cmSystemTools::ExpandListArgument(parameters.front(), list); @@ -692,12 +735,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( @@ -753,7 +797,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 +839,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 +1132,20 @@ 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 + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { return parameters.front(); } - virtual int NumExpectedParameters() const { return 1; } + int NumExpectedParameters() const CM_OVERRIDE { return 1; } } targetNameNode; @@ -1111,7 +1156,7 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode std::string Evaluate(const std::vector<std::string>& parameters, cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker*) const + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { if (!context->EvaluateForBuildsystem) { std::ostringstream e; @@ -1179,12 +1224,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 +1309,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 +1352,12 @@ 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*) const CM_OVERRIDE { if (!context->HeadTarget) { reportError( @@ -1365,13 +1411,13 @@ 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>&, cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker*) const + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { reportError(context, content->GetOriginalExpression(), "INSTALL_PREFIX is a marker for install(EXPORT) only. It " @@ -1529,12 +1575,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 +1653,7 @@ static const struct ShellPathNode : public cmGeneratorExpressionNode std::string Evaluate(const std::vector<std::string>& parameters, cmGeneratorExpressionContext* context, const GeneratorExpressionContent* content, - cmGeneratorExpressionDAGChecker*) const + cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE { if (!cmSystemTools::FileIsFullPath(parameters.front())) { reportError(context, content->GetOriginalExpression(), @@ -1632,7 +1679,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 +1724,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/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx index 3856091..793ad2e 100644 --- a/Source/cmGeneratorTarget.cxx +++ b/Source/cmGeneratorTarget.cxx @@ -27,7 +27,10 @@ #include "assert.h" #include <errno.h> -#if defined(CMAKE_BUILD_WITH_CMAKE) +#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 +42,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; @@ -250,7 +253,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 +261,7 @@ void CreatePropertyGeneratorExpressions( cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg) : Target(t) + , FortranModuleDirectoryCreated(false) , SourceFileFlagsConstructed(false) , PolicyWarnedCMP0022(false) , DebugIncludesDone(false) @@ -439,7 +443,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 @@ -457,7 +461,7 @@ void cmGeneratorTarget::AddSource(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(); @@ -473,7 +477,7 @@ void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs) this->LinkImplementationLanguageIsContextDependent = true; cmListFileBacktrace lfbt = this->Makefile->GetBacktrace(); cmGeneratorExpression ge(lfbt); - cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(srcFiles); + CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(srcFiles); cge->SetEvaluateForBuildsystem(true); this->SourceEntries.push_back( new cmGeneratorTarget::TargetPropertyEntry(cge)); @@ -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"); @@ -858,7 +862,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 +998,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 = @@ -1306,11 +1311,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 @@ -1349,11 +1350,17 @@ 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 +1388,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 +1400,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(); @@ -1504,7 +1517,7 @@ const char* cmGeneratorTarget::GetExportMacro() const } return this->ExportMacro.c_str(); } else { - return 0; + return CM_NULLPTR; } } @@ -1529,7 +1542,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: { @@ -1630,7 +1643,7 @@ public: if (this->Preferred.empty()) { return ""; } else if (this->Preferred.size() > 1) { - std::stringstream e; + std::ostringstream e; e << "Target " << this->Target->GetName() << " contains multiple languages with the highest linker preference" << " (" << this->Preference << "):\n"; @@ -1748,7 +1761,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 +1770,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 +1799,7 @@ cmSourceFile const* cmGeneratorTarget::GetModuleDefinitionFile( return data.front(); } - return 0; + return CM_NULLPTR; } bool cmGeneratorTarget::IsDLLPlatform() const @@ -1839,8 +1852,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 +1938,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 +2013,7 @@ void cmTargetTraceDependencies::Trace() this->CheckCustomCommand(*cc); } } - this->CurrentEntry = 0; + this->CurrentEntry = CM_NULLPTR; this->GeneratorTarget->AddTracedSources(this->NewSources); } @@ -2116,8 +2129,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 +2212,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 +2370,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 +2414,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 +2497,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 +2549,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 +2599,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 +2638,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)); @@ -2794,8 +2806,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 +2881,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 +2981,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 +2989,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 +3021,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. @@ -3267,7 +3285,7 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt, 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 +3294,7 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt, return tgt->GetLinkInterfaceDependentNumberMaxProperty(prop, config); } assert(0 && "Unreachable!"); - return 0; + return CM_NULLPTR; } template <typename PropertyType> @@ -3314,7 +3332,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 +3358,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 +3375,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 +3410,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; } @@ -3537,7 +3561,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 +3570,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) { @@ -3580,7 +3604,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: @@ -3751,28 +3775,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 +3811,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,6 +3863,40 @@ void cmGeneratorTarget::GetTargetVersion(bool soversion, int& major, } } +std::string cmGeneratorTarget::GetFortranModuleDirectory() const +{ + if (!this->FortranModuleDirectoryCreated) { + this->FortranModuleDirectory = true; + this->FortranModuleDirectory = this->CreateFortranModuleDirectory(); + } + + return this->FortranModuleDirectory; +} + +std::string cmGeneratorTarget::CreateFortranModuleDirectory() const +{ + std::string mod_dir; + const char* target_mod_dir = this->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 cmGeneratorTarget::GetFrameworkVersion() const { assert(this->GetType() != cmState::INTERFACE_LIBRARY); @@ -3930,14 +3988,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 +4017,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 +4041,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface( } } - return iface.Exists ? &iface : 0; + return iface.Exists ? &iface : CM_NULLPTR; } void cmGeneratorTarget::ComputeLinkInterface( @@ -4074,7 +4133,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 +4156,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, @@ -4126,7 +4185,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 +4195,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 +4226,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 +4240,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 +4249,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 +4261,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 +4269,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 +4316,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 +4326,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 +4384,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 +4510,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 +4546,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 +4572,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 +4589,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 +4732,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 +4961,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 +5001,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 +5095,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 +5109,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..f9987aa 100644 --- a/Source/cmGeneratorTarget.h +++ b/Source/cmGeneratorTarget.h @@ -215,7 +215,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 +402,7 @@ public: { SourceFileFlags() : Type(SourceFileTypeNormal) - , MacFolder(0) + , MacFolder(CM_NULLPTR) { } SourceFileFlags(SourceFileFlags const& r) @@ -453,7 +453,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 +526,13 @@ public: void GetTargetVersion(bool soversion, int& major, int& minor, int& patch) const; + std::string GetFortranModuleDirectory() const; + private: + std::string CreateFortranModuleDirectory() 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..c89d030 100644 --- a/Source/cmGetCMakePropertyCommand.cxx +++ b/Source/cmGetCMakePropertyCommand.cxx @@ -42,7 +42,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..7df9cc1 100644 --- a/Source/cmGetCMakePropertyCommand.h +++ b/Source/cmGetCMakePropertyCommand.h @@ -17,24 +17,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..a331e78 100644 --- a/Source/cmGetDirectoryPropertyCommand.cxx +++ b/Source/cmGetDirectoryPropertyCommand.cxx @@ -73,7 +73,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..1be9aa4 100644 --- a/Source/cmGetDirectoryPropertyCommand.h +++ b/Source/cmGetDirectoryPropertyCommand.h @@ -17,24 +17,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.h b/Source/cmGetFilenameComponentCommand.h index a114b3d..d8609fe 100644 --- a/Source/cmGetFilenameComponentCommand.h +++ b/Source/cmGetFilenameComponentCommand.h @@ -26,24 +26,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..2307e08 100644 --- a/Source/cmGetPropertyCommand.cxx +++ b/Source/cmGetPropertyCommand.cxx @@ -248,15 +248,14 @@ 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()); + } else { + return this->StoreResult(NULL); } } - 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 { @@ -323,7 +322,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,7 +346,7 @@ bool cmGetPropertyCommand::HandleInstallMode() std::string value; bool isSet = file->GetProperty(this->PropertyName, value); - return this->StoreResult(isSet ? value.c_str() : 0); + return this->StoreResult(isSet ? value.c_str() : CM_NULLPTR); } else { std::ostringstream e; e << "given INSTALL name that could not be found or created: " diff --git a/Source/cmGetPropertyCommand.h b/Source/cmGetPropertyCommand.h index aeed01d..558226b 100644 --- a/Source/cmGetPropertyCommand.h +++ b/Source/cmGetPropertyCommand.h @@ -19,24 +19,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..7b30a7d 100644 --- a/Source/cmGetSourceFilePropertyCommand.cxx +++ b/Source/cmGetSourceFilePropertyCommand.cxx @@ -34,7 +34,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..2d2477c 100644 --- a/Source/cmGetSourceFilePropertyCommand.h +++ b/Source/cmGetSourceFilePropertyCommand.h @@ -17,19 +17,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..073cf32 100644 --- a/Source/cmGetTargetPropertyCommand.cxx +++ b/Source/cmGetTargetPropertyCommand.cxx @@ -24,22 +24,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..3e0fe36 100644 --- a/Source/cmGetTargetPropertyCommand.h +++ b/Source/cmGetTargetPropertyCommand.h @@ -17,19 +17,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..5eaf872 100644 --- a/Source/cmGetTestPropertyCommand.cxx +++ b/Source/cmGetTestPropertyCommand.cxx @@ -27,7 +27,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..e419c98 100644 --- a/Source/cmGetTestPropertyCommand.h +++ b/Source/cmGetTestPropertyCommand.h @@ -17,19 +17,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/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx index 8565fdb..3d35114 100644 --- a/Source/cmGhsMultiTargetGenerator.cxx +++ b/Source/cmGhsMultiTargetGenerator.cxx @@ -371,7 +371,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/cmGlobalCommonGenerator.h b/Source/cmGlobalCommonGenerator.h index 7bb0e55..a48ff4f 100644 --- a/Source/cmGlobalCommonGenerator.h +++ b/Source/cmGlobalCommonGenerator.h @@ -21,7 +21,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..3ec16c0 100644 --- a/Source/cmGlobalGenerator.cxx +++ b/Source/cmGlobalGenerator.cxx @@ -81,9 +81,9 @@ 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; @@ -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; } @@ -1082,7 +1081,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 +1128,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 +1269,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 +1291,7 @@ void cmGlobalGenerator::Generate() this->WriteSummary(); - if (this->ExtraGenerator != 0) { + if (this->ExtraGenerator != CM_NULLPTR) { this->ExtraGenerator->Generate(); } @@ -1699,7 +1698,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 +1719,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: ", @@ -1946,7 +1947,7 @@ cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const return *it; } } - return 0; + return CM_NULLPTR; } ///! Find a local generator by its startdirectory @@ -1961,7 +1962,7 @@ cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator( return *it; } } - return 0; + return CM_NULLPTR; } void cmGlobalGenerator::AddAlias(const std::string& name, @@ -1995,7 +1996,7 @@ cmTarget* cmGlobalGenerator::FindTargetImpl(std::string const& name) const if (i != this->TargetSearchIndex.end()) { return i->second; } - return 0; + return CM_NULLPTR; } cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl( @@ -2006,7 +2007,7 @@ cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl( if (i != this->GeneratorTargetSearchIndex.end()) { return i->second; } - return 0; + return CM_NULLPTR; } cmTarget* cmGlobalGenerator::FindTarget(const std::string& name, @@ -2136,7 +2137,7 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) cpackCommandLines.push_back(singleLine); (*targets)[this->GetTestTargetName()] = this->CreateGlobalTarget(this->GetTestTargetName(), "Running tests...", - &cpackCommandLines, depends, 0, + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ true); } @@ -2157,7 +2158,7 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) cpackCommandLines.push_back(singleLine); (*targets)[editCacheTargetName] = this->CreateGlobalTarget( editCacheTargetName, "Running CMake cache editor...", - &cpackCommandLines, depends, 0, /*uses_terminal*/ true); + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ true); } else { singleLine.push_back(cmSystemTools::GetCMakeCommand()); singleLine.push_back("-E"); @@ -2166,7 +2167,7 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) cpackCommandLines.push_back(singleLine); (*targets)[editCacheTargetName] = this->CreateGlobalTarget( editCacheTargetName, "No interactive CMake dialog available...", - &cpackCommandLines, depends, 0, /*uses_terminal*/ false); + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ false); } } @@ -2183,15 +2184,16 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) cpackCommandLines.push_back(singleLine); (*targets)[rebuildCacheTargetName] = this->CreateGlobalTarget( rebuildCacheTargetName, "Running CMake to regenerate build system...", - &cpackCommandLines, depends, 0, /*uses_terminal*/ true); + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ true); } // Install 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; @@ -2208,7 +2210,7 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) singleLine.push_back(ostr.str()); (*targets)["list_install_components"] = this->CreateGlobalTarget( "list_install_components", ostr.str().c_str(), &cpackCommandLines, - depends, 0, /*uses_terminal*/ false); + depends, CM_NULLPTR, /*uses_terminal*/ false); } std::string cmd = cmSystemTools::GetCMakeCommand(); cpackCommandLines.erase(cpackCommandLines.begin(), @@ -2249,7 +2251,7 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) cpackCommandLines.push_back(singleLine); (*targets)[this->GetInstallTargetName()] = this->CreateGlobalTarget( this->GetInstallTargetName(), "Install the project...", - &cpackCommandLines, depends, 0, /*uses_terminal*/ true); + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ true); // install_local if (const char* install_local = this->GetInstallLocalTargetName()) { @@ -2263,12 +2265,12 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) (*targets)[install_local] = this->CreateGlobalTarget( install_local, "Installing only the local directory...", - &cpackCommandLines, depends, 0, /*uses_terminal*/ true); + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ true); } // 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"))) { cmCustomCommandLine stripCmdLine = singleLine; stripCmdLine.insert(stripCmdLine.begin() + 1, @@ -2279,7 +2281,7 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) (*targets)[install_strip] = this->CreateGlobalTarget( install_strip, "Installing the project stripped...", - &cpackCommandLines, depends, 0, /*uses_terminal*/ true); + &cpackCommandLines, depends, CM_NULLPTR, /*uses_terminal*/ true); } } } @@ -2327,8 +2329,8 @@ cmTarget cmGlobalGenerator::CreateGlobalTarget( 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); + cmCustomCommand cc(CM_NULLPTR, no_outputs, no_byproducts, no_depends, + *commandLines, CM_NULLPTR, workingDirectory); cc.SetUsesTerminal(uses_terminal); target.AddPostBuildCommand(cc); target.SetProperty("EchoString", message); @@ -2406,7 +2408,7 @@ void cmGlobalGenerator::SetExternalMakefileProjectGenerator( cmExternalMakefileProjectGenerator* extraGenerator) { this->ExtraGenerator = extraGenerator; - if (this->ExtraGenerator != 0) { + if (this->ExtraGenerator != CM_NULLPTR) { this->ExtraGenerator->SetGlobalGenerator(this); } } @@ -2571,7 +2573,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..089a637 100644 --- a/Source/cmGlobalGenerator.h +++ b/Source/cmGlobalGenerator.h @@ -25,7 +25,7 @@ #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> @@ -277,15 +277,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 +319,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; @@ -433,7 +433,7 @@ 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; @@ -503,7 +503,7 @@ private: void ClearGeneratorMembers(); - virtual const char* GetBuildIgnoreErrorsFlag() const { return 0; } + 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..74d3145 100644 --- a/Source/cmGlobalGeneratorFactory.h +++ b/Source/cmGlobalGeneratorFactory.h @@ -41,6 +41,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 +51,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.h b/Source/cmGlobalGhsMultiGenerator.h index 473d153..b2aac45 100644 --- a/Source/cmGlobalGhsMultiGenerator.h +++ b/Source/cmGlobalGhsMultiGenerator.h @@ -52,6 +52,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/cmGlobalKdevelopGenerator.cxx b/Source/cmGlobalKdevelopGenerator.cxx index 5c1e733..daf7003 100644 --- a/Source/cmGlobalKdevelopGenerator.cxx +++ b/Source/cmGlobalKdevelopGenerator.cxx @@ -25,20 +25,28 @@ #include <cmsys/FStream.hxx> #include <cmsys/SystemTools.hxx> -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 +119,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 +150,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 +174,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 +221,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 +304,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..666527c 100644 --- a/Source/cmGlobalKdevelopGenerator.h +++ b/Source/cmGlobalKdevelopGenerator.h @@ -33,20 +33,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/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx index 143ad92..3b8aaa6 100644 --- a/Source/cmGlobalNinjaGenerator.cxx +++ b/Source/cmGlobalNinjaGenerator.cxx @@ -30,8 +30,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 +44,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; @@ -165,16 +167,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"; @@ -198,9 +202,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; @@ -430,16 +435,17 @@ 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) @@ -487,6 +493,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 +515,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,8 +533,8 @@ 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); } } @@ -546,11 +554,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 +680,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 +721,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."); } @@ -799,7 +809,7 @@ void cmGlobalNinjaGenerator::CloseCompileCommandsStream() if (this->CompileCommandsStream) { *this->CompileCommandsStream << "\n]"; delete this->CompileCommandsStream; - this->CompileCommandsStream = 0; + this->CompileCommandsStream = CM_NULLPTR; } } @@ -857,6 +867,7 @@ void cmGlobalNinjaGenerator::AppendTargetOutputs( break; } case cmState::OBJECT_LIBRARY: + case cmState::GLOBAL_TARGET: case cmState::UTILITY: { std::string path = target->GetLocalGenerator()->GetCurrentBinaryDirectory() + @@ -865,12 +876,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 +885,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 +909,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 +953,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 +974,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); @@ -1227,9 +1276,9 @@ std::string cmGlobalNinjaGenerator::ninjaCmd() const bool cmGlobalNinjaGenerator::SupportsConsolePool() const { - return cmSystemTools::VersionCompare( - cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), - RequiredNinjaVersionForConsolePool().c_str()) == false; + return !cmSystemTools::VersionCompare( + cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), + RequiredNinjaVersionForConsolePool().c_str()); } void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os) diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h index 6d9bfe8..52fa5c9 100644 --- a/Source/cmGlobalNinjaGenerator.h +++ b/Source/cmGlobalNinjaGenerator.h @@ -81,6 +81,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. @@ -93,7 +99,7 @@ public: 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. @@ -161,11 +167,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 +180,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 +301,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,7 +320,7 @@ 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"; } @@ -319,13 +332,13 @@ public: void StripNinjaOutputPathPrefixAsSuffix(std::string& path); 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 OpenBuildFileStream(); void CloseBuildFileStream(); @@ -350,6 +363,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,6 +416,11 @@ 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; diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx index cc5d1ba..f115ecb 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.cxx +++ b/Source/cmGlobalUnixMakefileGenerator3.cxx @@ -32,7 +32,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 +155,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 +166,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"; diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h index f951b2a..ceb4140 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.h +++ b/Source/cmGlobalUnixMakefileGenerator3.h @@ -63,7 +63,7 @@ public: } ///! Get the name for the generator. - virtual std::string GetName() const + std::string GetName() const CM_OVERRIDE { return cmGlobalUnixMakefileGenerator3::GetActualName(); } @@ -75,26 +75,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 +122,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 +144,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 +171,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 +240,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..df831e5 100644 --- a/Source/cmGlobalVisualStudio10Generator.cxx +++ b/Source/cmGlobalVisualStudio10Generator.cxx @@ -42,8 +42,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 +65,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 +101,7 @@ cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator( this->SystemIsWindowsPhone = false; this->SystemIsWindowsStore = false; this->MSBuildCommandInitialized = false; + this->DefaultPlatformToolset = "v100"; this->Version = VS10; } diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx index 295b6eb..1478a17 100644 --- a/Source/cmGlobalVisualStudio11Generator.cxx +++ b/Source/cmGlobalVisualStudio11Generator.cxx @@ -36,8 +36,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 +70,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 +91,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/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx index 318cb39..3047171 100644 --- a/Source/cmGlobalVisualStudio12Generator.cxx +++ b/Source/cmGlobalVisualStudio12Generator.cxx @@ -36,8 +36,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 +59,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/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx index e190e84..254682c 100644 --- a/Source/cmGlobalVisualStudio14Generator.cxx +++ b/Source/cmGlobalVisualStudio14Generator.cxx @@ -36,8 +36,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 +59,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/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index a33bd8b..0a83b3a 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -122,9 +122,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); } @@ -674,7 +674,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..8a33ee0 100644 --- a/Source/cmGlobalVisualStudio7Generator.h +++ b/Source/cmGlobalVisualStudio7Generator.h @@ -48,6 +48,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..2c0168e 100644 --- a/Source/cmGlobalVisualStudio8Generator.cxx +++ b/Source/cmGlobalVisualStudio8Generator.cxx @@ -25,8 +25,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 +60,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 +82,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/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx index a47f4fc..acc7baa 100644 --- a/Source/cmGlobalVisualStudio9Generator.cxx +++ b/Source/cmGlobalVisualStudio9Generator.cxx @@ -23,8 +23,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 +62,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 +85,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/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx index 1bec581..7bdd74d 100644 --- a/Source/cmGlobalVisualStudioGenerator.cxx +++ b/Source/cmGlobalVisualStudioGenerator.cxx @@ -827,6 +827,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 +837,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..1d456ff 100644 --- a/Source/cmGlobalVisualStudioGenerator.h +++ b/Source/cmGlobalVisualStudioGenerator.h @@ -85,7 +85,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.h b/Source/cmGlobalWatcomWMakeGenerator.h index 3954907..bc0d786 100644 --- a/Source/cmGlobalWatcomWMakeGenerator.h +++ b/Source/cmGlobalWatcomWMakeGenerator.h @@ -28,7 +28,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 +41,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..780ca90 100644 --- a/Source/cmGlobalXCodeGenerator.cxx +++ b/Source/cmGlobalXCodeGenerator.cxx @@ -24,7 +24,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 +108,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 +176,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, " @@ -659,7 +660,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 +690,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 +700,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 +739,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile( this->ResourcesGroupChildren->AddObject(fileRef); } - buildFile->AddAttribute("settings", settings); + buildFile->AddAttributeIfNotEmpty("settings", settings); return buildFile; } @@ -772,6 +788,8 @@ std::string GetSourcecodeValueFromFileExtension(const std::string& _ext, sourcecode += ".asm"; } else if (ext == "metal") { sourcecode += ".metal"; + } else if (ext == "mig") { + sourcecode += ".mig"; } // else // { @@ -1544,7 +1562,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 +1580,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( } cmd += cmd2; ccg.AppendArguments(c, cmd); - makefileStream << "\t" << cmd.c_str() << "\n"; + makefileStream << "\t" << cmd << "\n"; } } } @@ -1784,6 +1802,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 +1844,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 +1883,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 +1907,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->c_str())) { + 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 +2025,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; @@ -3437,7 +3490,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..0485d4f 100644 --- a/Source/cmGlobalXCodeGenerator.h +++ b/Source/cmGlobalXCodeGenerator.h @@ -79,7 +79,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); diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx index 20cd171..adb9936 100644 --- a/Source/cmGraphVizWriter.cxx +++ b/Source/cmGraphVizWriter.cxx @@ -64,9 +64,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; @@ -140,7 +139,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 +148,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 +183,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 +192,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 +238,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 +277,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 +328,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 +339,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 +402,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 +426,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 +467,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/cmHexFileConverter.cxx b/Source/cmHexFileConverter.cxx index 9609e95..34fd626 100644 --- a/Source/cmHexFileConverter.cxx +++ b/Source/cmHexFileConverter.cxx @@ -28,7 +28,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)); @@ -144,7 +144,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 +193,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 +206,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/cmIfCommand.cxx b/Source/cmIfCommand.cxx index 45395d1..dd04136 100644 --- a/Source/cmIfCommand.cxx +++ b/Source/cmIfCommand.cxx @@ -46,8 +46,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,12 +184,12 @@ 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; + return true; } else { this->Makefile->IssueMessage(status, err); } diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h index 54200df..f1f979d 100644 --- a/Source/cmIfCommand.h +++ b/Source/cmIfCommand.h @@ -24,10 +24,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 +43,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 +65,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..360ebeb 100644 --- a/Source/cmIncludeCommand.cxx +++ b/Source/cmIncludeCommand.cxx @@ -77,7 +77,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..365a830 100644 --- a/Source/cmIncludeCommand.h +++ b/Source/cmIncludeCommand.h @@ -26,24 +26,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.h b/Source/cmIncludeDirectoryCommand.h index 952294b..25be709 100644 --- a/Source/cmIncludeDirectoryCommand.h +++ b/Source/cmIncludeDirectoryCommand.h @@ -26,19 +26,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.h b/Source/cmIncludeExternalMSProjectCommand.h index 999eb9e..8cda7b9 100644 --- a/Source/cmIncludeExternalMSProjectCommand.h +++ b/Source/cmIncludeExternalMSProjectCommand.h @@ -27,19 +27,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.h b/Source/cmIncludeRegularExpressionCommand.h index 1071a7a..52fdff0 100644 --- a/Source/cmIncludeRegularExpressionCommand.h +++ b/Source/cmIncludeRegularExpressionCommand.h @@ -26,19 +26,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..86ab85a 100644 --- a/Source/cmInstallCommand.cxx +++ b/Source/cmInstallCommand.cxx @@ -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(); @@ -373,14 +373,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 +407,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 +622,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 +706,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 +746,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 +822,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; @@ -1103,7 +1105,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; diff --git a/Source/cmInstallCommand.h b/Source/cmInstallCommand.h index 93aca45..3718ad5 100644 --- a/Source/cmInstallCommand.h +++ b/Source/cmInstallCommand.h @@ -26,19 +26,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); diff --git a/Source/cmInstallCommandArguments.cxx b/Source/cmInstallCommandArguments.cxx index 57e37a3..312c50e 100644 --- a/Source/cmInstallCommandArguments.cxx +++ b/Source/cmInstallCommandArguments.cxx @@ -17,7 +17,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 +35,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 +45,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 +56,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 +71,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 +82,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 +93,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 +104,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 +115,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 +126,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 +138,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/cmInstallDirectoryGenerator.cxx b/Source/cmInstallDirectoryGenerator.cxx index 671ab4c..3928231 100644 --- a/Source/cmInstallDirectoryGenerator.cxx +++ b/Source/cmInstallDirectoryGenerator.cxx @@ -22,7 +22,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,7 +69,7 @@ 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); } @@ -81,7 +81,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..93becf4 100644 --- a/Source/cmInstallDirectoryGenerator.h +++ b/Source/cmInstallDirectoryGenerator.h @@ -27,17 +27,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/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx index 2fef3a8..0fcd8ba 100644 --- a/Source/cmInstallExportGenerator.cxx +++ b/Source/cmInstallExportGenerator.cxx @@ -37,7 +37,7 @@ cmInstallExportGenerator::cmInstallExportGenerator( , FileName(filename) , Namespace(name_space) , ExportOld(exportOld) - , LocalGenerator(0) + , LocalGenerator(CM_NULLPTR) { this->EFGen = new cmExportInstallFileGenerator(this); exportSet->AddInstallation(this); @@ -74,9 +74,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 +105,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 +184,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 +224,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..22e661b 100644 --- a/Source/cmInstallExportGenerator.h +++ b/Source/cmInstallExportGenerator.h @@ -32,11 +32,11 @@ public: const char* component, MessageLevel message, bool exclude_from_all, const char* filename, const char* name_space, bool exportOld); - ~cmInstallExportGenerator(); + ~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 +45,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.h b/Source/cmInstallFilesCommand.h index 0d0388a..cf2c9ff 100644 --- a/Source/cmInstallFilesCommand.h +++ b/Source/cmInstallFilesCommand.h @@ -26,19 +26,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 +46,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..93a740c 100644 --- a/Source/cmInstallFilesGenerator.cxx +++ b/Source/cmInstallFilesGenerator.cxx @@ -23,7 +23,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 +65,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 +90,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..5cb09f4 100644 --- a/Source/cmInstallFilesGenerator.h +++ b/Source/cmInstallFilesGenerator.h @@ -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.h b/Source/cmInstallGenerator.h index e271d53..ad9fc28 100644 --- a/Source/cmInstallGenerator.h +++ b/Source/cmInstallGenerator.h @@ -37,15 +37,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 +59,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.h b/Source/cmInstallProgramsCommand.h index b104c69..b56a9b1 100644 --- a/Source/cmInstallProgramsCommand.h +++ b/Source/cmInstallProgramsCommand.h @@ -26,19 +26,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 +46,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..76d6b71 100644 --- a/Source/cmInstallScriptGenerator.cxx +++ b/Source/cmInstallScriptGenerator.cxx @@ -15,7 +15,7 @@ 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..dc00359 100644 --- a/Source/cmInstallScriptGenerator.h +++ b/Source/cmInstallScriptGenerator.h @@ -22,10 +22,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..4b2f40c 100644 --- a/Source/cmInstallTargetGenerator.cxx +++ b/Source/cmInstallTargetGenerator.cxx @@ -30,7 +30,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 +142,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 +303,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 +632,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..b1c28b8 100644 --- a/Source/cmInstallTargetGenerator.h +++ b/Source/cmInstallTargetGenerator.h @@ -27,7 +27,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 +54,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 +63,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.h b/Source/cmInstallTargetsCommand.h index b0d04b0..b7d7f33 100644 --- a/Source/cmInstallTargetsCommand.h +++ b/Source/cmInstallTargetsCommand.h @@ -27,19 +27,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/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx index ed0f74b..bfc5cf1 100644 --- a/Source/cmInstalledFile.cxx +++ b/Source/cmInstalledFile.cxx @@ -16,7 +16,7 @@ #include "cmSystemTools.h" cmInstalledFile::cmInstalledFile() - : NameExpression(0) + : NameExpression(CM_NULLPTR) { } diff --git a/Source/cmInstalledFile.h b/Source/cmInstalledFile.h index d000891..00ff611 100644 --- a/Source/cmInstalledFile.h +++ b/Source/cmInstalledFile.h @@ -22,7 +22,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.h b/Source/cmLinkDirectoriesCommand.h index 7014a69..721d663 100644 --- a/Source/cmLinkDirectoriesCommand.h +++ b/Source/cmLinkDirectoriesCommand.h @@ -28,19 +28,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..8aa3981 100644 --- a/Source/cmLinkItem.h +++ b/Source/cmLinkItem.h @@ -26,7 +26,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 +118,7 @@ struct cmOptionalLinkInterface : public cmLinkInterface , AllDone(false) , Exists(false) , HadHeadSensitiveCondition(false) - , ExplicitLibraries(0) + , ExplicitLibraries(CM_NULLPTR) { } bool LibrariesDone; diff --git a/Source/cmLinkLibrariesCommand.h b/Source/cmLinkLibrariesCommand.h index 6ab50ce..45cc4d7 100644 --- a/Source/cmLinkLibrariesCommand.h +++ b/Source/cmLinkLibrariesCommand.h @@ -27,19 +27,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..6b31074 100644 --- a/Source/cmLinkedTree.h +++ b/Source/cmLinkedTree.h @@ -56,7 +56,7 @@ public: public: iterator() - : Tree(0) + : Tree(CM_NULLPTR) , Position(0) { } diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h index 56d9694..1c33c96 100644 --- a/Source/cmListCommand.h +++ b/Source/cmListCommand.h @@ -24,24 +24,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..28b3781 100644 --- a/Source/cmListFileCache.cxx +++ b/Source/cmListFileCache.cxx @@ -23,6 +23,7 @@ struct cmListFileParser { cmListFileParser(cmListFile* lf, cmMakefile* mf, const char* filename); ~cmListFileParser(); + void IssueFileOpenError(std::string const& text) const; bool ParseFile(); bool ParseFunction(const char* name, long line); bool AddArgument(cmListFileLexer_Token* token, @@ -54,23 +55,25 @@ cmListFileParser::~cmListFileParser() cmListFileLexer_Delete(this->Lexer); } +void cmListFileParser::IssueFileOpenError(const std::string& text) const +{ + this->Makefile->IssueMessage(cmake::FATAL_ERROR, text); +} + 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; } @@ -115,7 +118,7 @@ bool cmListFileParser::ParseFile() return true; } -bool cmListFile::ParseFile(const char* filename, bool topLevel, cmMakefile* mf) +bool cmListFile::ParseFile(const char* filename, cmMakefile* mf) { if (!cmSystemTools::FileExists(filename) || cmSystemTools::FileIsDirectory(filename)) { @@ -129,83 +132,7 @@ bool cmListFile::ParseFile(const char* filename, bool topLevel, cmMakefile* mf) 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) @@ -387,13 +314,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) { } diff --git a/Source/cmListFileCache.h b/Source/cmListFileCache.h index d72c360..f3e6f70 100644 --- a/Source/cmListFileCache.h +++ b/Source/cmListFileCache.h @@ -158,7 +158,7 @@ private: struct cmListFile { - bool ParseFile(const char* path, bool topLevel, cmMakefile* mf); + bool ParseFile(const char* path, cmMakefile* mf); std::vector<cmListFileFunction> Functions; }; diff --git a/Source/cmLoadCacheCommand.h b/Source/cmLoadCacheCommand.h index 67d93ac..0755809 100644 --- a/Source/cmLoadCacheCommand.h +++ b/Source/cmLoadCacheCommand.h @@ -25,19 +25,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..ddf6ce6 100644 --- a/Source/cmLoadCommandCommand.cxx +++ b/Source/cmLoadCommandCommand.cxx @@ -37,12 +37,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 +54,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 +63,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 +72,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 +94,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 +112,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 +128,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*)); } diff --git a/Source/cmLoadCommandCommand.h b/Source/cmLoadCommandCommand.h index e00a01e..6552845 100644 --- a/Source/cmLoadCommandCommand.h +++ b/Source/cmLoadCommandCommand.h @@ -17,10 +17,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..5502296 100644 --- a/Source/cmLocalCommonGenerator.cxx +++ b/Source/cmLocalCommonGenerator.cxx @@ -13,9 +13,10 @@ #include "cmMakefile.h" -cmLocalCommonGenerator::cmLocalCommonGenerator(cmGlobalGenerator* gg, - cmMakefile* mf) +cmLocalCommonGenerator::cmLocalCommonGenerator( + cmGlobalGenerator* gg, cmMakefile* mf, cmOutputConverter::RelativeRoot wd) : cmLocalGenerator(gg, mf) + , WorkingDirectory(wd) { } @@ -34,3 +35,50 @@ 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(); + 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->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->Convert(*idi, cmOutputConverter::NONE, cmOutputConverter::SHELL); + this->AppendFlags(flags, flg); + } + } + + return flags; +} diff --git a/Source/cmLocalCommonGenerator.h b/Source/cmLocalCommonGenerator.h index d282054..0a8753d 100644 --- a/Source/cmLocalCommonGenerator.h +++ b/Source/cmLocalCommonGenerator.h @@ -22,12 +22,23 @@ class cmCommonTargetGenerator; class cmLocalCommonGenerator : public cmLocalGenerator { public: - cmLocalCommonGenerator(cmGlobalGenerator* gg, cmMakefile* mf); - ~cmLocalCommonGenerator(); + cmLocalCommonGenerator(cmGlobalGenerator* gg, cmMakefile* mf, + cmOutputConverter::RelativeRoot wd); + ~cmLocalCommonGenerator() CM_OVERRIDE; std::string const& GetConfigName() { return this->ConfigName; } + cmOutputConverter::RelativeRoot GetWorkingDirectory() const + { + return this->WorkingDirectory; + } + + std::string GetTargetFortranFlags(cmGeneratorTarget const* target, + std::string const& config) CM_OVERRIDE; + protected: + cmOutputConverter::RelativeRoot WorkingDirectory; + void SetConfigName(); std::string ConfigName; diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index e91eb46..2f29791 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -45,6 +45,7 @@ cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile) : cmOutputConverter(makefile->GetStateSnapshot()) , StateSnapshot(makefile->GetStateSnapshot()) + , DirectoryBacktrace(makefile->GetBacktrace()) { this->GlobalGenerator = gg; @@ -68,7 +69,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() @@ -271,7 +272,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 +445,7 @@ cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget( if (ti != this->GeneratorTargets.end()) { return *ti; } - return 0; + return CM_NULLPTR; } void cmLocalGenerator::ComputeTargetManifest() @@ -507,7 +508,7 @@ static const char* ruleReplaceVars[] = { "CMAKE_RANLIB", "CMAKE_LINKER", "CMAKE_CL_SHOWINCLUDES_PREFIX", - 0 + CM_NULLPTR }; std::string cmLocalGenerator::ExpandRuleVariable( @@ -703,13 +704,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); @@ -831,8 +832,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 +872,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 +944,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 +1153,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 @@ -1273,6 +1272,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.c_str()); +} + +std::string cmLocalGenerator::GetTargetFortranFlags(cmGeneratorTarget const*, + std::string const&) +{ + // Implemented by specific generators that override this. + return std::string(); +} + std::string cmLocalGenerator::ConvertToLinkReference(std::string const& lib, OutputFormat format) { @@ -1350,7 +1455,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()); } @@ -1398,7 +1503,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; @@ -1475,16 +1580,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"; @@ -1824,7 +1925,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 +2036,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 +2100,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 +2114,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 +2217,7 @@ const char* cmLocalGenerator::GetFeature(const std::string& feature, } snp = snp.GetBuildsystemDirectoryParent(); } - return 0; + return CM_NULLPTR; } std::string cmLocalGenerator::GetProjectName() const @@ -2178,7 +2280,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 +2333,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); } } diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h index 5c603a6..fa4bb30 100644 --- a/Source/cmLocalGenerator.h +++ b/Source/cmLocalGenerator.h @@ -138,13 +138,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 +202,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 +300,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 +310,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 +378,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/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx index 6c231c3..46d7e18 100644 --- a/Source/cmLocalNinjaGenerator.cxx +++ b/Source/cmLocalNinjaGenerator.cxx @@ -25,7 +25,7 @@ cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg, cmMakefile* mf) - : cmLocalCommonGenerator(gg, mf) + : cmLocalCommonGenerator(gg, mf, cmOutputConverter::HOME_OUTPUT) , HomeRelativeOutputPath("") { this->TargetImplib = "$TARGET_IMPLIB"; @@ -81,8 +81,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; } } @@ -257,8 +258,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 +284,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 +297,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 +336,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 +366,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 +397,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); @@ -443,13 +450,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(), diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h index 9899360..6e61087 100644 --- a/Source/cmLocalNinjaGenerator.h +++ b/Source/cmLocalNinjaGenerator.h @@ -34,12 +34,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 +72,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..75970772 100644 --- a/Source/cmLocalUnixMakefileGenerator3.cxx +++ b/Source/cmLocalUnixMakefileGenerator3.cxx @@ -30,8 +30,8 @@ #include "cmDependsJava.h" #endif +#include <cm_auto_ptr.hxx> #include <cmsys/Terminal.h> -#include <cmsys/auto_ptr.hxx> #include <algorithm> #include <queue> @@ -84,7 +84,7 @@ static std::string cmSplitExtension(std::string const& in, std::string& base) cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3( cmGlobalGenerator* gg, cmMakefile* mf) - : cmLocalCommonGenerator(gg, mf) + : cmLocalCommonGenerator(gg, mf, cmOutputConverter::START_OUTPUT) { this->MakefileVariableSize = 0; this->ColorMakefile = false; @@ -121,7 +121,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(); @@ -340,8 +340,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; } @@ -703,8 +703,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 @@ -1164,7 +1164,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 +1322,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 +1433,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); @@ -2068,19 +2068,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(relRetDir); 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..42d1d91 100644 --- a/Source/cmLocalUnixMakefileGenerator3.h +++ b/Source/cmLocalUnixMakefileGenerator3.h @@ -33,14 +33,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 +90,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,13 +110,14 @@ 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, @@ -130,11 +132,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); @@ -235,10 +237,11 @@ protected: std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg, cmGeneratorTarget* target, bool echo_comment = false, cmOutputConverter::RelativeRoot relative = cmOutputConverter::HOME_OUTPUT, - std::ostream* content = 0); + 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( @@ -253,9 +256,9 @@ private: cmGeneratorTarget* target, cmOutputConverter::RelativeRoot relative); - 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 +275,7 @@ private: cmGeneratorTarget* Target; std::string Language; LocalObjectEntry() - : Target(0) + : Target(CM_NULLPTR) , Language() { } diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index 6e7d7d2..e72abe9 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -683,7 +683,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; @@ -1012,7 +1013,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"); @@ -1474,7 +1476,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 +1689,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 +1837,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 +1852,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/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx index 85ab615..bdb1c2b 100644 --- a/Source/cmLocalVisualStudioGenerator.cxx +++ b/Source/cmLocalVisualStudioGenerator.cxx @@ -74,12 +74,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. diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h index c24d813..87acda2 100644 --- a/Source/cmLocalVisualStudioGenerator.h +++ b/Source/cmLocalVisualStudioGenerator.h @@ -16,7 +16,7 @@ #include "cmGlobalVisualStudioGenerator.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> class cmSourceFile; class cmSourceGroup; @@ -59,8 +59,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/cmLocale.h b/Source/cmLocale.h index e69c32e..f922c03 100644 --- a/Source/cmLocale.h +++ b/Source/cmLocale.h @@ -22,7 +22,7 @@ class cmLocaleRAII public: cmLocaleRAII() - : OldLocale(setlocale(LC_CTYPE, 0)) + : OldLocale(setlocale(LC_CTYPE, CM_NULLPTR)) { setlocale(LC_CTYPE, ""); } diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx index 2caa401..ee9dc8a 100644 --- a/Source/cmMacroCommand.cxx +++ b/Source/cmMacroCommand.cxx @@ -21,7 +21,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 +29,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 +48,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 +66,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); diff --git a/Source/cmMacroCommand.h b/Source/cmMacroCommand.h index 11d2e1c..541b54f 100644 --- a/Source/cmMacroCommand.h +++ b/Source/cmMacroCommand.h @@ -20,10 +20,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 +37,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.h b/Source/cmMakeDirectoryCommand.h index 1a86398..de4ab8b 100644 --- a/Source/cmMakeDirectoryCommand.h +++ b/Source/cmMakeDirectoryCommand.h @@ -29,24 +29,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..ab7de57 100644 --- a/Source/cmMakefile.cxx +++ b/Source/cmMakefile.cxx @@ -35,9 +35,10 @@ #include "cmake.h" #include <stdlib.h> // required for atoi +#include <cm_auto_ptr.hxx> #include <cmsys/FStream.hxx> #include <cmsys/RegularExpression.hxx> -#include <cmsys/auto_ptr.hxx> +#include <cmsys/SystemTools.hxx> #include <assert.h> #include <ctype.h> // for isspace @@ -105,8 +106,8 @@ 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()) { @@ -114,7 +115,7 @@ void cmMakefile::IssueMessage(cmake::MessageType t, std::string const& text, 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 +176,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 +262,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 +276,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 +449,7 @@ 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)) { return false; } @@ -475,7 +498,7 @@ 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)) { 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); } } @@ -761,7 +786,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput( // Make sure there is at least one output. if (outputs.empty()) { cmSystemTools::Error("Attempt to add a custom rule with no output!"); - return 0; + return CM_NULLPTR; } // Validate custom commands. TODO: More strict? @@ -772,12 +797,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. @@ -791,7 +816,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput( } else { // The existing custom command is different. We need to // generate a rule file for this new command. - file = 0; + file = CM_NULLPTR; } } else if (!file) { file = this->CreateSource(main_dependency); @@ -912,7 +937,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,14 +955,14 @@ 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), @@ -1420,10 +1445,81 @@ 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)) { 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 +1816,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 } @@ -1854,7 +1950,7 @@ cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput( } // otherwise return NULL - return 0; + return CM_NULLPTR; } cmSourceFile* cmMakefile::GetSourceFileWithOutput( @@ -1870,14 +1966,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 +1986,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 +2008,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; } } @@ -1946,7 +2042,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 +2145,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 +2174,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 +2230,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 +2263,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 +2570,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 +2585,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 +2626,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. @@ -2792,7 +2892,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 +3029,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 +3062,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 +3110,7 @@ cmSourceFile* cmMakefile::GetSource(const std::string& sourceName) const return sf; } } - return 0; + return CM_NULLPTR; } cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName, @@ -3180,7 +3280,7 @@ cmVariableWatch* cmMakefile::GetVariableWatch() const this->GetCMakeInstance()->GetVariableWatch()) { return this->GetCMakeInstance()->GetVariableWatch(); } - return 0; + return CM_NULLPTR; } #endif @@ -3341,8 +3441,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 +3484,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 +3525,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 +3581,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 +3603,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,7 +3694,7 @@ cmTarget* cmMakefile::AddImportedTarget(const std::string& name, cmState::TargetType type, bool global) { // Create the target. - cmsys::auto_ptr<cmTarget> target(new cmTarget); + CM_AUTO_PTR<cmTarget> target(new cmTarget); target->SetType(type, name); target->MarkAsImported(global); target->SetMakefile(this); @@ -3629,8 +3729,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); } @@ -3963,10 +4064,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 +4103,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 +4152,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 +4178,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; } @@ -4257,7 +4366,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 +4383,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 +4453,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 +4469,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..d07b4e1 100644 --- a/Source/cmMakefile.h +++ b/Source/cmMakefile.h @@ -28,10 +28,10 @@ #include "cmSourceGroup.h" #endif +#include <cm_auto_ptr.hxx> #include <cmsys/RegularExpression.hxx> -#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> @@ -97,7 +97,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); /** @@ -182,24 +182,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 +273,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 +436,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 +518,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,11 +591,11 @@ 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 @@ -643,8 +645,9 @@ public: void AddInstallGenerator(cmInstallGenerator* g) { - if (g) + if (g) { this->InstallGenerators.push_back(g); + } } std::vector<cmInstallGenerator*>& GetInstallGenerators() { @@ -653,8 +656,9 @@ public: void AddTestGenerator(cmTestGenerator* g) { - if (g) + if (g) { this->TestGenerators.push_back(g); + } } const std::vector<cmTestGenerator*>& GetTestGenerators() const { @@ -715,8 +719,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 +742,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 +771,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 +794,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; @@ -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..3b8bf5a 100644 --- a/Source/cmMakefileExecutableTargetGenerator.cxx +++ b/Source/cmMakefileExecutableTargetGenerator.cxx @@ -187,6 +187,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) this->LocalGenerator->AppendFlags( linkFlags, this->Makefile->GetDefinition(export_flag_var)); } + if (this->GeneratorTarget->GetProperty("LINK_WHAT_YOU_USE")) { + this->LocalGenerator->AppendFlags(linkFlags, " -Wl,--no-as-needed"); + } // Add language feature flags. this->AddFeatureFlags(flags, linkLanguage); @@ -274,27 +277,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 +301,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; @@ -356,6 +348,15 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) vars.LinkFlags = linkFlags.c_str(); vars.Manifests = manifests.c_str(); + if (this->GeneratorTarget->GetProperty("LINK_WHAT_YOU_USE")) { + std::string cmakeCommand = + this->Convert(cmSystemTools::GetCMakeCommand(), cmLocalGenerator::NONE, + 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(); @@ -406,8 +407,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) } // 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 +418,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..39def27 100644 --- a/Source/cmMakefileExecutableTargetGenerator.h +++ b/Source/cmMakefileExecutableTargetGenerator.h @@ -18,11 +18,11 @@ 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..68f8ff1 100644 --- a/Source/cmMakefileLibraryTargetGenerator.cxx +++ b/Source/cmMakefileLibraryTargetGenerator.cxx @@ -111,7 +111,7 @@ void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules() 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 +163,9 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink) extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->ConfigName); this->AddModuleDefinitionFlag(extraFlags); + if (this->GeneratorTarget->GetProperty("LINK_WHAT_YOU_USE")) { + this->LocalGenerator->AppendFlags(extraFlags, " -Wl,--no-as-needed"); + } this->WriteLibraryRules(linkRuleVar, extraFlags, relink); } @@ -329,8 +332,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 +346,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"; @@ -425,27 +429,10 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( // 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 +441,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 +504,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(); @@ -677,12 +622,24 @@ 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->GetProperty("LINK_WHAT_YOU_USE") && + (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY)) { + std::string cmakeCommand = + this->Convert(cmSystemTools::GetCMakeCommand(), + cmLocalGenerator::NONE, 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(); @@ -729,6 +686,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( 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( @@ -746,8 +704,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..935d8b1 100644 --- a/Source/cmMakefileLibraryTargetGenerator.h +++ b/Source/cmMakefileLibraryTargetGenerator.h @@ -18,11 +18,11 @@ 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..e12fc09 100644 --- a/Source/cmMakefileTargetGenerator.cxx +++ b/Source/cmMakefileTargetGenerator.cxx @@ -31,14 +31,18 @@ #include <ctype.h> +#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 +65,7 @@ cmMakefileTargetGenerator::~cmMakefileTargetGenerator() cmMakefileTargetGenerator* cmMakefileTargetGenerator::New( cmGeneratorTarget* tgt) { - cmMakefileTargetGenerator* result = 0; + cmMakefileTargetGenerator* result = CM_NULLPTR; switch (tgt->GetType()) { case cmState::EXECUTABLE: @@ -134,12 +138,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); } @@ -320,7 +324,8 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()( 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); } @@ -652,7 +657,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(); @@ -708,7 +714,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); } @@ -754,7 +760,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 +772,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 +790,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 +823,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() @@ -837,8 +845,8 @@ void cmMakefileTargetGenerator::WriteTargetCleanRules() cmOutputConverter::HOME_OUTPUT); // 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 +856,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; } @@ -892,7 +900,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) { @@ -962,7 +970,7 @@ void cmMakefileTargetGenerator::WriteTargetDependRules() << "\n" << "# Fortran module output directory.\n" << "set(CMAKE_Fortran_TARGET_MODULE_DIR \"" - << this->GetFortranModuleDirectory() << "\")\n"; + << this->GeneratorTarget->GetFortranModuleDirectory() << "\")\n"; /* clang-format on */ // and now write the rule to use it @@ -1025,8 +1033,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( @@ -1088,8 +1096,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) { @@ -1254,7 +1262,7 @@ void cmMakefileTargetGenerator::WriteTargetDriverRule( 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."; @@ -1443,6 +1451,73 @@ void cmMakefileTargetGenerator::CreateLinkScript( 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 START_OUTPUT 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) @@ -1591,3 +1666,46 @@ 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->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.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->Convert(name_of_def_file, cmOutputConverter::START_OUTPUT, + cmOutputConverter::SHELL); + linkFlags += " "; + } +} diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h index c513026..29b8887 100644 --- a/Source/cmMakefileTargetGenerator.h +++ b/Source/cmMakefileTargetGenerator.h @@ -35,7 +35,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 +83,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 +151,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 +165,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..27006ee 100644 --- a/Source/cmMakefileUtilityTargetGenerator.cxx +++ b/Source/cmMakefileUtilityTargetGenerator.cxx @@ -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..b41fb8b 100644 --- a/Source/cmMakefileUtilityTargetGenerator.h +++ b/Source/cmMakefileUtilityTargetGenerator.h @@ -18,11 +18,11 @@ 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..2fb6a75 100644 --- a/Source/cmMarkAsAdvancedCommand.cxx +++ b/Source/cmMarkAsAdvancedCommand.cxx @@ -35,7 +35,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..bb1b83c 100644 --- a/Source/cmMarkAsAdvancedCommand.h +++ b/Source/cmMarkAsAdvancedCommand.h @@ -25,19 +25,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 +45,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.h b/Source/cmMathCommand.h index 3ac6f41..b99e790 100644 --- a/Source/cmMathCommand.h +++ b/Source/cmMathCommand.h @@ -21,24 +21,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..080880b 100644 --- a/Source/cmMessageCommand.cxx +++ b/Source/cmMessageCommand.cxx @@ -24,7 +24,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 +35,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 +49,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 +64,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 + cmake* cm = this->Makefile->GetCMakeInstance(); + cm->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..61767a1 100644 --- a/Source/cmMessageCommand.h +++ b/Source/cmMessageCommand.h @@ -24,24 +24,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/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx index 1386a04..7644df3 100644 --- a/Source/cmNinjaNormalTargetGenerator.cxx +++ b/Source/cmNinjaNormalTargetGenerator.cxx @@ -41,15 +41,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 +126,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 +146,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 +241,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 +273,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 +286,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 +299,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile) /*rspcontent*/ "", /*restat*/ "", /*generator*/ false); + } } } @@ -295,6 +313,22 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd() const char* linkCmd = mf->GetDefinition(linkCmdVar); if (linkCmd) { cmSystemTools::ExpandListArgument(linkCmd, linkCmds); + if (this->GetGeneratorTarget()->GetProperty("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, + /*realpath=*/true)); + cmakeCommand += targetOutputReal; + cmakeCommand += " || true"; + linkCmds.push_back(cmakeCommand); + } return linkCmds; } } @@ -340,7 +374,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 @@ -434,11 +468,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 +502,10 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() vars["MANIFESTS"] = this->GetManifests(); vars["LINK_PATH"] = frameworkPath + linkPath; + std::string lwyuFlags; + if (genTarget.GetProperty("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 +513,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; @@ -560,7 +600,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 = @@ -607,7 +648,6 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() vars["POST_BUILD"] = ":"; symlinkVars["POST_BUILD"] = postBuildCmdLine; } - cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator(); int commandLineLengthLimit = -1; diff --git a/Source/cmNinjaNormalTargetGenerator.h b/Source/cmNinjaNormalTargetGenerator.h index 300618c..f466e17 100644 --- a/Source/cmNinjaNormalTargetGenerator.h +++ b/Source/cmNinjaNormalTargetGenerator.h @@ -27,9 +27,9 @@ 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..9030e05 100644 --- a/Source/cmNinjaTargetGenerator.cxx +++ b/Source/cmNinjaTargetGenerator.cxx @@ -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())) @@ -130,11 +120,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 +161,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 +211,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 += "/"; @@ -238,8 +231,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 +294,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"; @@ -421,8 +415,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 +476,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(); @@ -519,8 +518,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 +527,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); @@ -656,8 +656,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 +713,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 +731,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..9740f0e 100644 --- a/Source/cmNinjaTargetGenerator.h +++ b/Source/cmNinjaTargetGenerator.h @@ -37,7 +37,7 @@ public: cmNinjaTargetGenerator(cmGeneratorTarget* target); /// Destructor. - virtual ~cmNinjaTargetGenerator(); + ~cmNinjaTargetGenerator() CM_OVERRIDE; virtual void Generate() = 0; @@ -79,7 +79,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); @@ -134,7 +135,8 @@ protected: { } - void operator()(cmSourceFile const& source, const char* pkgloc); + void operator()(cmSourceFile const& source, + const char* pkgloc) CM_OVERRIDE; private: cmNinjaTargetGenerator* Generator; @@ -156,6 +158,7 @@ private: /// List of object files for this target. cmNinjaDeps Objects; std::vector<cmCustomCommand const*> CustomCommands; + cmNinjaDeps ExtraFiles; }; #endif // ! cmNinjaTargetGenerator_h diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx index f7a7f38..96a17ff 100644 --- a/Source/cmNinjaUtilityTargetGenerator.cxx +++ b/Source/cmNinjaUtilityTargetGenerator.cxx @@ -31,10 +31,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 +59,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 +102,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 +126,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(); @@ -141,6 +146,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..0c33a54 100644 --- a/Source/cmNinjaUtilityTargetGenerator.h +++ b/Source/cmNinjaUtilityTargetGenerator.h @@ -23,9 +23,9 @@ 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..dbfe6eb 100644 --- a/Source/cmOSXBundleGenerator.cxx +++ b/Source/cmOSXBundleGenerator.cxx @@ -23,10 +23,11 @@ cmOSXBundleGenerator::cmOSXBundleGenerator(cmGeneratorTarget* 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 +38,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 +66,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 +95,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 +166,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 +191,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/cmOptionCommand.h b/Source/cmOptionCommand.h index 491f45e..6e6b076 100644 --- a/Source/cmOptionCommand.h +++ b/Source/cmOptionCommand.h @@ -25,24 +25,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..20f2246 100644 --- a/Source/cmOrderDirectories.cxx +++ b/Source/cmOrderDirectories.cxx @@ -157,7 +157,7 @@ public: } } - virtual void Report(std::ostream& e) + void Report(std::ostream& e) CM_OVERRIDE { e << "runtime library ["; if (this->SOName.empty()) { @@ -168,7 +168,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 +212,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..38e197c 100644 --- a/Source/cmOrderDirectories.h +++ b/Source/cmOrderDirectories.h @@ -30,7 +30,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..411184c 100644 --- a/Source/cmOutputConverter.cxx +++ b/Source/cmOutputConverter.cxx @@ -15,6 +15,7 @@ #include "cmake.h" #include <assert.h> +#include <sstream> #include <ctype.h> /* isalpha */ #include <string.h> /* strlen */ @@ -26,14 +27,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,31 +42,21 @@ 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); + // Otherwise, perform standard conversion. + return this->ConvertToOutputFormat(remote, format); } std::string cmOutputConverter::ConvertToOutputForExisting( - RelativeRoot remote, const std::string& local, OutputFormat format) const + RelativeRoot remote, OutputFormat format) const { - // Perform standard conversion. - std::string result = this->Convert(remote, local, format, true); + // The relative root must have a path (i.e. not FULL or NONE) + assert(remote != FULL); + assert(remote != NONE); - // Consider short-path. const char* remotePath = this->GetRelativeRootPath(remote); - return this->ConvertToOutputForExistingCommon(remotePath, result, format); + assert(remotePath != CM_NULLPTR); + + return this->ConvertToOutputForExisting(remotePath, format); } const char* cmOutputConverter::GetRelativeRootPath(RelativeRoot relroot) const @@ -82,7 +73,7 @@ const char* cmOutputConverter::GetRelativeRootPath(RelativeRoot relroot) const default: break; } - return 0; + return CM_NULLPTR; } std::string cmOutputConverter::Convert(const std::string& source, @@ -157,22 +148,23 @@ std::string cmOutputConverter::ConvertDirectorySeparatorsForShell( std::string cmOutputConverter::Convert(RelativeRoot remote, const std::string& local, - OutputFormat output, - bool optional) const + OutputFormat output) const { - const char* remotePath = this->GetRelativeRootPath(remote); - // The relative root must have a path (i.e. not FULL or NONE) - assert(remotePath != 0); + assert(remote != FULL); + assert(remote != NONE); + + const char* remotePath = this->GetRelativeRootPath(remote); + assert(remotePath != CM_NULLPTR); - 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); + if (local.empty()) { + return this->ConvertToOutputFormat(remotePath, output); } - return this->ConvertToOutputFormat(remotePath, output); + std::vector<std::string> components; + cmSystemTools::SplitPath(local, components); + std::string result = this->ConvertToRelativePath(components, remotePath); + return this->ConvertToOutputFormat(result, output); } static bool cmOutputConverterNotAbove(const char* a, const char* b) @@ -328,19 +320,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 +351,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 +557,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; - - /* 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; - } - } + std::ostringstream out; - /* 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 +574,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 +590,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 +610,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 +624,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 +641,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 +649,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 +681,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 +696,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..23f2e62 100644 --- a/Source/cmOutputConverter.h +++ b/Source/cmOutputConverter.h @@ -58,8 +58,7 @@ public: 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; + OutputFormat output = UNCHANGED) const; std::string ConvertDirectorySeparatorsForShell( const std::string& source) const; @@ -70,13 +69,11 @@ public: ///! 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 +123,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, @@ -171,10 +159,6 @@ public: 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 +166,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..ef636e7 100644 --- a/Source/cmOutputRequiredFilesCommand.cxx +++ b/Source/cmOutputRequiredFilesCommand.cxx @@ -28,7 +28,7 @@ public: */ cmDependInformation() : DependDone(false) - , SourceFile(0) + , SourceFile(CM_NULLPTR) { } @@ -154,7 +154,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 +203,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; } @@ -329,7 +329,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); diff --git a/Source/cmOutputRequiredFilesCommand.h b/Source/cmOutputRequiredFilesCommand.h index 7a6f5a6..8838d09 100644 --- a/Source/cmOutputRequiredFilesCommand.h +++ b/Source/cmOutputRequiredFilesCommand.h @@ -20,10 +20,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.h b/Source/cmParseArgumentsCommand.h index 46d9daa..fcd9992 100644 --- a/Source/cmParseArgumentsCommand.h +++ b/Source/cmParseArgumentsCommand.h @@ -24,24 +24,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/cmPolicies.cxx b/Source/cmPolicies.cxx index 85f0fa3..124fb6a 100644 --- a/Source/cmPolicies.cxx +++ b/Source/cmPolicies.cxx @@ -57,9 +57,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 +71,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, @@ -102,9 +102,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( diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h index ff49e31..0c8ff60 100644 --- a/Source/cmPolicies.h +++ b/Source/cmPolicies.h @@ -203,7 +203,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..34b8df2 100644 --- a/Source/cmProcessTools.cxx +++ b/Source/cmProcessTools.cxx @@ -17,27 +17,27 @@ 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..61bfc64 100644 --- a/Source/cmProcessTools.h +++ b/Source/cmProcessTools.h @@ -62,7 +62,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 +73,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.h b/Source/cmProjectCommand.h index a4e6367..3318df1 100644 --- a/Source/cmProjectCommand.h +++ b/Source/cmProjectCommand.h @@ -28,19 +28,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..133258f 100644 --- a/Source/cmProperty.cxx +++ b/Source/cmProperty.cxx @@ -33,5 +33,5 @@ const char* cmProperty::GetValue() const if (this->ValueHasBeenSet) { return this->Value.c_str(); } - return 0; + return CM_NULLPTR; } diff --git a/Source/cmPropertyDefinitionMap.cxx b/Source/cmPropertyDefinitionMap.cxx index ebc2caa..0ba35e7 100644 --- a/Source/cmPropertyDefinitionMap.cxx +++ b/Source/cmPropertyDefinitionMap.cxx @@ -31,12 +31,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/cmPropertyMap.cxx b/Source/cmPropertyMap.cxx index 74e04da..1e1ff91 100644 --- a/Source/cmPropertyMap.cxx +++ b/Source/cmPropertyMap.cxx @@ -15,6 +15,7 @@ #include "cmSystemTools.h" #include "cmake.h" +#include <algorithm> #include <assert.h> cmProperty* cmPropertyMap::GetOrCreateProperty(const std::string& name) @@ -29,6 +30,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 +70,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..6dc7bfb 100644 --- a/Source/cmPropertyMap.h +++ b/Source/cmPropertyMap.h @@ -19,6 +19,8 @@ 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..ef8255a 100644 --- a/Source/cmQTWrapCPPCommand.cxx +++ b/Source/cmQTWrapCPPCommand.cxx @@ -80,7 +80,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..78d5510 100644 --- a/Source/cmQTWrapCPPCommand.h +++ b/Source/cmQTWrapCPPCommand.h @@ -30,19 +30,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..a948dd6 100644 --- a/Source/cmQTWrapUICommand.cxx +++ b/Source/cmQTWrapUICommand.cxx @@ -111,8 +111,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..a34a7bf 100644 --- a/Source/cmQTWrapUICommand.h +++ b/Source/cmQTWrapUICommand.h @@ -28,19 +28,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..d5634e8b 100644 --- a/Source/cmQtAutoGeneratorInitializer.cxx +++ b/Source/cmQtAutoGeneratorInitializer.cxx @@ -119,7 +119,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( @@ -406,7 +406,7 @@ 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(); @@ -426,8 +426,9 @@ 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; @@ -447,10 +448,11 @@ 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) { - std::stringstream err; + std::ostringstream err; err << "AUTOGEN: error: Rcc list process for " << sf->GetFullPath() << " failed:\n" << rccStdOut << "\n" @@ -480,7 +482,7 @@ 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(); diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx index 3677a28..174760f 100644 --- a/Source/cmQtAutoGenerators.cxx +++ b/Source/cmQtAutoGenerators.cxx @@ -34,8 +34,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; } @@ -88,7 +88,7 @@ static std::string extractSubDir(const std::string& absPath, } cmQtAutoGenerators::cmQtAutoGenerators() - : Verbose(cmsys::SystemTools::GetEnv("VERBOSE") != 0) + : Verbose(cmsys::SystemTools::HasEnv("VERBOSE")) , ColorOutput(true) , RunMocFailed(false) , RunUicFailed(false) @@ -155,7 +155,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); @@ -431,7 +431,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(); @@ -476,7 +476,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 +498,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 +526,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 +559,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 +587,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 +619,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 +635,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 +655,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 +669,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 +695,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 +716,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 +741,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 +764,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 +790,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 +806,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 +832,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 +853,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 +878,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); @@ -942,7 +941,7 @@ 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()); } @@ -971,7 +970,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 +1011,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"; @@ -1034,7 +1033,7 @@ bool cmQtAutoGenerators::GenerateMocFiles( 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()); @@ -1105,7 +1104,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 +1145,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 @@ -1222,7 +1221,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; @@ -1272,7 +1271,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 @@ -1339,7 +1338,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 +1386,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 +1408,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/cmRemoveCommand.h b/Source/cmRemoveCommand.h index c226a54..1deff36 100644 --- a/Source/cmRemoveCommand.h +++ b/Source/cmRemoveCommand.h @@ -25,24 +25,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.h b/Source/cmRemoveDefinitionsCommand.h index b440307..7fb2e5f 100644 --- a/Source/cmRemoveDefinitionsCommand.h +++ b/Source/cmRemoveDefinitionsCommand.h @@ -27,19 +27,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.h b/Source/cmReturnCommand.h index 44cd4c8..ddf3613 100644 --- a/Source/cmReturnCommand.h +++ b/Source/cmReturnCommand.h @@ -25,24 +25,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..b8aae5d 100644 --- a/Source/cmScriptGenerator.cxx +++ b/Source/cmScriptGenerator.cxx @@ -19,7 +19,7 @@ cmScriptGenerator::cmScriptGenerator( : RuntimeConfigVariable(config_var) , Configurations(configurations) , ConfigurationName("") - , ConfigurationTypes(0) + , ConfigurationTypes(CM_NULLPTR) , ActionsPerConfig(false) { } @@ -36,7 +36,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, diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx index a0cce12..ca3a57f 100644 --- a/Source/cmSearchPath.cxx +++ b/Source/cmSearchPath.cxx @@ -45,7 +45,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 +80,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 +107,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)) { @@ -172,7 +172,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 +213,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..65f703f 100644 --- a/Source/cmSearchPath.h +++ b/Source/cmSearchPath.h @@ -28,7 +28,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 +47,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.h b/Source/cmSeparateArgumentsCommand.h index 47246c9..3c9e7d7 100644 --- a/Source/cmSeparateArgumentsCommand.h +++ b/Source/cmSeparateArgumentsCommand.h @@ -25,24 +25,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/cmSetCommand.cxx b/Source/cmSetCommand.cxx index 5f4cfee..8fb6aa0 100644 --- a/Source/cmSetCommand.cxx +++ b/Source/cmSetCommand.cxx @@ -31,13 +31,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 +46,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; @@ -59,7 +60,7 @@ 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); + this->Makefile->RaiseScope(variable, CM_NULLPTR); return true; } @@ -73,7 +74,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..b51eed0 100644 --- a/Source/cmSetCommand.h +++ b/Source/cmSetCommand.h @@ -25,24 +25,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.h b/Source/cmSetDirectoryPropertiesCommand.h index a393eee..ef476ec 100644 --- a/Source/cmSetDirectoryPropertiesCommand.h +++ b/Source/cmSetDirectoryPropertiesCommand.h @@ -17,24 +17,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..8fe8ade 100644 --- a/Source/cmSetPropertyCommand.cxx +++ b/Source/cmSetPropertyCommand.cxx @@ -139,7 +139,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 +189,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 +230,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 +269,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 +317,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..e78b04c 100644 --- a/Source/cmSetPropertyCommand.h +++ b/Source/cmSetPropertyCommand.h @@ -19,24 +19,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.h b/Source/cmSetSourceFilesPropertiesCommand.h index 20e6b93..f6b4de0 100644 --- a/Source/cmSetSourceFilesPropertiesCommand.h +++ b/Source/cmSetSourceFilesPropertiesCommand.h @@ -17,19 +17,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.h b/Source/cmSetTargetPropertiesCommand.h index 122c15e..1ed8d90 100644 --- a/Source/cmSetTargetPropertiesCommand.h +++ b/Source/cmSetTargetPropertiesCommand.h @@ -17,19 +17,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.h b/Source/cmSetTestsPropertiesCommand.h index e469b2a..712ab36 100644 --- a/Source/cmSetTestsPropertiesCommand.h +++ b/Source/cmSetTestsPropertiesCommand.h @@ -17,19 +17,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..5c14991 100644 --- a/Source/cmSiteNameCommand.cxx +++ b/Source/cmSiteNameCommand.cxx @@ -55,7 +55,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..7a9ca9d 100644 --- a/Source/cmSiteNameCommand.h +++ b/Source/cmSiteNameCommand.h @@ -25,24 +25,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..04727b2 100644 --- a/Source/cmSourceFile.cxx +++ b/Source/cmSourceFile.cxx @@ -19,7 +19,7 @@ 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 +27,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 +135,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,7 +294,7 @@ const char* cmSourceFile::GetProperty(const std::string& prop) const // Check for computed properties. if (prop == "LOCATION") { if (this->FullPath.empty()) { - return 0; + return CM_NULLPTR; } else { return this->FullPath.c_str(); } diff --git a/Source/cmSourceFile.h b/Source/cmSourceFile.h index b1623bd..a3808f7 100644 --- a/Source/cmSourceFile.h +++ b/Source/cmSourceFile.h @@ -62,7 +62,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..099a6f0 100644 --- a/Source/cmSourceFileLocation.cxx +++ b/Source/cmSourceFileLocation.cxx @@ -19,7 +19,7 @@ #include "assert.h" cmSourceFileLocation::cmSourceFileLocation() - : Makefile(0) + : Makefile(CM_NULLPTR) , AmbiguousDirectory(true) , AmbiguousExtension(true) { @@ -177,10 +177,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/cmSourceGroup.cxx b/Source/cmSourceGroup.cxx index 394b33a..d9529a2 100644 --- a/Source/cmSourceGroup.cxx +++ b/Source/cmSourceGroup.cxx @@ -86,11 +86,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 +123,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 +143,7 @@ cmSourceGroup* cmSourceGroup::MatchChildrenFiles(const char* name) return result; } } - return 0; + return CM_NULLPTR; } cmSourceGroup* cmSourceGroup::MatchChildrenRegex(const char* name) @@ -168,7 +164,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..1f5232e 100644 --- a/Source/cmSourceGroup.h +++ b/Source/cmSourceGroup.h @@ -34,7 +34,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..6db14c0 100644 --- a/Source/cmSourceGroupCommand.cxx +++ b/Source/cmSourceGroupCommand.cxx @@ -28,7 +28,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..81dfad6 100644 --- a/Source/cmSourceGroupCommand.h +++ b/Source/cmSourceGroupCommand.h @@ -26,19 +26,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..606978e 100644 --- a/Source/cmStandardIncludes.h +++ b/Source/cmStandardIncludes.h @@ -18,18 +18,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 +55,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/cmState.cxx b/Source/cmState.cxx index 04f07ce..0470508 100644 --- a/Source/cmState.cxx +++ b/Source/cmState.cxx @@ -135,12 +135,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 +204,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 +246,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 +296,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() @@ -366,7 +374,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 +491,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); @@ -1189,7 +1197,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 +1286,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"); } diff --git a/Source/cmState.h b/Source/cmState.h index 18c45b8..e5f9917 100644 --- a/Source/cmState.h +++ b/Source/cmState.h @@ -55,7 +55,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; @@ -247,6 +247,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, diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index a348aef..3c913ee 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -89,7 +89,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()); @@ -485,7 +485,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 +501,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") diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h index 23d482c..23dc9db 100644 --- a/Source/cmStringCommand.h +++ b/Source/cmStringCommand.h @@ -29,24 +29,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.h b/Source/cmSubdirCommand.h index 9da91c4..08eb9a0 100644 --- a/Source/cmSubdirCommand.h +++ b/Source/cmSubdirCommand.h @@ -27,19 +27,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.h b/Source/cmSubdirDependsCommand.h index a15ee3e..41b27c8 100644 --- a/Source/cmSubdirDependsCommand.h +++ b/Source/cmSubdirDependsCommand.h @@ -17,10 +17,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..5745a01 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -228,14 +228,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); } @@ -581,7 +583,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 +595,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 +614,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 +643,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 +705,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 +1433,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 +1444,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 { @@ -1873,7 +1876,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 +1885,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 +1933,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 +1988,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 +2069,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 +2118,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 +2200,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"; @@ -2373,10 +2380,10 @@ bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op, if (lhs < rhs) { // lhs < rhs, so true if operation is LESS - return op == cmSystemTools::OP_LESS; + return (op & cmSystemTools::OP_LESS) != 0; } else 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 +2395,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 +2412,13 @@ 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()); +} + bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg, bool* removed) { @@ -2424,7 +2438,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..d0a28e1 100644 --- a/Source/cmSystemTools.h +++ b/Source/cmSystemTools.h @@ -64,33 +64,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 +222,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 +234,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 +284,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 +299,8 @@ 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); /** * Determine the file type based on the extension @@ -435,12 +443,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..8476538 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -27,7 +27,11 @@ #include <map> #include <set> #include <stdlib.h> // required for atof -#if defined(CMAKE_BUILD_WITH_CMAKE) + +#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 @@ -53,7 +57,7 @@ public: cmTarget::cmTarget() { - this->Makefile = 0; + this->Makefile = CM_NULLPTR; this->HaveInstallRule = false; this->DLLPlatform = false; this->IsAndroid = false; @@ -93,63 +97,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 +171,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 +183,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 +195,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 +239,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 +275,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 +293,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 +410,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 +481,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 +587,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"); @@ -1059,7 +1065,7 @@ bool cmTarget::HandleLocationPropertyPolicy(cmMakefile* context) const 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 +1107,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 +1120,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 +1149,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; @@ -1165,7 +1171,7 @@ const char* cmTarget::GetProperty(const std::string& prop, 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 +1218,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; @@ -1224,7 +1230,7 @@ const char* cmTarget::GetProperty(const std::string& prop, return cmState::GetTargetTypeName(this->GetType()); } else if (prop == propINCLUDE_DIRECTORIES) { if (this->Internal->IncludeDirectoriesEntries.empty()) { - return 0; + return CM_NULLPTR; } static std::string output; @@ -1232,7 +1238,7 @@ const char* cmTarget::GetProperty(const std::string& prop, return output.c_str(); } else if (prop == propCOMPILE_FEATURES) { if (this->Internal->CompileFeaturesEntries.empty()) { - return 0; + return CM_NULLPTR; } static std::string output; @@ -1240,7 +1246,7 @@ const char* cmTarget::GetProperty(const std::string& prop, return output.c_str(); } else if (prop == propCOMPILE_OPTIONS) { if (this->Internal->CompileOptionsEntries.empty()) { - return 0; + return CM_NULLPTR; } static std::string output; @@ -1248,7 +1254,7 @@ const char* cmTarget::GetProperty(const std::string& prop, return output.c_str(); } else if (prop == propCOMPILE_DEFINITIONS) { if (this->Internal->CompileDefinitionsEntries.empty()) { - return 0; + return CM_NULLPTR; } static std::string output; @@ -1264,7 +1270,7 @@ const char* cmTarget::GetProperty(const std::string& prop, return this->GetMakefile()->GetCurrentSourceDirectory(); } else if (prop == propSOURCES) { if (this->Internal->SourceEntries.empty()) { - return 0; + return CM_NULLPTR; } std::ostringstream ss; @@ -1429,8 +1435,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..209a729 100644 --- a/Source/cmTarget.h +++ b/Source/cmTarget.h @@ -19,9 +19,9 @@ #include "cmPolicies.h" #include "cmPropertyMap.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_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> @@ -156,7 +156,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 +195,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 +331,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.h b/Source/cmTargetCompileDefinitionsCommand.h index 29d86c5..1689a75 100644 --- a/Source/cmTargetCompileDefinitionsCommand.h +++ b/Source/cmTargetCompileDefinitionsCommand.h @@ -21,30 +21,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.h b/Source/cmTargetCompileFeaturesCommand.h index 3d883e9..4fae84a 100644 --- a/Source/cmTargetCompileFeaturesCommand.h +++ b/Source/cmTargetCompileFeaturesCommand.h @@ -16,23 +16,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.h b/Source/cmTargetCompileOptionsCommand.h index 231448b..7239629 100644 --- a/Source/cmTargetCompileOptionsCommand.h +++ b/Source/cmTargetCompileOptionsCommand.h @@ -21,30 +21,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/cmTargetIncludeDirectoriesCommand.h b/Source/cmTargetIncludeDirectoriesCommand.h index 4c907bd..ba5d980 100644 --- a/Source/cmTargetIncludeDirectoriesCommand.h +++ b/Source/cmTargetIncludeDirectoriesCommand.h @@ -21,34 +21,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..1c4a9ce 100644 --- a/Source/cmTargetLinkLibrariesCommand.cxx +++ b/Source/cmTargetLinkLibrariesCommand.cxx @@ -91,7 +91,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 +307,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: diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h index 016993d..4f58639 100644 --- a/Source/cmTargetLinkLibrariesCommand.h +++ b/Source/cmTargetLinkLibrariesCommand.h @@ -27,19 +27,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..71ac9e7 --- /dev/null +++ b/Source/cmTargetLinkLibraryType.h @@ -0,0 +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. +============================================================================*/ +#ifndef cmTargetLinkLibraryType_h +#define cmTargetLinkLibraryType_h + +enum cmTargetLinkLibraryType +{ + GENERAL_LibraryType, + DEBUG_LibraryType, + OPTIMIZED_LibraryType +}; + +#endif diff --git a/Source/cmTargetSourcesCommand.h b/Source/cmTargetSourcesCommand.h index 304e176..9073204 100644 --- a/Source/cmTargetSourcesCommand.h +++ b/Source/cmTargetSourcesCommand.h @@ -21,31 +21,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/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx index e599825..462edf9 100644 --- a/Source/cmTestGenerator.cxx +++ b/Source/cmTestGenerator.cxx @@ -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..66d590e 100644 --- a/Source/cmTestGenerator.h +++ b/Source/cmTestGenerator.h @@ -27,18 +27,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..61b74db 100644 --- a/Source/cmTimestamp.cxx +++ b/Source/cmTimestamp.cxx @@ -22,7 +22,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 +56,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 +93,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 @@ -152,7 +151,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/cmTryCompileCommand.h b/Source/cmTryCompileCommand.h index e50d54c..abfe335 100644 --- a/Source/cmTryCompileCommand.h +++ b/Source/cmTryCompileCommand.h @@ -25,19 +25,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..7b19048 100644 --- a/Source/cmTryRunCommand.cxx +++ b/Source/cmTryRunCommand.cxx @@ -124,8 +124,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 +187,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 +231,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 +253,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 +302,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 +333,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 +346,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 +354,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..b8eb1de 100644 --- a/Source/cmTryRunCommand.h +++ b/Source/cmTryRunCommand.h @@ -25,19 +25,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..147eba8 --- /dev/null +++ b/Source/cmTypeMacro.h @@ -0,0 +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. +============================================================================*/ +#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..05ba65a 100644 --- a/Source/cmUnsetCommand.cxx +++ b/Source/cmUnsetCommand.cxx @@ -47,7 +47,7 @@ bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args, } // unset(VAR PARENT_SCOPE) else if ((args.size() == 2) && (args[1] == "PARENT_SCOPE")) { - this->Makefile->RaiseScope(variable, 0); + this->Makefile->RaiseScope(variable, CM_NULLPTR); return true; } // ERROR: second argument isn't CACHE or PARENT_SCOPE diff --git a/Source/cmUnsetCommand.h b/Source/cmUnsetCommand.h index faa8f9b..6429c10 100644 --- a/Source/cmUnsetCommand.h +++ b/Source/cmUnsetCommand.h @@ -25,24 +25,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.h b/Source/cmUseMangledMesaCommand.h index 5a97a61..5a44035 100644 --- a/Source/cmUseMangledMesaCommand.h +++ b/Source/cmUseMangledMesaCommand.h @@ -18,11 +18,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..c50cbfb 100644 --- a/Source/cmUtilitySourceCommand.cxx +++ b/Source/cmUtilitySourceCommand.cxx @@ -38,7 +38,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 +50,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..2eb961f 100644 --- a/Source/cmUtilitySourceCommand.h +++ b/Source/cmUtilitySourceCommand.h @@ -18,10 +18,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..b7a79cc --- /dev/null +++ b/Source/cmUtils.hxx @@ -0,0 +1,26 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + 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 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/cmVariableRequiresCommand.h b/Source/cmVariableRequiresCommand.h index b83f615..c4b0817 100644 --- a/Source/cmVariableRequiresCommand.h +++ b/Source/cmVariableRequiresCommand.h @@ -18,10 +18,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..56e2770 100644 --- a/Source/cmVariableWatch.cxx +++ b/Source/cmVariableWatch.cxx @@ -13,7 +13,7 @@ #include "cmAlgorithms.h" -#include <cmsys/auto_ptr.hxx> +#include <cm_auto_ptr.hxx> static const char* const cmVariableWatchAccessStrings[] = { "READ_ACCESS", "UNKNOWN_READ_ACCESS", "UNKNOWN_DEFINED_ACCESS", @@ -48,7 +48,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..5ddb907 100644 --- a/Source/cmVariableWatch.h +++ b/Source/cmVariableWatch.h @@ -36,9 +36,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 +72,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.h b/Source/cmVariableWatchCommand.h index aad53cb..1d402af 100644 --- a/Source/cmVariableWatchCommand.h +++ b/Source/cmVariableWatchCommand.h @@ -24,34 +24,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/cmVersionConfig.h.in b/Source/cmVersionConfig.h.in index 16aeabe..92abfbe 100644 --- a/Source/cmVersionConfig.h.in +++ b/Source/cmVersionConfig.h.in @@ -12,4 +12,6 @@ #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/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index fb05976..c33a291 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -42,7 +42,9 @@ #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"; cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetClFlagTable() const { @@ -531,7 +533,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)"; @@ -1187,6 +1191,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) tool = "PRIResource"; } else if (ext == "xml") { tool = "XML"; + } else if (ext == "natvis") { + tool = "Natvis"; } if (this->NsightTegra) { @@ -1203,6 +1209,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() || @@ -1224,8 +1235,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); @@ -1679,7 +1689,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; @@ -1843,7 +1853,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; @@ -1900,7 +1910,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; @@ -2053,7 +2063,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); @@ -2066,7 +2076,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); @@ -2085,7 +2095,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); @@ -2145,7 +2155,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; @@ -2339,7 +2349,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")) { @@ -2354,10 +2365,11 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( cmGlobalVisualStudio10Generator* gg = static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); const char* toolset = gg->GetPlatformToolset(); - if (toolset && (cmHasLiteralPrefix(toolset, "v90") || - cmHasLiteralPrefix(toolset, "v100") || - cmHasLiteralPrefix(toolset, "v110") || - cmHasLiteralPrefix(toolset, "v120"))) { + if (toolset && + (toolset == kWINDOWS_7_1_SDK || cmHasLiteralPrefix(toolset, "v90") || + cmHasLiteralPrefix(toolset, "v100") || + cmHasLiteralPrefix(toolset, "v110") || + cmHasLiteralPrefix(toolset, "v120"))) { if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) { // Convert value from enumeration back to boolean for older toolsets. @@ -2503,7 +2515,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")) { @@ -2644,6 +2657,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")) { @@ -2656,7 +2683,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); @@ -2668,6 +2698,9 @@ void cmVisualStudio10TargetGenerator::WriteSDKReferences() if (iotExtensionsVersion) { this->WriteSingleSDKReference("WindowsIoT", iotExtensionsVersion); } + } + + if (hasWrittenItemGroup) { this->WriteString("</ItemGroup>\n", 1); } } diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx index bec2861..93a6271 100644 --- a/Source/cmWhileCommand.cxx +++ b/Source/cmWhileCommand.cxx @@ -37,8 +37,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; } diff --git a/Source/cmWhileCommand.h b/Source/cmWhileCommand.h index 0f35be8..bd354c7 100644 --- a/Source/cmWhileCommand.h +++ b/Source/cmWhileCommand.h @@ -21,10 +21,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 +41,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 +63,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.h b/Source/cmWriteFileCommand.h index b0eef9c..db24b0e 100644 --- a/Source/cmWriteFileCommand.h +++ b/Source/cmWriteFileCommand.h @@ -24,24 +24,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/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx index 3d31343..fabf097 100644 --- a/Source/cmXCodeObject.cxx +++ b/Source/cmXCodeObject.cxx @@ -83,6 +83,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..ed917af 100644 --- a/Source/cmXCodeObject.h +++ b/Source/cmXCodeObject.h @@ -59,21 +59,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 +103,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 +137,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 +145,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/cmXMLWriter.cxx b/Source/cmXMLWriter.cxx index 98c2680..e2dce93d 100644 --- a/Source/cmXMLWriter.cxx +++ b/Source/cmXMLWriter.cxx @@ -14,7 +14,7 @@ #include "cmXMLSafe.h" #include <cassert> -#include <fstream> +#include <cmsys/FStream.hxx> cmXMLWriter::cmXMLWriter(std::ostream& output, std::size_t level) : Output(output) @@ -107,7 +107,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/kwsys/auto_ptr.hxx.in b/Source/cm_auto_ptr.hxx index ad9654c..2cd35c3 100644 --- a/Source/kwsys/auto_ptr.hxx.in +++ b/Source/cm_auto_ptr.hxx @@ -1,6 +1,6 @@ /*============================================================================ - KWSys - Kitware System Library - Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + CMake - Cross Platform Makefile Generator + Copyright 2000-2016 Kitware, Inc. Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. @@ -9,26 +9,29 @@ implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ -#ifndef @KWSYS_NAMESPACE@_auto_ptr_hxx -#define @KWSYS_NAMESPACE@_auto_ptr_hxx +#ifndef CM_AUTO_PTR_HXX +#define CM_AUTO_PTR_HXX -#include <@KWSYS_NAMESPACE@/Configure.hxx> +#include <cmsys/Configure.hxx> -// The HP compiler and VS6 cannot handle the conversions necessary to use +// FIXME: Use std::auto_ptr on compilers that do not warn about it. +#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) || (defined(_MSC_VER) && _MSC_VER <= 1200) -# define @KWSYS_NAMESPACE@_AUTO_PTR_REF 0 -# define @KWSYS_NAMESPACE@_AUTO_PTR_CONST const -# define @KWSYS_NAMESPACE@_AUTO_PTR_CAST(a) cast(a) +#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 @KWSYS_NAMESPACE@_AUTO_PTR_REF 1 -# define @KWSYS_NAMESPACE@_AUTO_PTR_CONST -# define @KWSYS_NAMESPACE@_AUTO_PTR_CAST(a) a +#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 @@ -36,24 +39,24 @@ // 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 +#if __has_warning("-Wdeprecated") +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated" +#endif #endif -namespace @KWSYS_NAMESPACE@ -{ +namespace cm { -template <class X> class auto_ptr; +template <class X> +class auto_ptr; -#if @KWSYS_NAMESPACE@_AUTO_PTR_REF -namespace detail -{ +#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 +template <class Y> +struct auto_ptr_ref { Y* p_; @@ -62,7 +65,10 @@ template <class Y> struct auto_ptr_ref // 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) {} + auto_ptr_ref(Y* p, int) + : p_(p) + { + } }; } #endif @@ -71,10 +77,12 @@ template <class Y> struct auto_ptr_ref template <class X> class auto_ptr { -#if !@KWSYS_NAMESPACE@_AUTO_PTR_REF +#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); } + { + return const_cast<auto_ptr<Y>&>(a); + } #endif /** The pointer to the object held. */ @@ -87,19 +95,19 @@ public: /** 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@_AUTO_PTR_CONST& a) throw(): - x_(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release()) - { - } + 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> @KWSYS_NAMESPACE@_AUTO_PTR_CONST& a) throw() - { - this->reset(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release()); + 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 @@ -107,113 +115,107 @@ public: * * auto_ptr<X> ptr(new X()); */ - explicit auto_ptr(X* p=0) throw(): x_(p) - { - } + 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@_AUTO_PTR_CONST& a) throw(): - x_(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release()) - { - } + 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 @KWSYS_NAMESPACE@_AUTO_PTR_CONST& a) throw() - { - this->reset(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release()); + 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_; - } + X& operator*() const throw() { return *this->x_; } /** Return a pointer to the object held. */ - X* operator->() const throw() - { - return this->x_; - } + X* operator->() const throw() { return this->x_; } /** Return a pointer to the object held. */ - X* get() const throw() - { - return this->x_; - } + 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) - { + 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() - { + template <class Y> + operator auto_ptr<Y>() throw() + { return auto_ptr<Y>(this->release()); - } + } -#if @KWSYS_NAMESPACE@_AUTO_PTR_REF +#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_) - { - } + 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() - { + template <class Y> + operator detail::auto_ptr_ref<Y>() throw() + { return detail::auto_ptr_ref<Y>(this->release(), 1); - } + } #endif }; -} // namespace @KWSYS_NAMESPACE@ +} // namespace cm // Undo warning suppression. #if defined(__clang__) && defined(__has_warning) -# if __has_warning("-Wdeprecated") -# pragma clang diagnostic pop -# endif +#if __has_warning("-Wdeprecated") +#pragma clang diagnostic pop +#endif #endif #endif diff --git a/Source/cmake.cxx b/Source/cmake.cxx index 89ea955..b11f4f6 100644 --- a/Source/cmake.cxx +++ b/Source/cmake.cxx @@ -22,6 +22,7 @@ #include "cmSourceFile.h" #include "cmState.h" #include "cmTest.h" +#include "cmUtils.hxx" #if defined(CMAKE_BUILD_WITH_CMAKE) #include "cmGraphVizWriter.h" @@ -145,10 +146,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 @@ -192,7 +192,7 @@ cmake::~cmake() delete this->State; if (this->GlobalGenerator) { delete this->GlobalGenerator; - this->GlobalGenerator = 0; + this->GlobalGenerator = CM_NULLPTR; } cmDeleteAll(this->Generators); #ifdef CMAKE_BUILD_WITH_CMAKE @@ -398,7 +398,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 +464,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 +483,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 +494,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, frameworkPath, linkPath, flags, + linkFlags, gtgt, false); linkLibs = frameworkPath + linkPath + linkLibs; printf("%s\n", linkLibs.c_str()); @@ -555,9 +559,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 +591,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,53 +793,21 @@ 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 } @@ -847,34 +822,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( + (*i)->GetName(), *gen); + 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* 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 = 0; + cmGlobalGenerator* generator = CM_NULLPTR; for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(); i != this->Generators.end(); ++i) { generator = (*i)->CreateGlobalGenerator(name, this); @@ -949,16 +975,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 = ""; } } @@ -1423,7 +1443,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="); } @@ -1648,15 +1668,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 +1735,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 +1770,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 +1791,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 +1936,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(); @@ -1968,7 +1999,7 @@ cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const cmInstalledFile const& file = i->second; return &file; } else { - return 0; + return CM_NULLPTR; } } @@ -1989,9 +2020,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 +2125,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 @@ -2176,7 +2205,7 @@ static bool cmakeCheckStampList(const char* stampList) return true; } -cmake::MessageType cmake::ConvertMessageType(cmake::MessageType t) +cmake::MessageType cmake::ConvertMessageType(cmake::MessageType t) const { bool warningsAsErrors; @@ -2200,7 +2229,7 @@ cmake::MessageType cmake::ConvertMessageType(cmake::MessageType t) return t; } -bool cmake::IsMessageTypeVisible(cmake::MessageType t) +bool cmake::IsMessageTypeVisible(cmake::MessageType t) const { bool isVisible = true; @@ -2225,7 +2254,7 @@ bool cmake::IsMessageTypeVisible(cmake::MessageType t) return isVisible; } -bool cmake::PrintMessagePreamble(cmake::MessageType t, std::ostream& msg) +static bool printMessagePreamble(cmake::MessageType t, std::ostream& msg) { // Construct the message header. if (t == cmake::FATAL_ERROR) { @@ -2296,23 +2325,28 @@ void displayMessage(cmake::MessageType t, std::ostringstream& msg) } 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; - } + bool force = false; + // 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 cmake::DisplayMessage(cmake::MessageType t, std::string const& text, + cmListFileBacktrace const& backtrace) const +{ std::ostringstream msg; - if (!this->PrintMessagePreamble(t, msg)) { + if (!printMessagePreamble(t, msg)) { return; } @@ -2383,7 +2417,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 +2482,11 @@ 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); - } + const char* cacheEntryValue = + this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS"); + return cmSystemTools::IsOn(cacheEntryValue); } void cmake::SetSuppressDevWarnings(bool b) @@ -2482,20 +2508,11 @@ 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); - } + const char* cacheEntryValue = + this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED"); + return cacheEntryValue && cmSystemTools::IsOff(cacheEntryValue); } void cmake::SetSuppressDeprecatedWarnings(bool b) @@ -2517,16 +2534,11 @@ 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); - } + const char* cacheEntryValue = + this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS"); + return cacheEntryValue && cmSystemTools::IsOff(cacheEntryValue); } void cmake::SetDevWarningsAsErrors(bool b) @@ -2548,15 +2560,11 @@ 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); - } + const char* cacheEntryValue = + this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED"); + return cmSystemTools::IsOn(cacheEntryValue); } void cmake::SetDeprecatedWarningsAsErrors(bool b) diff --git a/Source/cmake.h b/Source/cmake.h index 266c33d..304a15d 100644 --- a/Source/cmake.h +++ b/Source/cmake.h @@ -27,7 +27,7 @@ class cmLocalGenerator; class cmMakefile; class cmVariableWatch; class cmFileTimeComparison; -class cmExternalMakefileProjectGenerator; +class cmExternalMakefileProjectGeneratorFactory; class cmDocumentationSection; class cmTarget; class cmGeneratedFileStream; @@ -103,7 +103,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; @@ -209,9 +213,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 +254,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 +312,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; } @@ -339,7 +349,7 @@ public: * 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 +360,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 +371,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 +382,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 +391,10 @@ 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; + + void DisplayMessage(cmake::MessageType t, std::string const& text, + cmListFileBacktrace const& backtrace) const; ///! run the --build option int Build(const std::string& dir, const std::string& target, @@ -407,21 +419,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 +462,6 @@ private: void operator=(const cmake&); // Not implemented. ProgressCallbackType ProgressCallback; void* ProgressCallbackClientData; - bool Verbose; bool InTryCompile; WorkingMode CurrentWorkingMode; bool DebugOutput; @@ -484,6 +490,8 @@ private: cmState* State; cmState::Snapshot CurrentSnapshot; + std::vector<std::string> TraceOnlyThisSources; + void UpdateConversionPathTable(); // Print a list of valid generators to stderr. @@ -493,15 +501,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..521a5bf 100644 --- a/Source/cmakemain.cxx +++ b/Source/cmakemain.cxx @@ -29,22 +29,23 @@ #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) diff --git a/Source/cmcldeps.cxx b/Source/cmcldeps.cxx index 8b0cede..44f71f1 100644 --- a/Source/cmcldeps.cxx +++ b/Source/cmcldeps.cxx @@ -213,7 +213,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..9d0337a 100644 --- a/Source/cmcmd.cxx +++ b/Source/cmcmd.cxx @@ -16,6 +16,7 @@ #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmQtAutoGenerators.h" +#include "cmUtils.hxx" #include "cmVersion.h" #if defined(CMAKE_BUILD_WITH_CMAKE) @@ -27,8 +28,7 @@ #include <cmsys/Process.h> #include <cmsys/Terminal.h> -#if defined(CMAKE_HAVE_VS_GENERATORS) -#include "cmCallVisualStudioMacro.h" +#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) && !defined(__CYGWIN__) #include "cmVisualStudioWCEPlatformParser.h" #endif @@ -271,6 +271,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 +282,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 +291,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 +299,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 +315,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 +344,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; } @@ -402,7 +433,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; } @@ -510,7 +542,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 +593,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 +672,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 +737,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 @@ -868,9 +872,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); @@ -1027,11 +1031,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 +1123,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 +1133,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 +1167,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 +1226,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 +1250,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 +1259,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/ctest.cxx b/Source/ctest.cxx index 4edd62e..38ff64f 100644 --- a/Source/ctest.cxx +++ b/Source/ctest.cxx @@ -21,12 +21,13 @@ #include "cmsys/Encoding.hxx" 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 +109,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/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt index 8b15394..87f6048 100644 --- a/Source/kwsys/CMakeLists.txt +++ b/Source/kwsys/CMakeLists.txt @@ -632,6 +632,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,7 +668,6 @@ 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. @@ -903,7 +907,6 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) # C++ tests IF(NOT WATCOM) SET(KWSYS_CXX_TESTS - testAutoPtr testHashSTL ) 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@_STL_HAS_WSTRING @KWSYS_STL_HAS_WSTRING@ +/* Whether <ext/stdio_filebuf.h> is available. */ +#define @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@ /* 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@_NAME_IS_KWSYS # define kwsys @KWSYS_NAMESPACE@ # endif -# define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE@_NAME_IS_KWSYS -# define KWSYS_STL_HAS_WSTRING @KWSYS_NAMESPACE@_STL_HAS_WSTRING +# define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define KWSYS_STL_HAS_WSTRING @KWSYS_NAMESPACE@_STL_HAS_WSTRING +# define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H #endif #endif diff --git a/Source/kwsys/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@_FStream_hxx #define @KWSYS_NAMESPACE@_FStream_hxx +#include <@KWSYS_NAMESPACE@/Configure.hxx> #include <@KWSYS_NAMESPACE@/Encoding.hxx> #include <fstream> +#if defined(_WIN32) +# if !defined(_MSC_VER) && @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H +# include <ext/stdio_filebuf.h> +# endif +#endif namespace @KWSYS_NAMESPACE@ { -#if defined(_MSC_VER) && _MSC_VER >= 1400 +#if defined(_WIN32) && (defined(_MSC_VER) || @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H) # if defined(_NOEXCEPT) # define @KWSYS_NAMESPACE@_FStream_NOEXCEPT _NOEXCEPT # else # define @KWSYS_NAMESPACE@_FStream_NOEXCEPT # endif + +#if defined(_MSC_VER) + template<typename CharType,typename Traits> class basic_filebuf : public std::basic_filebuf<CharType,Traits> { +# 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@_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@_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..eb2bec6 100644 --- a/Source/kwsys/SystemTools.cxx +++ b/Source/kwsys/SystemTools.cxx @@ -388,6 +388,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 +472,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 +490,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 +523,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 +576,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 +612,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 +628,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 +645,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 +736,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 +1292,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 +1347,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 +2166,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); } @@ -4061,16 +4183,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)) @@ -4811,7 +4926,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 +4935,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 +5485,7 @@ static unsigned int SystemToolsManagerCount; SystemToolsTranslationMap *SystemTools::TranslationMap; #ifdef _WIN32 SystemToolsPathCaseMap *SystemTools::PathCaseMap; +SystemToolsEnvMap *SystemTools::EnvMap; #endif #ifdef __CYGWIN__ SystemToolsTranslationMap *SystemTools::Cyg2Win32Map; @@ -5421,6 +5536,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 +5551,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 +5564,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 +5596,7 @@ void SystemTools::ClassFinalize() delete SystemTools::TranslationMap; #ifdef _WIN32 delete SystemTools::PathCaseMap; + delete SystemTools::EnvMap; #endif #ifdef __CYGWIN__ delete SystemTools::Cyg2Win32Map; @@ -5505,8 +5622,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..28ff0b3 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 @@ -843,6 +849,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 +989,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 +998,7 @@ private: static SystemToolsTranslationMap *TranslationMap; #ifdef _WIN32 static SystemToolsPathCaseMap *PathCaseMap; + static SystemToolsEnvMap *EnvMap; #endif #ifdef __CYGWIN__ static SystemToolsTranslationMap *Cyg2Win32Map; 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/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx index 4d97688..9252ea6 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; 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/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..b811c7f 100644 --- a/Tests/CMakeLib/run_compile_commands.cxx +++ b/Tests/CMakeLib/run_compile_commands.cxx @@ -46,10 +46,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 +66,9 @@ private: void ParseString() { this->String = ""; - if (!Expect('"')) + if (!Expect('"')) { return; + } while (!Expect('"')) { Expect('\\'); this->String.append(1, C); @@ -84,8 +87,9 @@ private: void ExpectOrDie(char c, const std::string& message) { - if (!Expect(c)) + if (!Expect(c)) { ErrorExit(std::string("'") + c + "' expected " + message + "."); + } } void NextNonWhitespace() @@ -98,8 +102,9 @@ private: void Next() { this->C = char(Input->get()); - if (this->Input->bad()) + if (this->Input->bad()) { ErrorExit("Unexpected end of file."); + } } void ErrorExit(const std::string& message) diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index f21e430..2d234db 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -954,6 +954,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 +1002,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 +1115,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} @@ -1373,6 +1384,10 @@ ${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() @@ -1381,6 +1396,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindLTTngUST) endif() + if(CMake_TEST_FindOpenCL) + add_subdirectory(FindOpenCL) + endif() + if(CMake_TEST_FindOpenSSL) add_subdirectory(FindOpenSSL) endif() @@ -1393,6 +1412,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() @@ -3092,6 +3115,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/Tests/CMakeOnly/find_library/lib/32/libtest5.a b/Tests/CMakeOnly/find_library/lib/32/libtest5.a new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/CMakeOnly/find_library/lib/32/libtest5.a diff --git a/Tests/CMakeOnly/find_library/lib/A/lib32/libtest3.a b/Tests/CMakeOnly/find_library/lib/A/lib32/libtest3.a new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/CMakeOnly/find_library/lib/A/lib32/libtest3.a diff --git a/Tests/CMakeOnly/find_library/lib32/A/lib/libtest2.a b/Tests/CMakeOnly/find_library/lib32/A/lib/libtest2.a new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/CMakeOnly/find_library/lib32/A/lib/libtest2.a diff --git a/Tests/CMakeOnly/find_library/lib32/A/lib32/libtest4.a b/Tests/CMakeOnly/find_library/lib32/A/lib32/libtest4.a new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/CMakeOnly/find_library/lib32/A/lib32/libtest4.a diff --git a/Tests/CMakeOnly/find_library/lib32/A/libtest4.a b/Tests/CMakeOnly/find_library/lib32/A/libtest4.a new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/CMakeOnly/find_library/lib32/A/libtest4.a diff --git a/Tests/CMakeOnly/find_library/lib32/libtest4.a b/Tests/CMakeOnly/find_library/lib32/libtest4.a new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/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/lib/x86_64-linux-gnu -L/lib/../lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../.. -L/usr/lib/llvm-3.8/bin/../lib -L/lib -L/usr/lib -whole-archive /usr/lib/llvm-3.8/bin/../lib/clang/3.8.0/lib/linux/libclang_rt.msan-x86_64.a -no-whole-archive --dynamic-list=/usr/lib/llvm-3.8/bin/../lib/clang/3.8.0/lib/linux/libclang_rt.msan-x86_64.a.syms /tmp/dummy-27898d.o --no-as-needed -lpthread -lrt -lm -ldl -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/crtend.o /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crtn.o]]) +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..7bea0af 100644 --- a/Tests/CMakeTests/ModuleNoticesTest.cmake.in +++ b/Tests/CMakeTests/ModuleNoticesTest.cmake.in @@ -35,7 +35,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/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/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/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/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/testcase/.*\\.lo$;^C:/hoffman/My Builds/testcase/.*\\.la$;^C:/hoffman/My Builds/testcase/mkinstalldirs$;^C:/hoffman/My Builds/testcase/missing$;^C:/hoffman/My Builds/testcase/ltmain\\.sh$;^C:/hoffman/My Builds/testcase/libtool$;^C:/hoffman/My Builds/testcase/install-sh$;^C:/hoffman/My Builds/testcase/configure$;^C:/hoffman/My Builds/testcase/config\\.sub$;^C:/hoffman/My Builds/testcase/config\\.status$;^C:/hoffman/My Builds/testcase/config\\.log$;^C:/hoffman/My Builds/testcase/config\\.guess$;^C:/hoffman/My Builds/testcase/autom4te\\.cache$;^C:/hoffman/My Builds/testcase/aclocal\\.m4$;^C:/hoffman/My Builds/testcase/depcomp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10_corr$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_scvh$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.rgbtip\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.zahb\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.085\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.mem$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.tex\\.bak$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j16\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j26\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j36\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_JNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Jseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_KNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Kseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check34_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check35_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check36_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check43_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check44_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check45_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check46_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check47_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check48_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/Makefile$;^C:/hoffman/My Builds/testcase/www/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/.*\\.flc$;^C:/hoffman/My Builds/testcase/src/Makefile$;^C:/hoffman/My Builds/testcase/src/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/\\.deps$;^C:/hoffman/My Builds/testcase/src/\\.libs$;^C:/hoffman/My Builds/testcase/src/.*\\.la$;^C:/hoffman/My Builds/testcase/src/.*\\.lo$;^C:/hoffman/My Builds/testcase/src/make\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/statef.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_15$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_rel$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/hot_post_agb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgb_tip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/start_shellflash\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/white_dwarf\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/3order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/5order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/8order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check8_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check5_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effoo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/tc\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/include/Makefile\\.in$;^C:/hoffman/My Builds/testcase/include/Makefile$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/0\\.1\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_eos1a-eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_0\\.1\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_eos1a-eos1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/fort\\.91$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/oldversion_grid$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2005Ap&SS\\.298\\.\\.135S\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2007Ap&SS\\.307\\.\\.263C\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/astro-ph\\.9909168_eprint_submitted_to_High_Press\\.Res\\.16,331\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/statef_grid-newversion$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/old$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/make\\.out.*$;^C:/hoffman/My Builds/testcase/utils/.*\\.flc$;^C:/hoffman/My Builds/testcase/utils/Makefile$;^C:/hoffman/My Builds/testcase/utils/Makefile\\.in$;^C:/hoffman/My Builds/testcase/utils/\\.deps$;^C:/hoffman/My Builds/testcase/utils/\\.libs$;^C:/hoffman/My Builds/testcase/utils/.*\\.la$;^C:/hoffman/My Builds/testcase/utils/.*\\.lo$;^C:/hoffman/My Builds/testcase/utils/free_eos_test$;^C:/hoffman/My Builds/testcase/utils/test_rosenbrock$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check5\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check8\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_checknr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effoo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence_20070613$;^C:/hoffman/My Builds/testcase/www/eospaper/text$;^C:/hoffman/My Builds/testcase/www/eospaper/cassisi_book_fig$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.1\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/2\\.0\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.2\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.3\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.4\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.5\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.6\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/figures$;^C:/hoffman/My Builds/testcase/www/eospaper/old$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_JNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Jseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_KNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Kseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check34\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check35\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check36\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check44\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check45\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check46\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_1_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_2_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_linear_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_nr_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_series_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.1\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.3\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_linear\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_nr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.rgbtip\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.zahb\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.rgbtip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_linear$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_noexchange$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_nr$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/delta\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos1gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos2gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb_adjust/coulomb_adjust\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/rtc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/make\\.out.*$") +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/.*\\.lo$;^C:/hoffman/My Builds/testcase/.*\\.la$;^C:/hoffman/My Builds/testcase/mkinstalldirs$;^C:/hoffman/My Builds/testcase/missing$;^C:/hoffman/My Builds/testcase/ltmain\\.sh$;^C:/hoffman/My Builds/testcase/libtool$;^C:/hoffman/My Builds/testcase/install-sh$;^C:/hoffman/My Builds/testcase/configure$;^C:/hoffman/My Builds/testcase/config\\.sub$;^C:/hoffman/My Builds/testcase/config\\.status$;^C:/hoffman/My Builds/testcase/config\\.log$;^C:/hoffman/My Builds/testcase/config\\.guess$;^C:/hoffman/My Builds/testcase/autom4te\\.cache$;^C:/hoffman/My Builds/testcase/aclocal\\.m4$;^C:/hoffman/My Builds/testcase/depcomp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10_corr$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_scvh$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.rgbtip\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.zahb\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.085\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.mem$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.tex\\.bak$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j16\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j26\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j36\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_JNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Jseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_KNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Kseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check34_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check35_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check36_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check43_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check44_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check45_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check46_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check47_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check48_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/Makefile$;^C:/hoffman/My Builds/testcase/www/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/.*\\.flc$;^C:/hoffman/My Builds/testcase/src/Makefile$;^C:/hoffman/My Builds/testcase/src/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/\\.deps$;^C:/hoffman/My Builds/testcase/src/\\.libs$;^C:/hoffman/My Builds/testcase/src/.*\\.la$;^C:/hoffman/My Builds/testcase/src/.*\\.lo$;^C:/hoffman/My Builds/testcase/src/make\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/statef.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_15$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_rel$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/hot_post_agb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgb_tip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/start_shellflash\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/white_dwarf\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/3order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/5order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/8order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check8_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check5_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effoo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/tc\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/include/Makefile\\.in$;^C:/hoffman/My Builds/testcase/include/Makefile$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/0\\.1\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_eos1a-eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_0\\.1\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_eos1a-eos1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/fort\\.91$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/oldversion_grid$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2005Ap&SS\\.298\\.\\.135S\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2007Ap&SS\\.307\\.\\.263C\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/astro-ph\\.9909168_eprint_submitted_to_High_Press\\.Res\\.16,331\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/statef_grid-newversion$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/old$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/make\\.out.*$;^C:/hoffman/My Builds/testcase/utils/.*\\.flc$;^C:/hoffman/My Builds/testcase/utils/Makefile$;^C:/hoffman/My Builds/testcase/utils/Makefile\\.in$;^C:/hoffman/My Builds/testcase/utils/\\.deps$;^C:/hoffman/My Builds/testcase/utils/\\.libs$;^C:/hoffman/My Builds/testcase/utils/.*\\.la$;^C:/hoffman/My Builds/testcase/utils/.*\\.lo$;^C:/hoffman/My Builds/testcase/utils/free_eos_test$;^C:/hoffman/My Builds/testcase/utils/test_rosenbrock$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check5\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check8\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_checknr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effoo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence_20070613$;^C:/hoffman/My Builds/testcase/www/eospaper/text$;^C:/hoffman/My Builds/testcase/www/eospaper/cassisi_book_fig$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.1\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/2\\.0\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.2\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.3\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.4\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.5\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.6\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/figures$;^C:/hoffman/My Builds/testcase/www/eospaper/old$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_JNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Jseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_KNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Kseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check34\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check35\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check36\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check44\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check45\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check46\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_1_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_2_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_linear_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_nr_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_series_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.1\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.3\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_linear\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_nr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.rgbtip\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.zahb\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.rgbtip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_linear$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_noexchange$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_nr$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/delta\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos1gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos2gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb_adjust/coulomb_adjust\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/rtc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/make\\.out.*$") # # 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/testcase/.*\\.lo$;^C:/hoffman/My Builds/testcase/.*\\.la$;^C:/hoffman/My Builds/testcase/mkinstalldirs$;^C:/hoffman/My Builds/testcase/missing$;^C:/hoffman/My Builds/testcase/ltmain\\.sh$;^C:/hoffman/My Builds/testcase/libtool$;^C:/hoffman/My Builds/testcase/install-sh$;^C:/hoffman/My Builds/testcase/configure$;^C:/hoffman/My Builds/testcase/config\\.sub$;^C:/hoffman/My Builds/testcase/config\\.status$;^C:/hoffman/My Builds/testcase/config\\.log$;^C:/hoffman/My Builds/testcase/config\\.guess$;^C:/hoffman/My Builds/testcase/autom4te\\.cache$;^C:/hoffman/My Builds/testcase/aclocal\\.m4$;^C:/hoffman/My Builds/testcase/depcomp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10_corr$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_scvh$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.rgbtip\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.zahb\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.085\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.mem$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.tex\\.bak$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j16\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j26\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j36\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_JNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Jseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_KNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Kseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check34_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check35_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check36_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check43_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check44_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check45_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check46_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check47_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check48_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/Makefile$;^C:/hoffman/My Builds/testcase/www/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/.*\\.flc$;^C:/hoffman/My Builds/testcase/src/Makefile$;^C:/hoffman/My Builds/testcase/src/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/\\.deps$;^C:/hoffman/My Builds/testcase/src/\\.libs$;^C:/hoffman/My Builds/testcase/src/.*\\.la$;^C:/hoffman/My Builds/testcase/src/.*\\.lo$;^C:/hoffman/My Builds/testcase/src/make\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/statef.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_15$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_rel$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/hot_post_agb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgb_tip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/start_shellflash\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/white_dwarf\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/3order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/5order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/8order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check8_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check5_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effoo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/tc\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/include/Makefile\\.in$;^C:/hoffman/My Builds/testcase/include/Makefile$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/0\\.1\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_eos1a-eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_0\\.1\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_eos1a-eos1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/fort\\.91$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/oldversion_grid$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2005Ap&SS\\.298\\.\\.135S\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2007Ap&SS\\.307\\.\\.263C\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/astro-ph\\.9909168_eprint_submitted_to_High_Press\\.Res\\.16,331\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/statef_grid-newversion$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/old$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/make\\.out.*$;^C:/hoffman/My Builds/testcase/utils/.*\\.flc$;^C:/hoffman/My Builds/testcase/utils/Makefile$;^C:/hoffman/My Builds/testcase/utils/Makefile\\.in$;^C:/hoffman/My Builds/testcase/utils/\\.deps$;^C:/hoffman/My Builds/testcase/utils/\\.libs$;^C:/hoffman/My Builds/testcase/utils/.*\\.la$;^C:/hoffman/My Builds/testcase/utils/.*\\.lo$;^C:/hoffman/My Builds/testcase/utils/free_eos_test$;^C:/hoffman/My Builds/testcase/utils/test_rosenbrock$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check5\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check8\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_checknr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effoo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence_20070613$;^C:/hoffman/My Builds/testcase/www/eospaper/text$;^C:/hoffman/My Builds/testcase/www/eospaper/cassisi_book_fig$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.1\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/2\\.0\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.2\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.3\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.4\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.5\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.6\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/figures$;^C:/hoffman/My Builds/testcase/www/eospaper/old$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_JNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Jseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_KNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Kseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check34\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check35\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check36\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check44\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check45\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check46\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_1_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_2_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_linear_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_nr_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_series_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.1\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.3\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_linear\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_nr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.rgbtip\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.zahb\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.rgbtip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_linear$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_noexchange$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_nr$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/delta\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos1gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos2gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb_adjust/coulomb_adjust\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/rtc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/make\\.out.*$") +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/.*\\.lo$;^C:/hoffman/My Builds/testcase/.*\\.la$;^C:/hoffman/My Builds/testcase/mkinstalldirs$;^C:/hoffman/My Builds/testcase/missing$;^C:/hoffman/My Builds/testcase/ltmain\\.sh$;^C:/hoffman/My Builds/testcase/libtool$;^C:/hoffman/My Builds/testcase/install-sh$;^C:/hoffman/My Builds/testcase/configure$;^C:/hoffman/My Builds/testcase/config\\.sub$;^C:/hoffman/My Builds/testcase/config\\.status$;^C:/hoffman/My Builds/testcase/config\\.log$;^C:/hoffman/My Builds/testcase/config\\.guess$;^C:/hoffman/My Builds/testcase/autom4te\\.cache$;^C:/hoffman/My Builds/testcase/aclocal\\.m4$;^C:/hoffman/My Builds/testcase/depcomp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.075\\.model_cassisi_eos1_10_corr$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model_cassisi_scvh$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.rgbtip\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.zahb\\.modelc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/0\\.085\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.mem$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange\\.tex\\.bak$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j16\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j26\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/j36\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k10\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k12\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k20\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k22\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k30\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/k32\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/1_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/2_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/linear_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/noexchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/nr_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dgamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/series_exchange_dlnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_JNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Jseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_KNR_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_Kseries_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check34_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check35_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check36_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check43_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check44_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check45_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check46_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check47_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check48_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/Makefile$;^C:/hoffman/My Builds/testcase/www/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/.*\\.flc$;^C:/hoffman/My Builds/testcase/src/Makefile$;^C:/hoffman/My Builds/testcase/src/Makefile\\.in$;^C:/hoffman/My Builds/testcase/src/\\.deps$;^C:/hoffman/My Builds/testcase/src/\\.libs$;^C:/hoffman/My Builds/testcase/src/.*\\.la$;^C:/hoffman/My Builds/testcase/src/.*\\.lo$;^C:/hoffman/My Builds/testcase/src/make\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/statef.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.1\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/0\\.3\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_15$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/1\\.0\\.model_rel$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/hot_post_agb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgb_tip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/rgbtip\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/start_shellflash\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/white_dwarf\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_13$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.1\\.0\\.model_23$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/model-loci/zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/15lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23gamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fermi_dirac_approx/23lnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/thermodynamic_consistency/.*\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_fit\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/3order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/5order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/8order_data\\.tex$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check8_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check5_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/effoo_check3_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda15lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23gamma1\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/fda23lnp\\.yplot$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/thermodynamic_consistency/tc\\.results$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_compare_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/opal_solar_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/opal_solar/statef_opal_model_1995\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/include/Makefile\\.in$;^C:/hoffman/My Builds/testcase/include/Makefile$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/0\\.1\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_eos1a-eos1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/1\\.0\\.model_pteh$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_0\\.1\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_eos1a-eos1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/model-loci/statef_model_1\\.0\\.model_pteh\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/fort\\.91$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/thermodynamic_consistency/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/oldversion_grid$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2005Ap&SS\\.298\\.\\.135S\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/2007Ap&SS\\.307\\.\\.263C\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/astro-ph\\.9909168_eprint_submitted_to_High_Press\\.Res\\.16,331\\.pdf$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/convergence\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/statef_grid-newversion$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/purehe_context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/old$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/make\\.out.*$;^C:/hoffman/My Builds/testcase/utils/.*\\.flc$;^C:/hoffman/My Builds/testcase/utils/Makefile$;^C:/hoffman/My Builds/testcase/utils/Makefile\\.in$;^C:/hoffman/My Builds/testcase/utils/\\.deps$;^C:/hoffman/My Builds/testcase/utils/\\.libs$;^C:/hoffman/My Builds/testcase/utils/.*\\.la$;^C:/hoffman/My Builds/testcase/utils/.*\\.lo$;^C:/hoffman/My Builds/testcase/utils/free_eos_test$;^C:/hoffman/My Builds/testcase/utils/test_rosenbrock$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check1\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check5\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_check8\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/eff_checknr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/eff_check/effoo_check3\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence_20070613$;^C:/hoffman/My Builds/testcase/www/eospaper/text$;^C:/hoffman/My Builds/testcase/www/eospaper/cassisi_book_fig$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.1\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/2\\.0\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.2\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.3\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.4\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.5\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/1\\.6\\.0$;^C:/hoffman/My Builds/testcase/www/eospaper/figures$;^C:/hoffman/My Builds/testcase/www/eospaper/old$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.ps.*$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/context\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/nocoulomb_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dgamma1_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/pteh_dlnp_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/make\\.out.*$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_JNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Jseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_KNR\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_Kseries\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check34\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check35\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check36\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check44\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check45\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/exchange_check46\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_1_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_2_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_linear_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_nr_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/statef_compare_series_exchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/series_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/nr_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/linear_exchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/noexchange_dgamma1\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/1_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/exchange_check/2_exchange_dlnp\\.gnuplot$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/convergence/pureh_newversion_grid/.*\\.err$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dgamma1$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/dlnp$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/dhtau/statef_compare\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.1\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_0\\.3\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_linear\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_noexchange\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.model_nr\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.rgbtip\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/statef_model_1\\.0\\.zahb\\.model\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.zahb\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.rgbtip\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_linear$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_noexchange$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model_nr$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.1\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/1\\.0\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/model-loci/0\\.3\\.model$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/contour\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/eos_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/exchange/context/statef_grid\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/delta\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos1gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/eff_fit/rho-T-loci/gong/m0085eos2gong\\.ascii$;^C:/hoffman/My Builds/testcase/www/eospaper/coulomb/coulomb_adjust/coulomb_adjust\\.out$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.ps$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/.*\\.pyc$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/head\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/body\\.tmp$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/prior-dvi\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.aux$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.log$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/solution\\.dvi$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/rtc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/tc_yplot\\.in$;^C:/hoffman/My Builds/testcase/www/eospaper/solution/make\\.out.*$") # # 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/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/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/CMakeLists.txt b/Tests/FindPackageTest/CMakeLists.txt index fadd0fe..d3e68bc 100644 --- a/Tests/FindPackageTest/CMakeLists.txt +++ b/Tests/FindPackageTest/CMakeLists.txt @@ -333,7 +333,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 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..99fcc0a 100644 --- a/Tests/Fortran/CMakeLists.txt +++ b/Tests/Fortran/CMakeLists.txt @@ -188,7 +188,7 @@ if(TEST_MODULE_DEPENDS) 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") + string(APPEND External_BINARY_DIR " Build") endif() add_custom_command( OUTPUT ${testf_BINARY_DIR}/ExternalProject 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/GenerateExportHeader/CMakeLists.txt b/Tests/Module/GenerateExportHeader/CMakeLists.txt index 8b94ca7..56f0f28 100644 --- a/Tests/Module/GenerateExportHeader/CMakeLists.txt +++ b/Tests/Module/GenerateExportHeader/CMakeLists.txt @@ -64,7 +64,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 @@ -103,7 +103,7 @@ 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") + string(APPEND CMAKE_CXX_FLAGS " -Wno-deprecated-declarations") endif() if(MSVC AND COMPILER_HAS_DEPRECATED) diff --git a/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt b/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt index c1be125..a057746 100644 --- a/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt +++ b/Tests/Module/GenerateExportHeader/lib_shared_and_static/CMakeLists.txt @@ -25,9 +25,12 @@ 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 ) set_target_properties(static_variant PROPERTIES COMPILE_FLAGS -DLIBSHARED_AND_STATIC_STATIC_DEFINE) 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 index 2764905..846c207 100644 --- a/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp +++ b/Tests/Module/GenerateExportHeader/lib_shared_and_static/libshared_and_static.cpp @@ -1,6 +1,10 @@ #include "libshared_and_static.h" +#ifndef MY_CUSTOM_CONTENT_ADDED +#error "MY_CUSTOM_CONTENT_ADDED not defined!" +#endif + int LibsharedAndStatic::libshared_and_static() const { 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/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/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..dbd5530 100644 --- a/Tests/RunCMake/CMakeLists.txt +++ b/Tests/RunCMake/CMakeLists.txt @@ -307,6 +307,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>) 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/VerifyResult.cmake b/Tests/RunCMake/CPack/VerifyResult.cmake index 6eab531..074890f 100644 --- a/Tests/RunCMake/CPack/VerifyResult.cmake +++ b/Tests/RunCMake/CPack/VerifyResult.cmake @@ -16,7 +16,7 @@ include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST}-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_) diff --git a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake index f449f1d..077a19d 100644 --- a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake +++ b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake @@ -264,6 +264,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/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/Tests/RunCMake/FindPkgConfig/pc-bar/lib32/pkgconfig/.placeholder b/Tests/RunCMake/FindPkgConfig/pc-bar/lib32/pkgconfig/.placeholder new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/FindPkgConfig/pc-bar/lib32/pkgconfig/.placeholder diff --git a/Tests/RunCMake/FindPkgConfig/pc-foo/lib32/pkgconfig/.placeholder b/Tests/RunCMake/FindPkgConfig/pc-foo/lib32/pkgconfig/.placeholder new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/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/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/LinkWhatYouUse/main.c b/Tests/RunCMake/LinkWhatYouUse/main.c new file mode 100644 index 0000000..8488f4e --- /dev/null +++ b/Tests/RunCMake/LinkWhatYouUse/main.c @@ -0,0 +1,4 @@ +int main(void) +{ + return 0; +} 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/Ninja/RunCMakeTest.cmake b/Tests/RunCMake/Ninja/RunCMakeTest.cmake index c73f852..622c327 100644 --- a/Tests/RunCMake/Ninja/RunCMakeTest.cmake +++ b/Tests/RunCMake/Ninja/RunCMakeTest.cmake @@ -41,10 +41,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/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..0684d57 100644 --- a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake +++ b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake @@ -31,13 +31,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 +48,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 +67,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 +86,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/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_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/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/find_path/Frameworks/Foo.framework/Headers/Some/Dir/Header.h b/Tests/RunCMake/find_path/Frameworks/Foo.framework/Headers/Some/Dir/Header.h new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/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/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/Tests/RunCMake/message/nomessage-internal-warning-stderr.txt b/Tests/RunCMake/message/nomessage-internal-warning-stderr.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/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/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/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/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/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/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/Release/linux32_release.cmake b/Utilities/Release/linux32_release.cmake index 6d096d1..4ef513e 100644 --- a/Utilities/Release/linux32_release.cmake +++ b/Utilities/Release/linux32_release.cmake @@ -17,7 +17,7 @@ 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_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=2.1 CMake_INSTALL_DEPENDENCIES:BOOL=ON QT_QMAKE_EXECUTABLE:FILEPATH=/home/kitware/qt-4.43-install/bin/qmake ") diff --git a/Utilities/Release/linux64_release.cmake b/Utilities/Release/linux64_release.cmake index cfe370b..168eb86 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=11 +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 @@ -17,9 +33,14 @@ 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-x86_64 BUILD_QtDialog:BOOL:=TRUE -CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL: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..e7e5ba4 100644 --- a/Utilities/Release/osx_release.cmake +++ b/Utilities/Release/osx_release.cmake @@ -13,16 +13,16 @@ set(CFLAGS "") set(CXXFLAGS "-stdlib=libc++") set(INITIAL_CACHE " CMAKE_BUILD_TYPE:STRING=Release +CMAKE_C_STANDARD:STRING=11 +CMAKE_CXX_STANDARD:STRING=11 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_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/win32_release.cmake b/Utilities/Release/win32_release.cmake index ba83b26..a27efda 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,7 @@ 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_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3 CMake_INSTALL_DEPENDENCIES:BOOL=ON CMAKE_EXE_LINKER_FLAGS:STRING=-machine:x86 -subsystem:console,5.01 ") diff --git a/Utilities/Release/win64_release.cmake b/Utilities/Release/win64_release.cmake index 8e207b5..e39a610 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,7 @@ 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_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3 CMake_INSTALL_DEPENDENCIES:BOOL=ON CMAKE_EXE_LINKER_FLAGS:STRING=-machine:x64 -subsystem:console,5.02 ") diff --git a/Utilities/Scripts/update-curl.bash b/Utilities/Scripts/update-curl.bash new file mode 100755 index 0000000..0e466cf --- /dev/null +++ b/Utilities/Scripts/update-curl.bash @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +set -e +set -x +shopt -s dotglob + +readonly name="curl" +readonly ownership="Curl Upstream <curl-library@cool.haxx.se>" +readonly subtree="Utilities/cmcurl" +readonly repo="https://github.com/bagder/curl.git" +readonly tag="curl-7_50_1" +readonly shortlog=false +readonly paths=" + CMake/* + CMakeLists.txt + COPYING + include/curl/*.h + include/curl/curlbuild.h.cmake + lib/*.c + lib/*.h + lib/CMakeLists.txt + lib/Makefile.inc + lib/curl_config.h.cmake + lib/libcurl.rc + lib/vauth/*.c + lib/vauth/*.h + lib/vtls/*.c + lib/vtls/*.h +" + +extract_source () { + git_archive + pushd "${extractdir}/${name}-reduced" + rm lib/config-*.h + popd +} + +. "${BASH_SOURCE%/*}/update-third-party.bash" 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@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/Sphinx/CMakeLists.txt b/Utilities/Sphinx/CMakeLists.txt index 257ba62..45f79dd 100644 --- a/Utilities/Sphinx/CMakeLists.txt +++ b/Utilities/Sphinx/CMakeLists.txt @@ -156,18 +156,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/cmcurl/CMake/CurlTests.c b/Utilities/cmcurl/CMake/CurlTests.c index 3c71232..ceff391 100644 --- a/Utilities/cmcurl/CMake/CurlTests.c +++ b/Utilities/cmcurl/CMake/CurlTests.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/CMake/OtherTests.cmake b/Utilities/cmcurl/CMake/OtherTests.cmake index 4f07f22..d599498 100644 --- a/Utilities/cmcurl/CMake/OtherTests.cmake +++ b/Utilities/cmcurl/CMake/OtherTests.cmake @@ -10,8 +10,8 @@ endmacro(add_header_include) set(signature_call_conv) if(HAVE_WINDOWS_H) - add_header_include(HAVE_WINDOWS_H "windows.h") add_header_include(HAVE_WINSOCK2_H "winsock2.h") + add_header_include(HAVE_WINDOWS_H "windows.h") add_header_include(HAVE_WINSOCK_H "winsock.h") set(_source_epilogue "${_source_epilogue}\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif") diff --git a/Utilities/cmcurl/CMakeLists.txt b/Utilities/cmcurl/CMakeLists.txt index 39b70c0..9031181 100644 --- a/Utilities/cmcurl/CMakeLists.txt +++ b/Utilities/cmcurl/CMakeLists.txt @@ -1,6 +1,5 @@ # Set curl options as needed for CMake build set(BUILD_CURL_EXE OFF CACHE INTERNAL "No curl exe") -set(BUILD_CURL_TESTS OFF CACHE INTERNAL "No curl tests") set(BUILD_DASHBOARD_REPORTS OFF CACHE INTERNAL "No curl dashboard reports") set(BUILD_RELEASE_DEBUG_DIRS OFF CACHE INTERNAL "No curl release/debug dirs") set(CMAKE_USE_GSSAPI OFF CACHE INTERNAL "Disable curl gssapi") @@ -70,7 +69,7 @@ endif() # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms -# are also available at http://curl.haxx.se/docs/copyright.html. +# are also available at https://curl.haxx.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is @@ -129,7 +128,7 @@ endif() # SET(PACKAGE_NAME "curl") # SET(PACKAGE_VERSION "-") # SET(PACKAGE_STRING "curl-") -# SET(PACKAGE_BUGREPORT "a suitable curl mailing list => http://curl.haxx.se/mail/") +# SET(PACKAGE_BUGREPORT "a suitable curl mailing list => https://curl.haxx.se/mail/") set(OPERATING_SYSTEM "${CMAKE_SYSTEM_NAME}") set(OS "\"${CMAKE_SYSTEM_NAME}\"") @@ -137,7 +136,6 @@ include_directories(${PROJECT_BINARY_DIR}/include/curl) include_directories( ${CURL_SOURCE_DIR}/include ) option(BUILD_CURL_EXE "Set to ON to build cURL executable." ON) -option(BUILD_CURL_TESTS "Set to ON to build cURL tests." ON) option(CURL_STATICLIB "Set to ON to build libcurl with static linking." OFF) option(ENABLE_ARES "Set to ON to enable c-ares support" OFF) option(ENABLE_THREADED_RESOLVER "Set to ON to enable POSIX threaded DNS lookup" OFF) @@ -173,12 +171,6 @@ if(ENABLE_ARES) set(CURL_LIBS ${CURL_LIBS} ${CARES_LIBRARY}) endif() -option(BUILD_DASHBOARD_REPORTS "Set to ON to activate reporting of cURL builds here http://www.cdash.org/CDashPublic/index.php?project=CURL" OFF) -if(BUILD_DASHBOARD_REPORTS) - #INCLUDE(Dart) - include(CTest) -endif(BUILD_DASHBOARD_REPORTS) - if(MSVC) option(BUILD_RELEASE_DEBUG_DIRS "Set OFF to build each configuration to a separate directory" OFF) mark_as_advanced(BUILD_RELEASE_DEBUG_DIRS) @@ -187,11 +179,6 @@ endif() option(CURL_HIDDEN_SYMBOLS "Set to ON to hide libcurl internal symbols (=hide all symbols that aren't officially external)." ON) mark_as_advanced(CURL_HIDDEN_SYMBOLS) -# IF(WIN32) -# OPTION(CURL_WINDOWS_SSPI "Use windows libraries to allow NTLM authentication without openssl" ON) -# MARK_AS_ADVANCED(CURL_WINDOWS_SSPI) -# ENDIF() - option(HTTP_ONLY "disables all protocols except HTTP (This overrides all CURL_DISABLE_* options)" OFF) mark_as_advanced(HTTP_ONLY) option(CURL_DISABLE_FTP "disables FTP" OFF) @@ -251,7 +238,7 @@ option(DISABLED_THREADSAFE "Set to explicitly specify we don't want to use threa mark_as_advanced(DISABLED_THREADSAFE) option(ENABLE_IPV6 "Define if you want to enable IPv6 support" ON) mark_as_advanced(ENABLE_IPV6) -if(ENABLE_IPV6) +if(ENABLE_IPV6 AND NOT WIN32) include(CheckStructHasMember) check_struct_has_member("struct sockaddr_in6" sin6_addr "netinet/in.h" HAVE_SOCKADDR_IN6_SIN6_ADDR) @@ -402,8 +389,7 @@ if(CMAKE_USE_OPENSSL) endif() elseif(WIN32) # Use Windows SSL/TLS native implementation. - add_definitions(-DUSE_SCHANNEL) - set(USE_WINDOWS_SSPI 1) + set(CURL_WINDOWS_SSPI ON) elseif(APPLE) # Use OS X SSL/TLS native implementation if available on target version. if(CMAKE_OSX_DEPLOYMENT_TARGET) @@ -426,11 +412,10 @@ elseif(APPLE) endif() if(NOT CURL_DISABLE_LDAP) - if(WIN32) option(USE_WIN32_LDAP "Use Windows LDAP implementation" ON) if(USE_WIN32_LDAP) - check_library_exists("wldap32" cldap_open "" HAVE_WLDAP32) + check_library_exists_concat("wldap32" cldap_open HAVE_WLDAP32) if(NOT HAVE_WLDAP32) set(USE_WIN32_LDAP OFF) endif() @@ -445,75 +430,78 @@ if(NOT CURL_DISABLE_LDAP) if(CMAKE_USE_OPENLDAP AND USE_WIN32_LDAP) message(FATAL_ERROR "Cannot use USE_WIN32_LDAP and CMAKE_USE_OPENLDAP at the same time") endif() - + # Now that we know, we're not using windows LDAP... - if(NOT USE_WIN32_LDAP) + if(USE_WIN32_LDAP) + check_include_file_concat("winldap.h" HAVE_WINLDAP_H) + check_include_file_concat("winber.h" HAVE_WINBER_H) + else() # Check for LDAP set(CMAKE_REQUIRED_LIBRARIES ${OPENSSL_LIBRARIES}) check_library_exists_concat(${CMAKE_LDAP_LIB} ldap_init HAVE_LIBLDAP) check_library_exists_concat(${CMAKE_LBER_LIB} ber_init HAVE_LIBLBER) - else() - check_include_file_concat("winldap.h" HAVE_WINLDAP_H) - check_include_file_concat("winber.h" HAVE_WINBER_H) - endif() - - set(CMAKE_LDAP_INCLUDE_DIR "" CACHE STRING "Path to LDAP include directory") - if(CMAKE_LDAP_INCLUDE_DIR) - set(CMAKE_REQUIRED_INCLUDES ${CMAKE_LDAP_INCLUDE_DIR}) - endif() - check_include_file_concat("ldap.h" HAVE_LDAP_H) - check_include_file_concat("lber.h" HAVE_LBER_H) - - if(NOT HAVE_LDAP_H) - message(STATUS "LDAP_H not found CURL_DISABLE_LDAP set ON") - set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) - elseif(NOT HAVE_LIBLDAP) - message(STATUS "LDAP library '${CMAKE_LDAP_LIB}' not found CURL_DISABLE_LDAP set ON") - set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) - else() - if(CMAKE_USE_OPENLDAP) - set(USE_OPENLDAP ON) - endif() + + set(CMAKE_REQUIRED_INCLUDES_BAK ${CMAKE_REQUIRED_INCLUDES}) + set(CMAKE_LDAP_INCLUDE_DIR "" CACHE STRING "Path to LDAP include directory") if(CMAKE_LDAP_INCLUDE_DIR) - include_directories(${CMAKE_LDAP_INCLUDE_DIR}) + list(APPEND CMAKE_REQUIRED_INCLUDES ${CMAKE_LDAP_INCLUDE_DIR}) endif() - set(NEED_LBER_H ON) - set(_HEADER_LIST) - if(HAVE_WINDOWS_H) - list(APPEND _HEADER_LIST "windows.h") - endif() - if(HAVE_SYS_TYPES_H) - list(APPEND _HEADER_LIST "sys/types.h") - endif() - list(APPEND _HEADER_LIST "ldap.h") + check_include_file_concat("ldap.h" HAVE_LDAP_H) + check_include_file_concat("lber.h" HAVE_LBER_H) + + if(NOT HAVE_LDAP_H) + message(STATUS "LDAP_H not found CURL_DISABLE_LDAP set ON") + set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) + set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES_BAK}) #LDAP includes won't be used + elseif(NOT HAVE_LIBLDAP) + message(STATUS "LDAP library '${CMAKE_LDAP_LIB}' not found CURL_DISABLE_LDAP set ON") + set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) + set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES_BAK}) #LDAP includes won't be used + else() + if(CMAKE_USE_OPENLDAP) + set(USE_OPENLDAP ON) + endif() + if(CMAKE_LDAP_INCLUDE_DIR) + include_directories(${CMAKE_LDAP_INCLUDE_DIR}) + endif() + set(NEED_LBER_H ON) + set(_HEADER_LIST) + if(HAVE_WINDOWS_H) + list(APPEND _HEADER_LIST "windows.h") + endif() + if(HAVE_SYS_TYPES_H) + list(APPEND _HEADER_LIST "sys/types.h") + endif() + list(APPEND _HEADER_LIST "ldap.h") - set(_SRC_STRING "") - foreach(_HEADER ${_HEADER_LIST}) - set(_INCLUDE_STRING "${_INCLUDE_STRING}#include <${_HEADER}>\n") - endforeach() + set(_SRC_STRING "") + foreach(_HEADER ${_HEADER_LIST}) + set(_INCLUDE_STRING "${_INCLUDE_STRING}#include <${_HEADER}>\n") + endforeach() - set(_SRC_STRING - " - ${_INCLUDE_STRING} - int main(int argc, char ** argv) - { - BerValue *bvp = NULL; - BerElement *bep = ber_init(bvp); - ber_free(bep, 1); - return 0; - }" - ) - set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -DLDAP_DEPRECATED=1") - list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LDAP_LIB}) - if(HAVE_LIBLBER) - list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LBER_LIB}) - endif() - check_c_source_compiles("${_SRC_STRING}" NOT_NEED_LBER_H) + set(_SRC_STRING + " + ${_INCLUDE_STRING} + int main(int argc, char ** argv) + { + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + return 0; + }" + ) + set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -DLDAP_DEPRECATED=1") + list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LDAP_LIB}) + if(HAVE_LIBLBER) + list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LBER_LIB}) + endif() + check_c_source_compiles("${_SRC_STRING}" NOT_NEED_LBER_H) - if(NOT_NEED_LBER_H) - set(NEED_LBER_H OFF) - else() - set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -DNEED_LBER_H") + if(NOT_NEED_LBER_H) + set(NEED_LBER_H OFF) + else() + set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -DNEED_LBER_H") + endif() endif() endif() @@ -551,6 +539,7 @@ if(CURL_ZLIB) set(HAVE_LIBZ ON) list(APPEND CURL_LIBS ${ZLIB_LIBRARIES}) include_directories(${ZLIB_INCLUDE_DIRS}) + list(APPEND CMAKE_REQUIRED_INCLUDES ${ZLIB_INCLUDE_DIRS}) endif() endif() endif() @@ -577,7 +566,7 @@ if(CMAKE_USE_LIBSSH2) if(LIBSSH2_FOUND) list(APPEND CURL_LIBS ${LIBSSH2_LIBRARY}) set(CMAKE_REQUIRED_LIBRARIES ${LIBSSH2_LIBRARY}) - set(CMAKE_REQUIRED_INCLUDES "${LIBSSH2_INCLUDE_DIR}") + list(APPEND CMAKE_REQUIRED_INCLUDES "${LIBSSH2_INCLUDE_DIR}") include_directories("${LIBSSH2_INCLUDE_DIR}") set(HAVE_LIBSSH2 ON) set(USE_LIBSSH2 ON) @@ -610,7 +599,7 @@ if(CMAKE_USE_GSSAPI) message(STATUS "Found ${GSS_FLAVOUR} GSSAPI version: \"${GSS_VERSION}\"") - set(CMAKE_REQUIRED_INCLUDES ${GSS_INCLUDE_DIR}) + list(APPEND CMAKE_REQUIRED_INCLUDES ${GSS_INCLUDE_DIRECTORIES}) check_include_file_concat("gssapi/gssapi.h" HAVE_GSSAPI_GSSAPI_H) check_include_file_concat("gssapi/gssapi_generic.h" HAVE_GSSAPI_GSSAPI_GENERIC_H) check_include_file_concat("gssapi/gssapi_krb5.h" HAVE_GSSAPI_GSSAPI_KRB5_H) @@ -646,7 +635,7 @@ if(CMAKE_USE_GSSAPI) endif() - include_directories(${GSS_INCLUDE_DIR}) + include_directories(${GSS_INCLUDE_DIRECTORIES}) link_directories(${GSS_LINK_DIRECTORIES}) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GSS_COMPILER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${GSS_LINKER_FLAGS}") @@ -666,12 +655,26 @@ else() unset(USE_UNIX_SOCKETS CACHE) endif() + # Check for header files if(NOT UNIX) check_include_file_concat("windows.h" HAVE_WINDOWS_H) check_include_file_concat("winsock.h" HAVE_WINSOCK_H) check_include_file_concat("ws2tcpip.h" HAVE_WS2TCPIP_H) check_include_file_concat("winsock2.h" HAVE_WINSOCK2_H) + if(CURL_WINDOWS_SSPI) + set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -DSECURITY_WIN32") + check_include_file_concat("sspi.h" HAVE_SSPI_H) + if(HAVE_SSPI_H) + check_include_file_concat("schannel.h" HAVE_SCHANNEL_H) + set(USE_WINDOWS_SSPI ON) + if(HAVE_SCHANNEL_H) + set(USE_SCHANNEL ON) + set(SSL_ENABLED ON) + set(CURL_LIBS ${CURL_LIBS} "crypt32") + endif() + endif() + endif() else() set(HAVE_WINDOWS_H 0) set(HAVE_WINSOCK_H 0) @@ -1090,9 +1093,6 @@ add_subdirectory(lib) if(BUILD_CURL_EXE) add_subdirectory(src) endif() -if(BUILD_CURL_TESTS) - add_subdirectory(tests) -endif() #----------------------------------------------------------------------------- # CMake-specific curl code. @@ -1107,6 +1107,11 @@ install(FILES COPYING DESTINATION ${CMAKE_DOC_DIR}/cmcurl) #----------------------------------------------------------------------------- if(0) # This code not needed for building within CMake. +include(CTest) +if(BUILD_TESTING) + add_subdirectory(tests) +endif() + # TODO support GNUTLS, NSS, POLARSSL, AXTLS, CYASSL, WINSSL, DARWINSSL if(USE_OPENSSL) set(SSL_ENABLED 1) @@ -1123,7 +1128,8 @@ endfunction() # Clear list and try to detect available features set(_items) -_add_if("SSL" SSL_ENABLED) +_add_if("WinSSL" SSL_ENABLED AND USE_WINDOWS_SSPI) +_add_if("OpenSSL" SSL_ENABLED AND USE_OPENSSL) _add_if("IPv6" ENABLE_IPV6) _add_if("unix-sockets" USE_UNIX_SOCKETS) _add_if("libz" HAVE_LIBZ) @@ -1221,7 +1227,7 @@ set(VERSIONNUM "${CURL_VERSION_NUM}") # Finally generate a "curl-config" matching this config configure_file("${CURL_SOURCE_DIR}/curl-config.in" "${CURL_BINARY_DIR}/curl-config" @ONLY) -install(FILES "${CMAKE_BINARY_DIR}/curl-config" +install(FILES "${CURL_BINARY_DIR}/curl-config" DESTINATION bin PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE @@ -1231,7 +1237,7 @@ install(FILES "${CMAKE_BINARY_DIR}/curl-config" # Finally generate a pkg-config file matching this config configure_file("${CURL_SOURCE_DIR}/libcurl.pc.in" "${CURL_BINARY_DIR}/libcurl.pc" @ONLY) -install(FILES "${CMAKE_BINARY_DIR}/libcurl.pc" +install(FILES "${CURL_BINARY_DIR}/libcurl.pc" DESTINATION lib/pkgconfig) # This needs to be run very last so other parts of the scripts can take advantage of this. diff --git a/Utilities/cmcurl/COPYING b/Utilities/cmcurl/COPYING index 6b5d59f..a98663e 100644 --- a/Utilities/cmcurl/COPYING +++ b/Utilities/cmcurl/COPYING @@ -1,6 +1,7 @@ COPYRIGHT AND PERMISSION NOTICE -Copyright (c) 1996 - 2015, Daniel Stenberg, <daniel@haxx.se>. +Copyright (c) 1996 - 2016, Daniel Stenberg, <daniel@haxx.se>, and many +contributors, see the THANKS file. All rights reserved. diff --git a/Utilities/cmcurl/README-CMake.txt b/Utilities/cmcurl/README-CMake.txt deleted file mode 100644 index 1e75672..0000000 --- a/Utilities/cmcurl/README-CMake.txt +++ /dev/null @@ -1,66 +0,0 @@ -The Utilities/cmcurl directory contains a reduced distribution -of the curl 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 curl snapshots and -nothing else. No Git ref points explicitly to the head of this -branch, but it is merged into our history. - -Update curl from upstream as follows. Create a local branch to -explicitly reference the upstream snapshot branch head: - - git branch curl-upstream 70654261 - -Use a temporary directory to checkout the branch: - - mkdir curl-tmp - cd curl-tmp - git init - git pull .. curl-upstream - rm -rf * - -Now place the (reduced) curl content in this directory. See -instructions shown by - - git log 70654261 - -for help extracting the content from the upstream repo. Then run -the following commands to commit the new version. Substitute the -appropriate date and version number: - - git add --all - - GIT_AUTHOR_NAME='Curl Upstream' \ - GIT_AUTHOR_EMAIL='curl-library@cool.haxx.se' \ - GIT_AUTHOR_DATE='Tue Aug 11 20:13:01 2015 +0200' \ - git commit -m 'curl 7.44.0 (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:curl-upstream - cd .. - rm -rf curl-tmp - -Create a topic in the main repository on which to perform the update: - - git checkout -b update-curl master - -Merge the curl-upstream branch as a subtree: - - git merge -s recursive -X subtree=Utilities/cmcurl \ - curl-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 curl-upstream - -to get the commit from which the curl-upstream branch must be started -on the next update. Edit the "git branch curl-upstream" line above to -record it, and commit this file. diff --git a/Utilities/cmcurl/include/curl/curl.h b/Utilities/cmcurl/include/curl/curl.h index 86ce1ff..dfaea5d 100644 --- a/Utilities/cmcurl/include/curl/curl.h +++ b/Utilities/cmcurl/include/curl/curl.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,10 +24,10 @@ /* * If you have libcurl problems, all docs and details are found here: - * http://curl.haxx.se/libcurl/ + * https://curl.haxx.se/libcurl/ * * curl-library mailing list subscription and unsubscription web interface: - * http://cool.haxx.se/mailman/listinfo/curl-library/ + * https://cool.haxx.se/mailman/listinfo/curl-library/ */ #include "curlver.h" /* libcurl version defines */ @@ -56,7 +56,8 @@ #include <time.h> #if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) -#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || defined(__LWIP_OPT_H__)) +#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ + defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) /* The check above prevents the winsock2 inclusion if winsock.h already was included, since they can't co-exist without problems */ #include <winsock2.h> @@ -90,7 +91,13 @@ extern "C" { #endif +#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) +typedef struct Curl_easy CURL; +typedef struct Curl_share CURLSH; +#else typedef void CURL; +typedef void CURLSH; +#endif /* * libcurl external API function linkage decorations. @@ -112,7 +119,7 @@ typedef void CURL; #ifndef curl_socket_typedef /* socket typedef */ -#if defined(WIN32) && !defined(__LWIP_OPT_H__) +#if defined(WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) typedef SOCKET curl_socket_t; #define CURL_SOCKET_BAD INVALID_SOCKET #else @@ -127,7 +134,8 @@ struct curl_httppost { char *name; /* pointer to allocated name */ long namelength; /* length of name length */ char *contents; /* pointer to allocated data contents */ - long contentslength; /* length of contents field */ + long contentslength; /* length of contents field, see also + CURL_HTTPPOST_LARGE */ char *buffer; /* pointer to allocated buffer contents */ long bufferlength; /* length of buffer field */ char *contenttype; /* Content-Type */ @@ -136,24 +144,33 @@ struct curl_httppost { file, this link should link to following files */ long flags; /* as defined below */ -#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */ -#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */ -#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer - do not free in formfree */ -#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer - do not free in formfree */ -#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */ -#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */ -#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the - regular read callback to get the data - and pass the given pointer as custom - pointer */ + +/* specified content is a file name */ +#define CURL_HTTPPOST_FILENAME (1<<0) +/* specified content is a file name */ +#define CURL_HTTPPOST_READFILE (1<<1) +/* name is only stored pointer do not free in formfree */ +#define CURL_HTTPPOST_PTRNAME (1<<2) +/* contents is only stored pointer do not free in formfree */ +#define CURL_HTTPPOST_PTRCONTENTS (1<<3) +/* upload file from buffer */ +#define CURL_HTTPPOST_BUFFER (1<<4) +/* upload file from pointer contents */ +#define CURL_HTTPPOST_PTRBUFFER (1<<5) +/* upload file contents by using the regular read callback to get the data and + pass the given pointer as custom pointer */ +#define CURL_HTTPPOST_CALLBACK (1<<6) +/* use size in 'contentlen', added in 7.46.0 */ +#define CURL_HTTPPOST_LARGE (1<<7) char *showfilename; /* The file name to show. If not set, the actual file name will be used (if this is a file part) */ void *userp; /* custom pointer used for HTTPPOST_CALLBACK posts */ + curl_off_t contentlen; /* alternative length of contents + field. Used if CURL_HTTPPOST_LARGE is + set. Added in 7.46.0 */ }; /* This is the CURLOPT_PROGRESSFUNCTION callback proto. It is now considered @@ -362,6 +379,7 @@ typedef curlioerr (*curl_ioctl_callback)(CURL *handle, int cmd, void *clientp); +#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* * The following typedef's are signatures of malloc, free, realloc, strdup and * calloc respectively. Function pointers of these types can be passed to the @@ -374,6 +392,9 @@ typedef void *(*curl_realloc_callback)(void *ptr, size_t size); typedef char *(*curl_strdup_callback)(const char *str); typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); +#define CURL_DID_MEMORY_FUNC_TYPEDEFS +#endif + /* the kind of data that is passed to information_callback*/ typedef enum { CURLINFO_TEXT = 0, @@ -460,9 +481,9 @@ typedef enum { CURLE_OBSOLETE44, /* 44 - NOT USED */ CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ CURLE_OBSOLETE46, /* 46 - NOT USED */ - CURLE_TOO_MANY_REDIRECTS , /* 47 - catch endless re-direct loops */ + CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */ CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ - CURLE_TELNET_OPTION_SYNTAX , /* 49 - Malformed telnet option */ + CURLE_TELNET_OPTION_SYNTAX, /* 49 - Malformed telnet option */ CURLE_OBSOLETE50, /* 50 - NOT USED */ CURLE_PEER_FAILED_VERIFICATION, /* 51 - peer's certificate or fingerprint wasn't verified fine */ @@ -524,6 +545,8 @@ typedef enum { CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not match */ CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */ + CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer + */ CURL_LAST /* never use! */ } CURLcode; @@ -818,9 +841,13 @@ typedef enum { but 32 */ #define CURLOPTTYPE_LONG 0 #define CURLOPTTYPE_OBJECTPOINT 10000 +#define CURLOPTTYPE_STRINGPOINT 10000 #define CURLOPTTYPE_FUNCTIONPOINT 20000 #define CURLOPTTYPE_OFF_T 30000 +/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the + string options from the header file */ + /* name is uppercase CURLOPT_<name>, type is one of the defined CURLOPTTYPE_<type> number is unique identifier */ @@ -834,6 +861,7 @@ typedef enum { /* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ #define LONG CURLOPTTYPE_LONG #define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT +#define STRINGPOINT CURLOPTTYPE_OBJECTPOINT #define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT #define OFF_T CURLOPTTYPE_OFF_T #define CINIT(name,type,number) CURLOPT_/**/name = type + number @@ -850,22 +878,22 @@ typedef enum { CINIT(WRITEDATA, OBJECTPOINT, 1), /* The full URL to get/put */ - CINIT(URL, OBJECTPOINT, 2), + CINIT(URL, STRINGPOINT, 2), /* Port number to connect to, if other than default. */ CINIT(PORT, LONG, 3), /* Name of proxy to use. */ - CINIT(PROXY, OBJECTPOINT, 4), + CINIT(PROXY, STRINGPOINT, 4), /* "user:password;options" to use when fetching. */ - CINIT(USERPWD, OBJECTPOINT, 5), + CINIT(USERPWD, STRINGPOINT, 5), /* "user:password" to use with proxy. */ - CINIT(PROXYUSERPWD, OBJECTPOINT, 6), + CINIT(PROXYUSERPWD, STRINGPOINT, 6), /* Range to get, specified as an ASCII string. */ - CINIT(RANGE, OBJECTPOINT, 7), + CINIT(RANGE, STRINGPOINT, 7), /* not used */ @@ -902,14 +930,14 @@ typedef enum { CINIT(POSTFIELDS, OBJECTPOINT, 15), /* Set the referrer page (needed by some CGIs) */ - CINIT(REFERER, OBJECTPOINT, 16), + CINIT(REFERER, STRINGPOINT, 16), /* Set the FTP PORT string (interface name, named or numerical IP address) Use i.e '-' to use default address. */ - CINIT(FTPPORT, OBJECTPOINT, 17), + CINIT(FTPPORT, STRINGPOINT, 17), /* Set the User-Agent string (examined by some CGIs) */ - CINIT(USERAGENT, OBJECTPOINT, 18), + CINIT(USERAGENT, STRINGPOINT, 18), /* If the download receives less than "low speed limit" bytes/second * during "low speed time" seconds, the operations is aborted. @@ -932,7 +960,7 @@ typedef enum { CINIT(RESUME_FROM, LONG, 21), /* Set cookie in request: */ - CINIT(COOKIE, OBJECTPOINT, 22), + CINIT(COOKIE, STRINGPOINT, 22), /* This points to a linked list of headers, struct curl_slist kind. This list is also used for RTSP (in spite of its name) */ @@ -942,10 +970,10 @@ typedef enum { CINIT(HTTPPOST, OBJECTPOINT, 24), /* name of the file keeping your private SSL-certificate */ - CINIT(SSLCERT, OBJECTPOINT, 25), + CINIT(SSLCERT, STRINGPOINT, 25), /* password for the SSL or SSH private key */ - CINIT(KEYPASSWD, OBJECTPOINT, 26), + CINIT(KEYPASSWD, STRINGPOINT, 26), /* send TYPE parameter? */ CINIT(CRLF, LONG, 27), @@ -959,7 +987,7 @@ typedef enum { /* point to a file to read the initial cookies from, also enables "cookie awareness" */ - CINIT(COOKIEFILE, OBJECTPOINT, 31), + CINIT(COOKIEFILE, STRINGPOINT, 31), /* What version to specifically try to use. See CURL_SSLVERSION defines below. */ @@ -978,9 +1006,9 @@ typedef enum { HTTP: DELETE, TRACE and others FTP: to use a different list command */ - CINIT(CUSTOMREQUEST, OBJECTPOINT, 36), + CINIT(CUSTOMREQUEST, STRINGPOINT, 36), - /* HTTP request, for odd commands like DELETE, TRACE and others */ + /* FILE handle to use instead of stderr */ CINIT(STDERR, OBJECTPOINT, 37), /* 38 is not used */ @@ -1037,19 +1065,19 @@ typedef enum { CINIT(HTTPPROXYTUNNEL, LONG, 61), /* Set the interface string to use as outgoing network interface */ - CINIT(INTERFACE, OBJECTPOINT, 62), + CINIT(INTERFACE, STRINGPOINT, 62), /* Set the krb4/5 security level, this also enables krb4/5 awareness. This * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string * is set but doesn't match one of these, 'private' will be used. */ - CINIT(KRBLEVEL, OBJECTPOINT, 63), + CINIT(KRBLEVEL, STRINGPOINT, 63), /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ CINIT(SSL_VERIFYPEER, LONG, 64), /* The CApath or CAfile used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true */ - CINIT(CAINFO, OBJECTPOINT, 65), + CINIT(CAINFO, STRINGPOINT, 65), /* 66 = OBSOLETE */ /* 67 = OBSOLETE */ @@ -1083,10 +1111,10 @@ typedef enum { /* Set to a file name that contains random data for libcurl to use to seed the random engine when doing SSL connects. */ - CINIT(RANDOM_FILE, OBJECTPOINT, 76), + CINIT(RANDOM_FILE, STRINGPOINT, 76), /* Set to the Entropy Gathering Daemon socket pathname */ - CINIT(EGDSOCKET, OBJECTPOINT, 77), + CINIT(EGDSOCKET, STRINGPOINT, 77), /* Time-out connect operations after this amount of seconds, if connects are OK within this time, then fine... This only aborts the connect phase. */ @@ -1108,10 +1136,10 @@ typedef enum { /* Specify which file name to write all known cookies in after completed operation. Set file name to "-" (dash) to make it go to stdout. */ - CINIT(COOKIEJAR, OBJECTPOINT, 82), + CINIT(COOKIEJAR, STRINGPOINT, 82), /* Specify which SSL ciphers to use */ - CINIT(SSL_CIPHER_LIST, OBJECTPOINT, 83), + CINIT(SSL_CIPHER_LIST, STRINGPOINT, 83), /* Specify which HTTP version to use! This must be set to one of the CURL_HTTP_VERSION* enums set below. */ @@ -1123,16 +1151,16 @@ typedef enum { CINIT(FTP_USE_EPSV, LONG, 85), /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ - CINIT(SSLCERTTYPE, OBJECTPOINT, 86), + CINIT(SSLCERTTYPE, STRINGPOINT, 86), /* name of the file keeping your private SSL-key */ - CINIT(SSLKEY, OBJECTPOINT, 87), + CINIT(SSLKEY, STRINGPOINT, 87), /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ - CINIT(SSLKEYTYPE, OBJECTPOINT, 88), + CINIT(SSLKEYTYPE, STRINGPOINT, 88), /* crypto engine for the SSL-sub system */ - CINIT(SSLENGINE, OBJECTPOINT, 89), + CINIT(SSLENGINE, STRINGPOINT, 89), /* set the crypto engine for the SSL-sub system as default the param has no meaning... @@ -1159,7 +1187,7 @@ typedef enum { /* The CApath directory used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true */ - CINIT(CAPATH, OBJECTPOINT, 97), + CINIT(CAPATH, STRINGPOINT, 97), /* Instruct libcurl to use a smaller receive buffer */ CINIT(BUFFERSIZE, LONG, 98), @@ -1179,7 +1207,7 @@ typedef enum { /* Set the Accept-Encoding string. Use this to tell a server you would like the response to be compressed. Before 7.21.6, this was known as CURLOPT_ENCODING */ - CINIT(ACCEPT_ENCODING, OBJECTPOINT, 102), + CINIT(ACCEPT_ENCODING, STRINGPOINT, 102), /* Set pointer to private data */ CINIT(PRIVATE, OBJECTPOINT, 103), @@ -1260,7 +1288,7 @@ typedef enum { to parse (using the CURLOPT_NETRC option). If not set, libcurl will do a poor attempt to find the user's home directory and check for a .netrc file in there. */ - CINIT(NETRC_FILE, OBJECTPOINT, 118), + CINIT(NETRC_FILE, STRINGPOINT, 118), /* Enable SSL/TLS for FTP, pick one of: CURLUSESSL_TRY - try using SSL, proceed anyway otherwise @@ -1303,10 +1331,10 @@ typedef enum { /* zero terminated string for pass on to the FTP server when asked for "account" info */ - CINIT(FTP_ACCOUNT, OBJECTPOINT, 134), + CINIT(FTP_ACCOUNT, STRINGPOINT, 134), - /* feed cookies into cookie engine */ - CINIT(COOKIELIST, OBJECTPOINT, 135), + /* feed cookie into cookie engine */ + CINIT(COOKIELIST, STRINGPOINT, 135), /* ignore Content-Length */ CINIT(IGNORE_CONTENT_LENGTH, LONG, 136), @@ -1352,7 +1380,7 @@ typedef enum { CINIT(MAX_RECV_SPEED_LARGE, OFF_T, 146), /* Pointer to command string to send if USER/PASS fails. */ - CINIT(FTP_ALTERNATIVE_TO_USER, OBJECTPOINT, 147), + CINIT(FTP_ALTERNATIVE_TO_USER, STRINGPOINT, 147), /* callback function for setting socket options */ CINIT(SOCKOPTFUNCTION, FUNCTIONPOINT, 148), @@ -1366,8 +1394,8 @@ typedef enum { CINIT(SSH_AUTH_TYPES, LONG, 151), /* Used by scp/sftp to do public/private key authentication */ - CINIT(SSH_PUBLIC_KEYFILE, OBJECTPOINT, 152), - CINIT(SSH_PRIVATE_KEYFILE, OBJECTPOINT, 153), + CINIT(SSH_PUBLIC_KEYFILE, STRINGPOINT, 152), + CINIT(SSH_PRIVATE_KEYFILE, STRINGPOINT, 153), /* Send CCC (Clear Command Channel) after authentication */ CINIT(FTP_SSL_CCC, LONG, 154), @@ -1391,7 +1419,7 @@ typedef enum { CINIT(POSTREDIR, LONG, 161), /* used by scp/sftp to verify the host's public key */ - CINIT(SSH_HOST_PUBLIC_KEY_MD5, OBJECTPOINT, 162), + CINIT(SSH_HOST_PUBLIC_KEY_MD5, STRINGPOINT, 162), /* Callback function for opening socket (instead of socket(2)). Optionally, callback is able change the address or refuse to connect returning @@ -1411,10 +1439,10 @@ typedef enum { CINIT(SEEKDATA, OBJECTPOINT, 168), /* CRL file */ - CINIT(CRLFILE, OBJECTPOINT, 169), + CINIT(CRLFILE, STRINGPOINT, 169), /* Issuer certificate */ - CINIT(ISSUERCERT, OBJECTPOINT, 170), + CINIT(ISSUERCERT, STRINGPOINT, 170), /* (IPv6) Address scope */ CINIT(ADDRESS_SCOPE, LONG, 171), @@ -1424,12 +1452,12 @@ typedef enum { CINIT(CERTINFO, LONG, 172), /* "name" and "pwd" to use when fetching. */ - CINIT(USERNAME, OBJECTPOINT, 173), - CINIT(PASSWORD, OBJECTPOINT, 174), + CINIT(USERNAME, STRINGPOINT, 173), + CINIT(PASSWORD, STRINGPOINT, 174), /* "name" and "pwd" to use with Proxy when fetching. */ - CINIT(PROXYUSERNAME, OBJECTPOINT, 175), - CINIT(PROXYPASSWORD, OBJECTPOINT, 176), + CINIT(PROXYUSERNAME, STRINGPOINT, 175), + CINIT(PROXYPASSWORD, STRINGPOINT, 176), /* Comma separated list of hostnames defining no-proxy zones. These should match both hostnames directly, and hostnames within a domain. For @@ -1438,13 +1466,13 @@ typedef enum { implementations of this, .local.com will be considered to be the same as local.com. A single * is the only valid wildcard, and effectively disables the use of proxy. */ - CINIT(NOPROXY, OBJECTPOINT, 177), + CINIT(NOPROXY, STRINGPOINT, 177), /* block size for TFTP transfers */ CINIT(TFTP_BLKSIZE, LONG, 178), /* Socks Service */ - CINIT(SOCKS5_GSSAPI_SERVICE, OBJECTPOINT, 179), + CINIT(SOCKS5_GSSAPI_SERVICE, STRINGPOINT, 179), /* DEPRECATED, do not use! */ /* Socks Service */ CINIT(SOCKS5_GSSAPI_NEC, LONG, 180), @@ -1462,7 +1490,7 @@ typedef enum { CINIT(REDIR_PROTOCOLS, LONG, 182), /* set the SSH knownhost file name to use */ - CINIT(SSH_KNOWNHOSTS, OBJECTPOINT, 183), + CINIT(SSH_KNOWNHOSTS, STRINGPOINT, 183), /* set the SSH host key callback, must point to a curl_sshkeycallback function */ @@ -1472,9 +1500,9 @@ typedef enum { CINIT(SSH_KEYDATA, OBJECTPOINT, 185), /* set the SMTP mail originator */ - CINIT(MAIL_FROM, OBJECTPOINT, 186), + CINIT(MAIL_FROM, STRINGPOINT, 186), - /* set the SMTP mail receiver(s) */ + /* set the list of SMTP mail receiver(s) */ CINIT(MAIL_RCPT, OBJECTPOINT, 187), /* FTP: send PRET before PASV */ @@ -1484,13 +1512,13 @@ typedef enum { CINIT(RTSP_REQUEST, LONG, 189), /* The RTSP session identifier */ - CINIT(RTSP_SESSION_ID, OBJECTPOINT, 190), + CINIT(RTSP_SESSION_ID, STRINGPOINT, 190), /* The RTSP stream URI */ - CINIT(RTSP_STREAM_URI, OBJECTPOINT, 191), + CINIT(RTSP_STREAM_URI, STRINGPOINT, 191), /* The Transport: header to use in RTSP requests */ - CINIT(RTSP_TRANSPORT, OBJECTPOINT, 192), + CINIT(RTSP_TRANSPORT, STRINGPOINT, 192), /* Manually initialize the client RTSP CSeq for this handle */ CINIT(RTSP_CLIENT_CSEQ, LONG, 193), @@ -1528,13 +1556,13 @@ typedef enum { CINIT(RESOLVE, OBJECTPOINT, 203), /* Set a username for authenticated TLS */ - CINIT(TLSAUTH_USERNAME, OBJECTPOINT, 204), + CINIT(TLSAUTH_USERNAME, STRINGPOINT, 204), /* Set a password for authenticated TLS */ - CINIT(TLSAUTH_PASSWORD, OBJECTPOINT, 205), + CINIT(TLSAUTH_PASSWORD, STRINGPOINT, 205), /* Set authentication type for authenticated TLS */ - CINIT(TLSAUTH_TYPE, OBJECTPOINT, 206), + CINIT(TLSAUTH_TYPE, STRINGPOINT, 206), /* Set to 1 to enable the "TE:" header in HTTP requests to ask for compressed transfer-encoded responses. Set to 0 to disable the use of TE: @@ -1557,7 +1585,7 @@ typedef enum { CINIT(GSSAPI_DELEGATION, LONG, 210), /* Set the name servers to use for DNS resolution */ - CINIT(DNS_SERVERS, OBJECTPOINT, 211), + CINIT(DNS_SERVERS, STRINGPOINT, 211), /* Time-out accept operations (currently for FTP only) after this amount of miliseconds. */ @@ -1574,7 +1602,7 @@ typedef enum { CINIT(SSL_OPTIONS, LONG, 216), /* Set the SMTP auth originator */ - CINIT(MAIL_AUTH, OBJECTPOINT, 217), + CINIT(MAIL_AUTH, STRINGPOINT, 217), /* Enable/disable SASL initial response */ CINIT(SASL_IR, LONG, 218), @@ -1585,23 +1613,23 @@ typedef enum { CINIT(XFERINFOFUNCTION, FUNCTIONPOINT, 219), /* The XOAUTH2 bearer token */ - CINIT(XOAUTH2_BEARER, OBJECTPOINT, 220), + CINIT(XOAUTH2_BEARER, STRINGPOINT, 220), /* Set the interface string to use as outgoing network * interface for DNS requests. * Only supported by the c-ares DNS backend */ - CINIT(DNS_INTERFACE, OBJECTPOINT, 221), + CINIT(DNS_INTERFACE, STRINGPOINT, 221), /* Set the local IPv4 address to use for outgoing DNS requests. * Only supported by the c-ares DNS backend */ - CINIT(DNS_LOCAL_IP4, OBJECTPOINT, 222), + CINIT(DNS_LOCAL_IP4, STRINGPOINT, 222), /* Set the local IPv4 address to use for outgoing DNS requests. * Only supported by the c-ares DNS backend */ - CINIT(DNS_LOCAL_IP6, OBJECTPOINT, 223), + CINIT(DNS_LOCAL_IP6, STRINGPOINT, 223), /* Set authentication options directly */ - CINIT(LOGIN_OPTIONS, OBJECTPOINT, 224), + CINIT(LOGIN_OPTIONS, STRINGPOINT, 224), /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */ CINIT(SSL_ENABLE_NPN, LONG, 225), @@ -1622,10 +1650,10 @@ typedef enum { /* The public key in DER form used to validate the peer public key this option is used only if SSL_VERIFYPEER is true */ - CINIT(PINNEDPUBLICKEY, OBJECTPOINT, 230), + CINIT(PINNEDPUBLICKEY, STRINGPOINT, 230), /* Path to Unix domain socket */ - CINIT(UNIX_SOCKET_PATH, OBJECTPOINT, 231), + CINIT(UNIX_SOCKET_PATH, STRINGPOINT, 231), /* Set if we should verify the certificate status. */ CINIT(SSL_VERIFYSTATUS, LONG, 232), @@ -1637,14 +1665,36 @@ typedef enum { CINIT(PATH_AS_IS, LONG, 234), /* Proxy Service Name */ - CINIT(PROXY_SERVICE_NAME, OBJECTPOINT, 235), + CINIT(PROXY_SERVICE_NAME, STRINGPOINT, 235), /* Service Name */ - CINIT(SERVICE_NAME, OBJECTPOINT, 236), + CINIT(SERVICE_NAME, STRINGPOINT, 236), /* Wait/don't wait for pipe/mutex to clarify */ CINIT(PIPEWAIT, LONG, 237), + /* Set the protocol used when curl is given a URL without a protocol */ + CINIT(DEFAULT_PROTOCOL, STRINGPOINT, 238), + + /* Set stream weight, 1 - 256 (default is 16) */ + CINIT(STREAM_WEIGHT, LONG, 239), + + /* Set stream dependency on another CURL handle */ + CINIT(STREAM_DEPENDS, OBJECTPOINT, 240), + + /* Set E-xclusive stream dependency on another CURL handle */ + CINIT(STREAM_DEPENDS_E, OBJECTPOINT, 241), + + /* Do not send any tftp option requests to the server */ + CINIT(TFTP_NO_OPTIONS, LONG, 242), + + /* Linked-list of host:port:connect-to-host:connect-to-port, + overrides the URL's host:port (only for the network layer) */ + CINIT(CONNECT_TO, OBJECTPOINT, 243), + + /* Set TCP Fast Open */ + CINIT(TCP_FASTOPEN, LONG, 244), + CURLOPT_LASTENTRY /* the last unused */ } CURLoption; @@ -1694,7 +1744,10 @@ enum { for us! */ CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ - CURL_HTTP_VERSION_2_0, /* please use HTTP 2.0 in the request */ + CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */ + CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */ + CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1 + Upgrade */ CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ }; @@ -1819,6 +1872,7 @@ typedef enum { CFINIT(OBSOLETE2), CFINIT(STREAM), + CFINIT(CONTENTLEN), /* added in 7.46.0, provide a curl_off_t length */ CURLFORM_LASTENTRY /* the last unused */ } CURLformoption; @@ -2073,12 +2127,18 @@ typedef enum { CURLSSLBACKEND_CYASSL = 7, CURLSSLBACKEND_SCHANNEL = 8, CURLSSLBACKEND_DARWINSSL = 9, - CURLSSLBACKEND_AXTLS = 10 + CURLSSLBACKEND_AXTLS = 10, + CURLSSLBACKEND_MBEDTLS = 11 } curl_sslbackend; +/* aliases for library clones and renames */ +#define CURLSSLBACKEND_LIBRESSL 1 +#define CURLSSLBACKEND_BORINGSSL 1 +#define CURLSSLBACKEND_WOLFSSL 6 + /* Information about the SSL library used and the respective internal SSL handle, which can be used to obtain further information regarding the - connection. Asked for with CURLINFO_TLS_SESSION. */ + connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */ struct curl_tlssessioninfo { curl_sslbackend backend; void *internals; @@ -2088,6 +2148,7 @@ struct curl_tlssessioninfo { #define CURLINFO_LONG 0x200000 #define CURLINFO_DOUBLE 0x300000 #define CURLINFO_SLIST 0x400000 +#define CURLINFO_SOCKET 0x500000 #define CURLINFO_MASK 0x0fffff #define CURLINFO_TYPEMASK 0xf00000 @@ -2136,9 +2197,12 @@ typedef enum { CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, CURLINFO_TLS_SESSION = CURLINFO_SLIST + 43, + CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44, + CURLINFO_TLS_SSL_PTR = CURLINFO_SLIST + 45, + CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46, /* Fill in new entries below here! */ - CURLINFO_LASTONE = 43 + CURLINFO_LASTONE = 46 } CURLINFO; /* CURLINFO_RESPONSE_CODE is the new name for the option previously known as @@ -2200,7 +2264,6 @@ typedef void (*curl_unlock_function)(CURL *handle, curl_lock_data data, void *userptr); -typedef void CURLSH; typedef enum { CURLSHE_OK, /* all is fine */ @@ -2298,6 +2361,8 @@ typedef struct { #define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ #define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ #define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ +#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used + for cookie domain verification */ /* * NAME curl_version_info() diff --git a/Utilities/cmcurl/include/curl/curlbuild.h.cmake b/Utilities/cmcurl/include/curl/curlbuild.h.cmake index 6608694..c8b4f52 100644 --- a/Utilities/cmcurl/include/curl/curlbuild.h.cmake +++ b/Utilities/cmcurl/include/curl/curlbuild.h.cmake @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -35,7 +35,7 @@ * * If you think that something actually needs to be changed, adjusted * or fixed in this file, then, report it on the libcurl development - * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/ + * mailing list: https://cool.haxx.se/mailman/listinfo/curl-library/ * * This header file shall only export symbols which are 'curl' or 'CURL' * prefixed, otherwise public name space would be polluted. diff --git a/Utilities/cmcurl/include/curl/curlrules.h b/Utilities/cmcurl/include/curl/curlrules.h index 7c2ede3..55d21f6 100644 --- a/Utilities/cmcurl/include/curl/curlrules.h +++ b/Utilities/cmcurl/include/curl/curlrules.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -47,7 +47,7 @@ * library is properly built and used. * * You can find further help on the libcurl development mailing list: - * http://cool.haxx.se/mailman/listinfo/curl-library/ + * https://cool.haxx.se/mailman/listinfo/curl-library/ * * NOTE 2 * ------ diff --git a/Utilities/cmcurl/include/curl/curlver.h b/Utilities/cmcurl/include/curl/curlver.h index a41fdef..09f612a 100644 --- a/Utilities/cmcurl/include/curl/curlver.h +++ b/Utilities/cmcurl/include/curl/curlver.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,17 +26,17 @@ a script at release-time. This was made its own header file in 7.11.2 */ /* This is the global package copyright */ -#define LIBCURL_COPYRIGHT "1996 - 2015 Daniel Stenberg, <daniel@haxx.se>." +#define LIBCURL_COPYRIGHT "1996 - 2016 Daniel Stenberg, <daniel@haxx.se>." /* This is the version number of the libcurl package from which this header file origins: */ -#define LIBCURL_VERSION "7.44.0" +#define LIBCURL_VERSION "7.50.1" /* The numeric version number is also available "in parts" by using these defines: */ #define LIBCURL_VERSION_MAJOR 7 -#define LIBCURL_VERSION_MINOR 44 -#define LIBCURL_VERSION_PATCH 0 +#define LIBCURL_VERSION_MINOR 50 +#define LIBCURL_VERSION_PATCH 1 /* This is the numeric version of the libcurl version number, meant for easier parsing and comparions by programs. The LIBCURL_VERSION_NUM define will @@ -57,7 +57,7 @@ CURL_VERSION_BITS() macro since curl's own configure script greps for it and needs it to contain the full number. */ -#define LIBCURL_VERSION_NUM 0x072C00 +#define LIBCURL_VERSION_NUM 0x073201 /* * This is the date and time when the full source package was created. The diff --git a/Utilities/cmcurl/include/curl/easy.h b/Utilities/cmcurl/include/curl/easy.h index c1e3e76..afc766c 100644 --- a/Utilities/cmcurl/include/curl/easy.h +++ b/Utilities/cmcurl/include/curl/easy.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/include/curl/mprintf.h b/Utilities/cmcurl/include/curl/mprintf.h index c6b0d76..e20f546 100644 --- a/Utilities/cmcurl/include/curl/mprintf.h +++ b/Utilities/cmcurl/include/curl/mprintf.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,8 +24,7 @@ #include <stdarg.h> #include <stdio.h> /* needed for FILE */ - -#include "curl.h" +#include "curl.h" /* for CURL_EXTERN */ #ifdef __cplusplus extern "C" { @@ -44,29 +43,6 @@ CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, CURL_EXTERN char *curl_maprintf(const char *format, ...); CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); -#ifdef _MPRINTF_REPLACE -# undef printf -# undef fprintf -# undef sprintf -# undef vsprintf -# undef snprintf -# undef vprintf -# undef vfprintf -# undef vsnprintf -# undef aprintf -# undef vaprintf -# define printf curl_mprintf -# define fprintf curl_mfprintf -# define sprintf curl_msprintf -# define vsprintf curl_mvsprintf -# define snprintf curl_msnprintf -# define vprintf curl_mvprintf -# define vfprintf curl_mvfprintf -# define vsnprintf curl_mvsnprintf -# define aprintf curl_maprintf -# define vaprintf curl_mvaprintf -#endif - #ifdef __cplusplus } #endif diff --git a/Utilities/cmcurl/include/curl/multi.h b/Utilities/cmcurl/include/curl/multi.h index 0f1561d..f93e511 100644 --- a/Utilities/cmcurl/include/curl/multi.h +++ b/Utilities/cmcurl/include/curl/multi.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -52,7 +52,11 @@ extern "C" { #endif +#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) +typedef struct Curl_multi CURLM; +#else typedef void CURLM; +#endif typedef enum { CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or diff --git a/Utilities/cmcurl/include/curl/stdcheaders.h b/Utilities/cmcurl/include/curl/stdcheaders.h index ad82ef6..6f0f7f3 100644 --- a/Utilities/cmcurl/include/curl/stdcheaders.h +++ b/Utilities/cmcurl/include/curl/stdcheaders.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/include/curl/typecheck-gcc.h b/Utilities/cmcurl/include/curl/typecheck-gcc.h index 13fb0fa..6ec8bcf 100644 --- a/Utilities/cmcurl/include/curl/typecheck-gcc.h +++ b/Utilities/cmcurl/include/curl/typecheck-gcc.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -218,60 +218,67 @@ _CURL_WARNING(_curl_easy_getinfo_err_curl_slist, /* evaluates to true if option takes a char* argument */ #define _curl_is_string_option(option) \ - ((option) == CURLOPT_URL || \ - (option) == CURLOPT_PROXY || \ - (option) == CURLOPT_INTERFACE || \ - (option) == CURLOPT_NETRC_FILE || \ - (option) == CURLOPT_USERPWD || \ - (option) == CURLOPT_USERNAME || \ - (option) == CURLOPT_PASSWORD || \ - (option) == CURLOPT_PROXYUSERPWD || \ - (option) == CURLOPT_PROXYUSERNAME || \ - (option) == CURLOPT_PROXYPASSWORD || \ - (option) == CURLOPT_NOPROXY || \ - (option) == CURLOPT_ACCEPT_ENCODING || \ - (option) == CURLOPT_REFERER || \ - (option) == CURLOPT_USERAGENT || \ + ((option) == CURLOPT_ACCEPT_ENCODING || \ + (option) == CURLOPT_CAINFO || \ + (option) == CURLOPT_CAPATH || \ (option) == CURLOPT_COOKIE || \ (option) == CURLOPT_COOKIEFILE || \ (option) == CURLOPT_COOKIEJAR || \ (option) == CURLOPT_COOKIELIST || \ + (option) == CURLOPT_CRLFILE || \ + (option) == CURLOPT_CUSTOMREQUEST || \ + (option) == CURLOPT_DEFAULT_PROTOCOL || \ + (option) == CURLOPT_DNS_INTERFACE || \ + (option) == CURLOPT_DNS_LOCAL_IP4 || \ + (option) == CURLOPT_DNS_LOCAL_IP6 || \ + (option) == CURLOPT_DNS_SERVERS || \ + (option) == CURLOPT_EGDSOCKET || \ (option) == CURLOPT_FTPPORT || \ - (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ (option) == CURLOPT_FTP_ACCOUNT || \ - (option) == CURLOPT_RANGE || \ - (option) == CURLOPT_CUSTOMREQUEST || \ - (option) == CURLOPT_SSLCERT || \ - (option) == CURLOPT_SSLCERTTYPE || \ - (option) == CURLOPT_SSLKEY || \ - (option) == CURLOPT_SSLKEYTYPE || \ + (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ + (option) == CURLOPT_INTERFACE || \ + (option) == CURLOPT_ISSUERCERT || \ (option) == CURLOPT_KEYPASSWD || \ - (option) == CURLOPT_SSLENGINE || \ - (option) == CURLOPT_CAINFO || \ - (option) == CURLOPT_CAPATH || \ - (option) == CURLOPT_RANDOM_FILE || \ - (option) == CURLOPT_EGDSOCKET || \ - (option) == CURLOPT_SSL_CIPHER_LIST || \ (option) == CURLOPT_KRBLEVEL || \ - (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ - (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ - (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ - (option) == CURLOPT_CRLFILE || \ - (option) == CURLOPT_ISSUERCERT || \ - (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ - (option) == CURLOPT_SSH_KNOWNHOSTS || \ + (option) == CURLOPT_LOGIN_OPTIONS || \ + (option) == CURLOPT_MAIL_AUTH || \ (option) == CURLOPT_MAIL_FROM || \ + (option) == CURLOPT_NETRC_FILE || \ + (option) == CURLOPT_NOPROXY || \ + (option) == CURLOPT_PASSWORD || \ + (option) == CURLOPT_PINNEDPUBLICKEY || \ + (option) == CURLOPT_PROXY || \ + (option) == CURLOPT_PROXYPASSWORD || \ + (option) == CURLOPT_PROXYUSERNAME || \ + (option) == CURLOPT_PROXYUSERPWD || \ + (option) == CURLOPT_PROXY_SERVICE_NAME || \ + (option) == CURLOPT_RANDOM_FILE || \ + (option) == CURLOPT_RANGE || \ + (option) == CURLOPT_REFERER || \ (option) == CURLOPT_RTSP_SESSION_ID || \ (option) == CURLOPT_RTSP_STREAM_URI || \ (option) == CURLOPT_RTSP_TRANSPORT || \ - (option) == CURLOPT_XOAUTH2_BEARER || \ - (option) == CURLOPT_DNS_SERVERS || \ - (option) == CURLOPT_DNS_INTERFACE || \ - (option) == CURLOPT_DNS_LOCAL_IP4 || \ - (option) == CURLOPT_DNS_LOCAL_IP6 || \ - (option) == CURLOPT_LOGIN_OPTIONS || \ - (option) == CURLOPT_PROXY_SERVICE_NAME || \ (option) == CURLOPT_SERVICE_NAME || \ + (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ + (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ + (option) == CURLOPT_SSH_KNOWNHOSTS || \ + (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ + (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ + (option) == CURLOPT_SSLCERT || \ + (option) == CURLOPT_SSLCERTTYPE || \ + (option) == CURLOPT_SSLENGINE || \ + (option) == CURLOPT_SSLKEY || \ + (option) == CURLOPT_SSLKEYTYPE || \ + (option) == CURLOPT_SSL_CIPHER_LIST || \ + (option) == CURLOPT_TLSAUTH_PASSWORD || \ + (option) == CURLOPT_TLSAUTH_TYPE || \ + (option) == CURLOPT_TLSAUTH_USERNAME || \ + (option) == CURLOPT_UNIX_SOCKET_PATH || \ + (option) == CURLOPT_URL || \ + (option) == CURLOPT_USERAGENT || \ + (option) == CURLOPT_USERNAME || \ + (option) == CURLOPT_USERPWD || \ + (option) == CURLOPT_XOAUTH2_BEARER || \ 0) /* evaluates to true if option takes a curl_write_callback argument */ @@ -287,21 +294,22 @@ _CURL_WARNING(_curl_easy_getinfo_err_curl_slist, /* evaluates to true if option takes a data argument to pass to a callback */ #define _curl_is_cb_data_option(option) \ - ((option) == CURLOPT_WRITEDATA || \ - (option) == CURLOPT_READDATA || \ + ((option) == CURLOPT_CHUNK_DATA || \ + (option) == CURLOPT_CLOSESOCKETDATA || \ + (option) == CURLOPT_DEBUGDATA || \ + (option) == CURLOPT_FNMATCH_DATA || \ + (option) == CURLOPT_HEADERDATA || \ + (option) == CURLOPT_INTERLEAVEDATA || \ (option) == CURLOPT_IOCTLDATA || \ - (option) == CURLOPT_SOCKOPTDATA || \ (option) == CURLOPT_OPENSOCKETDATA || \ + (option) == CURLOPT_PRIVATE || \ (option) == CURLOPT_PROGRESSDATA || \ - (option) == CURLOPT_HEADERDATA || \ - (option) == CURLOPT_DEBUGDATA || \ - (option) == CURLOPT_SSL_CTX_DATA || \ + (option) == CURLOPT_READDATA || \ (option) == CURLOPT_SEEKDATA || \ - (option) == CURLOPT_PRIVATE || \ + (option) == CURLOPT_SOCKOPTDATA || \ (option) == CURLOPT_SSH_KEYDATA || \ - (option) == CURLOPT_INTERLEAVEDATA || \ - (option) == CURLOPT_CHUNK_DATA || \ - (option) == CURLOPT_FNMATCH_DATA || \ + (option) == CURLOPT_SSL_CTX_DATA || \ + (option) == CURLOPT_WRITEDATA || \ 0) /* evaluates to true if option takes a POST data argument (void* or char*) */ @@ -312,13 +320,15 @@ _CURL_WARNING(_curl_easy_getinfo_err_curl_slist, /* evaluates to true if option takes a struct curl_slist * argument */ #define _curl_is_slist_option(option) \ - ((option) == CURLOPT_HTTPHEADER || \ - (option) == CURLOPT_HTTP200ALIASES || \ - (option) == CURLOPT_QUOTE || \ + ((option) == CURLOPT_HTTP200ALIASES || \ + (option) == CURLOPT_HTTPHEADER || \ + (option) == CURLOPT_MAIL_RCPT || \ (option) == CURLOPT_POSTQUOTE || \ (option) == CURLOPT_PREQUOTE || \ + (option) == CURLOPT_PROXYHEADER || \ + (option) == CURLOPT_QUOTE || \ + (option) == CURLOPT_RESOLVE || \ (option) == CURLOPT_TELNETOPTIONS || \ - (option) == CURLOPT_MAIL_RCPT || \ 0) /* groups of curl_easy_getinfo infos that take the same type of argument */ diff --git a/Utilities/cmcurl/lib/Makefile.inc b/Utilities/cmcurl/lib/Makefile.inc index d444a6b..0ed998c 100644 --- a/Utilities/cmcurl/lib/Makefile.inc +++ b/Utilities/cmcurl/lib/Makefile.inc @@ -5,11 +5,11 @@ # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # -# Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. +# Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms -# are also available at http://curl.haxx.se/docs/copyright.html. +# are also available at https://curl.haxx.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is @@ -20,13 +20,22 @@ # ########################################################################### +LIB_VAUTH_CFILES = vauth/vauth.c vauth/cleartext.c vauth/cram.c \ + vauth/digest.c vauth/digest_sspi.c vauth/krb5_gssapi.c \ + vauth/krb5_sspi.c vauth/ntlm.c vauth/ntlm_sspi.c vauth/oauth2.c \ + vauth/spnego_gssapi.c vauth/spnego_sspi.c + +LIB_VAUTH_HFILES = vauth/vauth.h vauth/digest.h vauth/ntlm.h + LIB_VTLS_CFILES = vtls/openssl.c vtls/gtls.c vtls/vtls.c vtls/nss.c \ vtls/polarssl.c vtls/polarssl_threadlock.c vtls/axtls.c \ - vtls/cyassl.c vtls/schannel.c vtls/darwinssl.c vtls/gskit.c + vtls/cyassl.c vtls/schannel.c vtls/darwinssl.c vtls/gskit.c \ + vtls/mbedtls.c LIB_VTLS_HFILES = vtls/openssl.h vtls/vtls.h vtls/gtls.h \ vtls/nssg.h vtls/polarssl.h vtls/polarssl_threadlock.h vtls/axtls.h \ - vtls/cyassl.h vtls/schannel.h vtls/darwinssl.h vtls/gskit.h + vtls/cyassl.h vtls/schannel.h vtls/darwinssl.h vtls/gskit.h \ + vtls/mbedtls.h LIB_CFILES = file.c timeval.c base64.c hostip.c progress.c formdata.c \ cookie.c http.c sendf.c ftp.c url.c dict.c if2ip.c speedcheck.c \ @@ -41,12 +50,10 @@ LIB_CFILES = file.c timeval.c base64.c hostip.c progress.c formdata.c \ curl_sspi.c slist.c nonblock.c curl_memrchr.c imap.c pop3.c smtp.c \ pingpong.c rtsp.c curl_threads.c warnless.c hmac.c curl_rtmp.c \ openldap.c curl_gethostname.c gopher.c idn_win32.c \ - http_negotiate_sspi.c http_proxy.c non-ascii.c asyn-ares.c \ - asyn-thread.c curl_gssapi.c curl_ntlm.c curl_ntlm_wb.c \ - curl_ntlm_core.c curl_ntlm_msgs.c curl_sasl.c curl_multibyte.c \ - hostcheck.c conncache.c pipeline.c dotdot.c x509asn1.c \ - http2.c curl_sasl_sspi.c smb.c curl_sasl_gssapi.c curl_endian.c \ - curl_des.c + http_proxy.c non-ascii.c asyn-ares.c asyn-thread.c curl_gssapi.c \ + http_ntlm.c curl_ntlm_wb.c curl_ntlm_core.c curl_sasl.c \ + curl_multibyte.c hostcheck.c conncache.c pipeline.c dotdot.c \ + x509asn1.c http2.c smb.c curl_endian.c curl_des.c system_win32.c LIB_HFILES = arpa_telnet.h netrc.h file.h timeval.h hostip.h progress.h \ formdata.h cookie.h http.h sendf.h ftp.h url.h dict.h if2ip.h \ @@ -61,13 +68,13 @@ LIB_HFILES = arpa_telnet.h netrc.h file.h timeval.h hostip.h progress.h \ slist.h nonblock.h curl_memrchr.h imap.h pop3.h smtp.h pingpong.h \ rtsp.h curl_threads.h warnless.h curl_hmac.h curl_rtmp.h \ curl_gethostname.h gopher.h http_proxy.h non-ascii.h asyn.h \ - curl_ntlm.h curl_gssapi.h curl_ntlm_wb.h curl_ntlm_core.h \ - curl_ntlm_msgs.h curl_sasl.h curl_multibyte.h hostcheck.h \ - conncache.h curl_setup_once.h multihandle.h setup-vms.h pipeline.h \ - dotdot.h x509asn1.h http2.h sigpipe.h smb.h curl_endian.h curl_des.h \ - curl_printf.h + http_ntlm.h curl_gssapi.h curl_ntlm_wb.h curl_ntlm_core.h \ + curl_sasl.h curl_multibyte.h hostcheck.h conncache.h \ + curl_setup_once.h multihandle.h setup-vms.h pipeline.h dotdot.h \ + x509asn1.h http2.h sigpipe.h smb.h curl_endian.h curl_des.h \ + curl_printf.h system_win32.h LIB_RCFILES = libcurl.rc -CSOURCES = $(LIB_CFILES) $(LIB_VTLS_CFILES) -HHEADERS = $(LIB_HFILES) $(LIB_VTLS_HFILES) +CSOURCES = $(LIB_CFILES) $(LIB_VAUTH_CFILES) $(LIB_VTLS_CFILES) +HHEADERS = $(LIB_HFILES) $(LIB_VAUTH_HFILES) $(LIB_VTLS_HFILES) diff --git a/Utilities/cmcurl/lib/amigaos.c b/Utilities/cmcurl/lib/amigaos.c index e3ff85f..5591d22 100644 --- a/Utilities/cmcurl/lib/amigaos.c +++ b/Utilities/cmcurl/lib/amigaos.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -35,7 +35,7 @@ extern int errno, h_errno; #include <stabs.h> void __request(const char *msg); #else -# define __request( msg ) Printf( msg "\n\a") +# define __request(msg) Printf(msg "\n\a") #endif void Curl_amiga_cleanup() diff --git a/Utilities/cmcurl/lib/amigaos.h b/Utilities/cmcurl/lib/amigaos.h index 76578be..02bee16 100644 --- a/Utilities/cmcurl/lib/amigaos.h +++ b/Utilities/cmcurl/lib/amigaos.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/arpa_telnet.h b/Utilities/cmcurl/lib/arpa_telnet.h index 098d9a9..ec23872 100644 --- a/Utilities/cmcurl/lib/arpa_telnet.h +++ b/Utilities/cmcurl/lib/arpa_telnet.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/asyn-ares.c b/Utilities/cmcurl/lib/asyn-ares.c index 98ecdfd..2aed94f 100644 --- a/Utilities/cmcurl/lib/asyn-ares.c +++ b/Utilities/cmcurl/lib/asyn-ares.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -68,7 +68,6 @@ #include "connect.h" #include "select.h" #include "progress.h" -#include "curl_printf.h" # if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \ (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) @@ -83,8 +82,9 @@ #define HAVE_CARES_CALLBACK_TIMEOUTS 1 #endif +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" struct ResolverResults { @@ -249,7 +249,7 @@ int Curl_resolver_getsock(struct connectdata *conn, static int waitperform(struct connectdata *conn, int timeout_ms) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int nfds; int bitmask; ares_socket_t socks[ARES_GETSOCK_MAXNUM]; @@ -309,7 +309,7 @@ static int waitperform(struct connectdata *conn, int timeout_ms) CURLcode Curl_resolver_is_resolved(struct connectdata *conn, struct Curl_dns_entry **dns) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ResolverResults *res = (struct ResolverResults *) conn->async.os_specific; CURLcode result = CURLE_OK; @@ -353,7 +353,7 @@ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); struct Curl_dns_entry *temp_entry; @@ -492,7 +492,7 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, int *waitp) { char *bufp; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct in_addr in; int family = PF_INET; #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ @@ -583,7 +583,7 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, return NULL; /* no struct yet */ } -CURLcode Curl_set_dns_servers(struct SessionHandle *data, +CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers) { CURLcode result = CURLE_NOT_BUILT_IN; @@ -621,7 +621,7 @@ CURLcode Curl_set_dns_servers(struct SessionHandle *data, return result; } -CURLcode Curl_set_dns_interface(struct SessionHandle *data, +CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf) { #if (ARES_VERSION >= 0x010704) @@ -638,7 +638,7 @@ CURLcode Curl_set_dns_interface(struct SessionHandle *data, #endif } -CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4) { #if (ARES_VERSION >= 0x010704) @@ -663,7 +663,7 @@ CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, #endif } -CURLcode Curl_set_dns_local_ip6(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6) { #if (ARES_VERSION >= 0x010704) && defined(ENABLE_IPV6) diff --git a/Utilities/cmcurl/lib/asyn-thread.c b/Utilities/cmcurl/lib/asyn-thread.c index bd47d5a..7cce01a 100644 --- a/Utilities/cmcurl/lib/asyn-thread.c +++ b/Utilities/cmcurl/lib/asyn-thread.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -69,10 +69,9 @@ #include "inet_ntop.h" #include "curl_threads.h" #include "connect.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" - -/* The last #include file should be: */ #include "memdebug.h" /*********************************************************************** @@ -280,6 +279,9 @@ static unsigned int CURL_STDCALL getaddrinfo_thread (void *arg) if(tsd->sock_error == 0) tsd->sock_error = RESOLVER_ENOMEM; } + else { + Curl_addrinfo_set_port(tsd->res, tsd->port); + } Curl_mutex_acquire(tsd->mtx); if(tsd->done) { @@ -495,7 +497,7 @@ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, CURLcode Curl_resolver_is_resolved(struct connectdata *conn, struct Curl_dns_entry **entry) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct thread_data *td = (struct thread_data*) conn->async.os_specific; int done = 0; @@ -603,6 +605,7 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, *waitp = 0; /* default to synchronous response */ +#ifndef USE_RESOLVE_ON_IPS /* First check if this is an IPv4 address string */ if(Curl_inet_pton(AF_INET, hostname, &in) > 0) /* This is a dotted IP address 123.123.123.123-style */ @@ -610,10 +613,13 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, #ifdef CURLRES_IPV6 /* check if this is an IPv6 address string */ - if(Curl_inet_pton (AF_INET6, hostname, &in6) > 0) + if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0) /* This is an IPv6 address literal */ return Curl_ip2addr(AF_INET6, &in6, hostname, port); +#endif /* CURLRES_IPV6 */ +#endif /* !USE_RESOLVE_ON_IPS */ +#ifdef CURLRES_IPV6 /* * Check if a limited name resolve has been requested. */ @@ -632,7 +638,6 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, if((pf != PF_INET) && !Curl_ipv6works()) /* The stack seems to be a non-IPv6 one */ pf = PF_INET; - #endif /* CURLRES_IPV6 */ memset(&hints, 0, sizeof(hints)); @@ -657,12 +662,16 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, hostname, port, Curl_strerror(conn, SOCKERRNO)); return NULL; } + else { + Curl_addrinfo_set_port(res, port); + } + return res; } #endif /* !HAVE_GETADDRINFO */ -CURLcode Curl_set_dns_servers(struct SessionHandle *data, +CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers) { (void)data; @@ -671,7 +680,7 @@ CURLcode Curl_set_dns_servers(struct SessionHandle *data, } -CURLcode Curl_set_dns_interface(struct SessionHandle *data, +CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf) { (void)data; @@ -679,7 +688,7 @@ CURLcode Curl_set_dns_interface(struct SessionHandle *data, return CURLE_NOT_BUILT_IN; } -CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4) { (void)data; @@ -687,7 +696,7 @@ CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, return CURLE_NOT_BUILT_IN; } -CURLcode Curl_set_dns_local_ip6(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6) { (void)data; diff --git a/Utilities/cmcurl/lib/asyn.h b/Utilities/cmcurl/lib/asyn.h index 1b681ea..3adc366 100644 --- a/Utilities/cmcurl/lib/asyn.h +++ b/Utilities/cmcurl/lib/asyn.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -27,7 +27,7 @@ struct addrinfo; struct hostent; -struct SessionHandle; +struct Curl_easy; struct connectdata; struct Curl_dns_entry; diff --git a/Utilities/cmcurl/lib/base64.c b/Utilities/cmcurl/lib/base64.c index 6b87eed..ad25459 100644 --- a/Utilities/cmcurl/lib/base64.c +++ b/Utilities/cmcurl/lib/base64.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -23,13 +23,13 @@ /* Base64 encoding/decoding */ #include "curl_setup.h" -#include "curl_printf.h" -#include "urldata.h" /* for the SessionHandle definition */ +#include "urldata.h" /* for the Curl_easy definition */ #include "warnless.h" #include "curl_base64.h" #include "non-ascii.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -169,11 +169,11 @@ CURLcode Curl_base64_decode(const char *src, } static CURLcode base64_encode(const char *table64, - struct SessionHandle *data, + struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen) { - CURLcode error; + CURLcode result; unsigned char ibuf[3]; unsigned char obuf[4]; int i; @@ -187,11 +187,11 @@ static CURLcode base64_encode(const char *table64, *outptr = NULL; *outlen = 0; - if(0 == insize) + if(!insize) insize = strlen(indata); - base64data = output = malloc(insize*4/3+4); - if(NULL == output) + base64data = output = malloc(insize * 4 / 3 + 4); + if(!output) return CURLE_OUT_OF_MEMORY; /* @@ -199,10 +199,10 @@ static CURLcode base64_encode(const char *table64, * not the host encoding. And we can't change the actual input * so we copy it to a buffer, translate it, and use that instead. */ - error = Curl_convert_clone(data, indata, insize, &convbuf); - if(error) { + result = Curl_convert_clone(data, indata, insize, &convbuf); + if(result) { free(output); - return error; + return result; } if(convbuf) @@ -233,28 +233,35 @@ static CURLcode base64_encode(const char *table64, table64[obuf[0]], table64[obuf[1]]); break; + case 2: /* two bytes read */ snprintf(output, 5, "%c%c%c=", table64[obuf[0]], table64[obuf[1]], table64[obuf[2]]); break; + default: snprintf(output, 5, "%c%c%c%c", table64[obuf[0]], table64[obuf[1]], table64[obuf[2]], - table64[obuf[3]] ); + table64[obuf[3]]); break; } output += 4; } + + /* Zero terminate */ *output = '\0'; - *outptr = base64data; /* return pointer to new data, allocated memory */ + + /* Return the pointer to the new data (allocated memory) */ + *outptr = base64data; free(convbuf); - *outlen = strlen(base64data); /* return the length of the new data */ + /* Return the length of the new data */ + *outlen = strlen(base64data); return CURLE_OK; } @@ -276,7 +283,7 @@ static CURLcode base64_encode(const char *table64, * * @unittest: 1302 */ -CURLcode Curl_base64_encode(struct SessionHandle *data, +CURLcode Curl_base64_encode(struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen) { @@ -300,10 +307,9 @@ CURLcode Curl_base64_encode(struct SessionHandle *data, * * @unittest: 1302 */ -CURLcode Curl_base64url_encode(struct SessionHandle *data, +CURLcode Curl_base64url_encode(struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen) { return base64_encode(base64url, data, inputbuff, insize, outptr, outlen); } -/* ---- End of Base64 Encoding ---- */ diff --git a/Utilities/cmcurl/lib/conncache.c b/Utilities/cmcurl/lib/conncache.c index c712ed7..32a7030 100644 --- a/Utilities/cmcurl/lib/conncache.c +++ b/Utilities/cmcurl/lib/conncache.c @@ -5,12 +5,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2012, Linus Nielsen Feltzing, <linus@haxx.se> + * Copyright (C) 2012, 2016, Linus Nielsen Feltzing, <linus@haxx.se> * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -32,10 +32,9 @@ #include "sendf.h" #include "rawstr.h" #include "conncache.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" static void conn_llist_dtor(void *user, void *element) @@ -46,7 +45,7 @@ static void conn_llist_dtor(void *user, void *element) data->bundle = NULL; } -static CURLcode bundle_create(struct SessionHandle *data, +static CURLcode bundle_create(struct Curl_easy *data, struct connectbundle **cb_ptr) { (void)data; @@ -132,9 +131,16 @@ void Curl_conncache_destroy(struct conncache *connc) /* returns an allocated key to find a bundle for this connection */ static char *hashkey(struct connectdata *conn) { - return aprintf("%s:%d", - conn->bits.proxy?conn->proxy.name:conn->host.name, - conn->localport); + const char *hostname; + + if(conn->bits.proxy) + hostname = conn->proxy.name; + else if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; + + return aprintf("%s:%d", hostname, conn->port); } /* Look up the bundle with all the connections to the same host this @@ -193,7 +199,7 @@ CURLcode Curl_conncache_add_conn(struct conncache *connc, CURLcode result; struct connectbundle *bundle; struct connectbundle *new_bundle = NULL; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache); if(!bundle) { diff --git a/Utilities/cmcurl/lib/conncache.h b/Utilities/cmcurl/lib/conncache.h index 59181bf..b1dadf9 100644 --- a/Utilities/cmcurl/lib/conncache.h +++ b/Utilities/cmcurl/lib/conncache.h @@ -12,7 +12,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/connect.c b/Utilities/cmcurl/lib/connect.c index 18ac32c..0047f9a 100644 --- a/Utilities/cmcurl/lib/connect.c +++ b/Utilities/cmcurl/lib/connect.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -56,7 +56,6 @@ #include <inet.h> #endif -#include "curl_printf.h" #include "urldata.h" #include "sendf.h" #include "if2ip.h" @@ -73,8 +72,10 @@ #include "warnless.h" #include "conncache.h" #include "multihandle.h" +#include "system_win32.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -103,7 +104,7 @@ struct tcp_keepalive { #endif static void -tcpkeepalive(struct SessionHandle *data, +tcpkeepalive(struct Curl_easy *data, curl_socket_t sockfd) { int optval = data->set.tcp_keepalive?1:0; @@ -178,7 +179,7 @@ singleipconnect(struct connectdata *conn, * * @unittest: 1303 */ -long Curl_timeleft(struct SessionHandle *data, +long Curl_timeleft(struct Curl_easy *data, struct timeval *nowp, bool duringconnect) { @@ -238,7 +239,7 @@ long Curl_timeleft(struct SessionHandle *data, static CURLcode bindlocal(struct connectdata *conn, curl_socket_t sockfd, int af, unsigned int scope) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct Curl_sockaddr_storage sa; struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */ @@ -619,7 +620,7 @@ static bool getaddressinfo(struct sockaddr* sa, char* addr, switch (sa->sa_family) { case AF_INET: - si = (struct sockaddr_in*) sa; + si = (struct sockaddr_in*)(void*) sa; if(Curl_inet_ntop(sa->sa_family, &si->sin_addr, addr, MAX_IPADR_LEN)) { us_port = ntohs(si->sin_port); @@ -629,7 +630,7 @@ static bool getaddressinfo(struct sockaddr* sa, char* addr, break; #ifdef ENABLE_IPV6 case AF_INET6: - si6 = (struct sockaddr_in6*)sa; + si6 = (struct sockaddr_in6*)(void*) sa; if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr, addr, MAX_IPADR_LEN)) { us_port = ntohs(si6->sin6_port); @@ -662,13 +663,13 @@ void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd) curl_socklen_t len; struct Curl_sockaddr_storage ssrem; struct Curl_sockaddr_storage ssloc; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(conn->socktype == SOCK_DGRAM) /* there's no connection! */ return; - if(!conn->bits.reuse) { + if(!conn->bits.reuse && !conn->bits.tcp_fastopen) { int error; len = sizeof(struct Curl_sockaddr_storage); @@ -719,7 +720,7 @@ CURLcode Curl_is_connected(struct connectdata *conn, int sockindex, bool *connected) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; long allow; int error = 0; @@ -764,6 +765,7 @@ CURLcode Curl_is_connected(struct connectdata *conn, rc = Curl_socket_ready(CURL_SOCKET_BAD, conn->tempsock[i], 0); if(rc == 0) { /* no connection yet */ + error = 0; if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) { infof(data, "After %ldms connect time, move on!\n", conn->timeoutms_per_addr); @@ -776,7 +778,7 @@ CURLcode Curl_is_connected(struct connectdata *conn, trynextip(conn, sockindex, 1); } } - else if(rc == CURL_CSELECT_OUT) { + else if(rc == CURL_CSELECT_OUT || conn->bits.tcp_fastopen) { if(verifyconnect(conn->tempsock[i], &error)) { /* we are connected with TCP, awesome! */ @@ -841,6 +843,8 @@ CURLcode Curl_is_connected(struct connectdata *conn, if(result) { /* no more addresses to try */ + const char* hostname; + /* if the first address family runs out of addresses to try before the happy eyeball timeout, go ahead and try the next family now */ if(conn->tempaddr[1] == NULL) { @@ -849,20 +853,27 @@ CURLcode Curl_is_connected(struct connectdata *conn, return result; } + if(conn->bits.proxy) + hostname = conn->proxy.name; + else if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; + failf(data, "Failed to connect to %s port %ld: %s", - conn->bits.proxy?conn->proxy.name:conn->host.name, - conn->port, Curl_strerror(conn, error)); + hostname, conn->port, Curl_strerror(conn, error)); } return result; } -static void tcpnodelay(struct connectdata *conn, - curl_socket_t sockfd) +void Curl_tcpnodelay(struct connectdata *conn, curl_socket_t sockfd) { -#ifdef TCP_NODELAY - struct SessionHandle *data= conn->data; - curl_socklen_t onoff = (curl_socklen_t) data->set.tcp_nodelay; +#if defined(TCP_NODELAY) +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + struct Curl_easy *data = conn->data; +#endif + curl_socklen_t onoff = (curl_socklen_t) 1; int level = IPPROTO_TCP; #if 0 @@ -878,6 +889,10 @@ static void tcpnodelay(struct connectdata *conn, level = pe->p_proto; #endif +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) conn; +#endif + if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff, sizeof(onoff)) < 0) infof(data, "Could not set TCP_NODELAY: %s\n", @@ -898,7 +913,7 @@ static void tcpnodelay(struct connectdata *conn, static void nosigpipe(struct connectdata *conn, curl_socket_t sockfd) { - struct SessionHandle *data= conn->data; + struct Curl_easy *data= conn->data; int onoff = 1; if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff, sizeof(onoff)) < 0) @@ -913,7 +928,7 @@ static void nosigpipe(struct connectdata *conn, /* When you run a program that uses the Windows Sockets API, you may experience slow performance when you copy data to a TCP server. - http://support.microsoft.com/kb/823764 + https://support.microsoft.com/kb/823764 Work-around: Make the Socket Send Buffer Size Larger Than the Program Send Buffer Size @@ -931,43 +946,15 @@ void Curl_sndbufset(curl_socket_t sockfd) int val = CURL_MAX_WRITE_SIZE + 32; int curval = 0; int curlen = sizeof(curval); - DWORD majorVersion = 6; static int detectOsState = DETECT_OS_NONE; if(detectOsState == DETECT_OS_NONE) { -#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \ - (_WIN32_WINNT < _WIN32_WINNT_WIN2K) - OSVERSIONINFO osver; - - memset(&osver, 0, sizeof(osver)); - osver.dwOSVersionInfoSize = sizeof(osver); - - detectOsState = DETECT_OS_PREVISTA; - if(GetVersionEx(&osver)) { - if(osver.dwMajorVersion >= majorVersion) - detectOsState = DETECT_OS_VISTA_OR_LATER; - } -#else - ULONGLONG cm; - OSVERSIONINFOEX osver; - - memset(&osver, 0, sizeof(osver)); - osver.dwOSVersionInfoSize = sizeof(osver); - osver.dwMajorVersion = majorVersion; - - cm = VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_MINORVERSION, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); - - if(VerifyVersionInfo(&osver, (VER_MAJORVERSION | VER_MINORVERSION | - VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR), - cm)) + if(Curl_verify_windows_version(6, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) detectOsState = DETECT_OS_VISTA_OR_LATER; else detectOsState = DETECT_OS_PREVISTA; -#endif } if(detectOsState == DETECT_OS_VISTA_OR_LATER) @@ -995,10 +982,10 @@ static CURLcode singleipconnect(struct connectdata *conn, curl_socket_t *sockp) { struct Curl_sockaddr_ex addr; - int rc; + int rc = -1; int error = 0; bool isconnected = FALSE; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sockfd; CURLcode result; char ipaddress[MAX_IPADR_LEN]; @@ -1033,7 +1020,7 @@ static CURLcode singleipconnect(struct connectdata *conn, is_tcp = (addr.family == AF_INET) && addr.socktype == SOCK_STREAM; #endif if(is_tcp && data->set.tcp_nodelay) - tcpnodelay(conn, sockfd); + Curl_tcpnodelay(conn, sockfd); nosigpipe(conn, sockfd); @@ -1084,7 +1071,29 @@ static CURLcode singleipconnect(struct connectdata *conn, /* Connect TCP sockets, bind UDP */ if(!isconnected && (conn->socktype == SOCK_STREAM)) { - rc = connect(sockfd, &addr.sa_addr, addr.addrlen); + if(conn->bits.tcp_fastopen) { +#if defined(CONNECT_DATA_IDEMPOTENT) /* OS X */ + sa_endpoints_t endpoints; + endpoints.sae_srcif = 0; + endpoints.sae_srcaddr = NULL; + endpoints.sae_srcaddrlen = 0; + endpoints.sae_dstaddr = &addr.sa_addr; + endpoints.sae_dstaddrlen = addr.addrlen; + + rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY, + CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT, + NULL, 0, NULL, NULL); +#elif defined(MSG_FASTOPEN) /* Linux */ + if(conn->given->flags & PROTOPT_SSL) + rc = connect(sockfd, &addr.sa_addr, addr.addrlen); + else + rc = 0; /* Do nothing */ +#endif + } + else { + rc = connect(sockfd, &addr.sa_addr, addr.addrlen); + } + if(-1 == rc) error = SOCKERRNO; } @@ -1140,7 +1149,7 @@ static CURLcode singleipconnect(struct connectdata *conn, CURLcode Curl_connecthost(struct connectdata *conn, /* context */ const struct Curl_dns_entry *remotehost) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct timeval before = Curl_tvnow(); CURLcode result = CURLE_COULDNT_CONNECT; @@ -1199,11 +1208,11 @@ static int conn_is_conn(struct connectdata *conn, void *param) /* * Used to extract socket and connectdata struct for the most recent - * transfer on the given SessionHandle. + * transfer on the given Curl_easy. * * The returned socket will be CURL_SOCKET_BAD in case of failure! */ -curl_socket_t Curl_getconnectinfo(struct SessionHandle *data, +curl_socket_t Curl_getconnectinfo(struct Curl_easy *data, struct connectdata **connp) { curl_socket_t sockfd; @@ -1243,10 +1252,10 @@ curl_socket_t Curl_getconnectinfo(struct SessionHandle *data, } /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */ #ifdef MSG_PEEK - else { + else if(sockfd != CURL_SOCKET_BAD) { /* use the socket */ char buf; - if(recv((RECV_TYPE_ARG1)c->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf, + if(recv((RECV_TYPE_ARG1)sockfd, (RECV_TYPE_ARG2)&buf, (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) { return CURL_SOCKET_BAD; /* FIN received */ } @@ -1303,7 +1312,7 @@ CURLcode Curl_socket(struct connectdata *conn, struct Curl_sockaddr_ex *addr, curl_socket_t *sockfd) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct Curl_sockaddr_ex dummy; if(!addr) diff --git a/Utilities/cmcurl/lib/connect.h b/Utilities/cmcurl/lib/connect.h index 91646c7..6d60e0d 100644 --- a/Utilities/cmcurl/lib/connect.h +++ b/Utilities/cmcurl/lib/connect.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -35,7 +35,7 @@ CURLcode Curl_connecthost(struct connectdata *conn, /* generic function that returns how much time there's left to run, according to the timeouts set */ -long Curl_timeleft(struct SessionHandle *data, +long Curl_timeleft(struct Curl_easy *data, struct timeval *nowp, bool duringconnect); @@ -45,18 +45,18 @@ long Curl_timeleft(struct SessionHandle *data, /* * Used to extract socket and connectdata struct for the most recent - * transfer on the given SessionHandle. + * transfer on the given Curl_easy. * * The returned socket will be CURL_SOCKET_BAD in case of failure! */ -curl_socket_t Curl_getconnectinfo(struct SessionHandle *data, +curl_socket_t Curl_getconnectinfo(struct Curl_easy *data, struct connectdata **connp); #ifdef USE_WINSOCK /* When you run a program that uses the Windows Sockets API, you may experience slow performance when you copy data to a TCP server. - http://support.microsoft.com/kb/823764 + https://support.microsoft.com/kb/823764 Work-around: Make the Socket Send Buffer Size Larger Than the Program Send Buffer Size @@ -102,6 +102,8 @@ CURLcode Curl_socket(struct connectdata *conn, struct Curl_sockaddr_ex *addr, curl_socket_t *sockfd); +void Curl_tcpnodelay(struct connectdata *conn, curl_socket_t sockfd); + #ifdef CURLDEBUG /* * Curl_connclose() sets the bit.close bit to TRUE with an explanation. diff --git a/Utilities/cmcurl/lib/content_encoding.c b/Utilities/cmcurl/lib/content_encoding.c index c68e6e5..fa36aca 100644 --- a/Utilities/cmcurl/lib/content_encoding.c +++ b/Utilities/cmcurl/lib/content_encoding.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -67,7 +67,7 @@ zfree_cb(voidpf opaque, voidpf ptr) static CURLcode process_zlib_error(struct connectdata *conn, z_stream *z) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(z->msg) failf (data, "Error while processing content unencoding: %s", z->msg); @@ -425,7 +425,7 @@ Curl_unencode_gzip_write(struct connectdata *conn, void Curl_unencode_cleanup(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; z_stream *z = &k->z; if(k->zlib_init != ZLIB_UNINIT) diff --git a/Utilities/cmcurl/lib/content_encoding.h b/Utilities/cmcurl/lib/content_encoding.h index 501f6c8..3fadd28 100644 --- a/Utilities/cmcurl/lib/content_encoding.h +++ b/Utilities/cmcurl/lib/content_encoding.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/cookie.c b/Utilities/cmcurl/lib/cookie.c index 22730cf..d5a83fd 100644 --- a/Utilities/cmcurl/lib/cookie.c +++ b/Utilities/cmcurl/lib/cookie.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,13 +26,13 @@ RECEIVING COOKIE INFORMATION ============================ -struct CookieInfo *Curl_cookie_init(struct SessionHandle *data, +struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, const char *file, struct CookieInfo *inc, bool newsession); Inits a cookie struct to store data in a local file. This is always called before any cookies are set. -struct Cookie *Curl_cookie_add(struct SessionHandle *data, +struct Cookie *Curl_cookie_add(struct Curl_easy *data, struct CookieInfo *c, bool httpheader, char *lineptr, const char *domain, const char *path); @@ -84,7 +84,10 @@ Example set of cookies: #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) -#include "curl_printf.h" +#ifdef USE_LIBPSL +# include <libpsl.h> +#endif + #include "urldata.h" #include "cookie.h" #include "strequal.h" @@ -97,7 +100,8 @@ Example set of cookies: #include "curl_memrchr.h" #include "inet_pton.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -256,7 +260,7 @@ static char *sanitize_cookie_path(const char *cookie_path) * * NOTE: OOM or cookie parsing failures are ignored. */ -void Curl_cookie_loadfiles(struct SessionHandle *data) +void Curl_cookie_loadfiles(struct Curl_easy *data) { struct curl_slist *list = data->change.cookielist; if(list) { @@ -305,7 +309,7 @@ static void remove_expired(struct CookieInfo *cookies) pv = NULL; while(co) { nx = co->next; - if((co->expirestr || co->maxage) && co->expires < now) { + if(co->expires && co->expires < now) { if(co == cookies->cookies) { cookies->cookies = co->next; } @@ -358,7 +362,7 @@ static bool isip(const char *domain) ***************************************************************************/ struct Cookie * -Curl_cookie_add(struct SessionHandle *data, +Curl_cookie_add(struct Curl_easy *data, /* The 'data' pointer here may be NULL at times, and thus must only be used very carefully for things that can deal with data being NULL. Such as infof() and similar */ @@ -379,6 +383,10 @@ Curl_cookie_add(struct SessionHandle *data, bool replace_old = FALSE; bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */ +#ifdef USE_LIBPSL + const psl_ctx_t *psl; +#endif + #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; #endif @@ -409,7 +417,7 @@ Curl_cookie_add(struct SessionHandle *data, do { /* we have a <what>=<this> pair or a stand-alone word here */ name[0]=what[0]=0; /* init the buffers */ - if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n =] =%" + if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%" MAX_COOKIE_LINE_TXT "[^;\r\n]", name, what)) { /* Use strstore() below to properly deal with received cookie @@ -419,15 +427,24 @@ Curl_cookie_add(struct SessionHandle *data, bool done = FALSE; bool sep; size_t len=strlen(what); - const char *endofn = &ptr[ strlen(name) ]; - - /* skip trailing spaces in name */ - while(*endofn && ISBLANK(*endofn)) - endofn++; + size_t nlen = strlen(name); + const char *endofn = &ptr[ nlen ]; /* name ends with a '=' ? */ sep = (*endofn == '=')?TRUE:FALSE; + if(nlen) { + endofn--; /* move to the last character */ + if(ISBLANK(*endofn)) { + /* skip trailing spaces in name */ + while(*endofn && ISBLANK(*endofn) && nlen) { + endofn--; + nlen--; + } + name[nlen]=0; /* new end of name */ + } + } + /* Strip off trailing whitespace from the 'what' */ while(len && ISBLANK(what[len-1])) { what[len-1]=0; @@ -439,7 +456,16 @@ Curl_cookie_add(struct SessionHandle *data, while(*whatptr && ISBLANK(*whatptr)) whatptr++; - if(!len) { + if(!co->name && sep) { + /* The very first name/value pair is the actual cookie name */ + co->name = strdup(name); + co->value = strdup(whatptr); + if(!co->name || !co->value) { + badcookie = TRUE; + break; + } + } + else if(!len) { /* this was a "<name>=" with no content, and we must allow 'secure' and 'httponly' specified this weirdly */ done = TRUE; @@ -533,14 +559,6 @@ Curl_cookie_add(struct SessionHandle *data, break; } } - else if(!co->name) { - co->name = strdup(name); - co->value = strdup(whatptr); - if(!co->name || !co->value) { - badcookie = TRUE; - break; - } - } /* else this is the second (or more) name we don't know about! */ @@ -777,6 +795,21 @@ Curl_cookie_add(struct SessionHandle *data, /* at first, remove expired cookies */ remove_expired(c); +#ifdef USE_LIBPSL + /* Check if the domain is a Public Suffix and if yes, ignore the cookie. + This needs a libpsl compiled with builtin data. */ + if(domain && co->domain && !isip(co->domain)) { + if(((psl = psl_builtin()) != NULL) + && !psl_is_cookie_domain_acceptable(psl, domain, co->domain)) { + infof(data, + "cookie '%s' dropped, domain '%s' must not set cookies for '%s'\n", + co->name, domain, co->domain); + freecookie(co); + return NULL; + } + } +#endif + clist = c->cookies; replace_old = FALSE; while(clist) { @@ -880,7 +913,7 @@ Curl_cookie_add(struct SessionHandle *data, * * Returns NULL on out of memory. Invalid cookies are ignored. ****************************************************************************/ -struct CookieInfo *Curl_cookie_init(struct SessionHandle *data, +struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, const char *file, struct CookieInfo *inc, bool newsession) @@ -1247,6 +1280,7 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere) struct Cookie *co; FILE *out; bool use_stdout=FALSE; + char *format_ptr; if((NULL == c) || (0 == c->numcookies)) /* If there are no known cookies, we don't write or even create any @@ -1267,27 +1301,23 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere) return 1; /* failure */ } - if(c) { - char *format_ptr; + fputs("# Netscape HTTP Cookie File\n" + "# https://curl.haxx.se/docs/http-cookies.html\n" + "# This file was generated by libcurl! Edit at your own risk.\n\n", + out); - fputs("# Netscape HTTP Cookie File\n" - "# http://curl.haxx.se/docs/http-cookies.html\n" - "# This file was generated by libcurl! Edit at your own risk.\n\n", - out); - - for(co = c->cookies; co; co = co->next) { - if(!co->domain) - continue; - format_ptr = get_netscape_format(co); - if(format_ptr == NULL) { - fprintf(out, "#\n# Fatal libcurl error\n"); - if(!use_stdout) - fclose(out); - return 1; - } - fprintf(out, "%s\n", format_ptr); - free(format_ptr); + for(co = c->cookies; co; co = co->next) { + if(!co->domain) + continue; + format_ptr = get_netscape_format(co); + if(format_ptr == NULL) { + fprintf(out, "#\n# Fatal libcurl error\n"); + if(!use_stdout) + fclose(out); + return 1; } + fprintf(out, "%s\n", format_ptr); + free(format_ptr); } if(!use_stdout) @@ -1296,7 +1326,7 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere) return 0; } -struct curl_slist *Curl_cookie_list(struct SessionHandle *data) +struct curl_slist *Curl_cookie_list(struct Curl_easy *data) { struct curl_slist *list = NULL; struct curl_slist *beg; @@ -1327,7 +1357,7 @@ struct curl_slist *Curl_cookie_list(struct SessionHandle *data) return list; } -void Curl_flush_cookies(struct SessionHandle *data, int cleanup) +void Curl_flush_cookies(struct Curl_easy *data, int cleanup) { if(data->set.str[STRING_COOKIEJAR]) { if(data->change.cookielist) { diff --git a/Utilities/cmcurl/lib/cookie.h b/Utilities/cmcurl/lib/cookie.h index bd89082..cd7c54a 100644 --- a/Utilities/cmcurl/lib/cookie.h +++ b/Utilities/cmcurl/lib/cookie.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -70,13 +70,13 @@ struct CookieInfo { #define MAX_NAME 1024 #define MAX_NAME_TXT "1023" -struct SessionHandle; +struct Curl_easy; /* * Add a cookie to the internal list of cookies. The domain and path arguments * are only used if the header boolean is TRUE. */ -struct Cookie *Curl_cookie_add(struct SessionHandle *data, +struct Cookie *Curl_cookie_add(struct Curl_easy *data, struct CookieInfo *, bool header, char *lineptr, const char *domain, const char *path); @@ -93,12 +93,12 @@ void Curl_cookie_clearsess(struct CookieInfo *cookies); #define Curl_cookie_cleanup(x) Curl_nop_stmt #define Curl_flush_cookies(x,y) Curl_nop_stmt #else -void Curl_flush_cookies(struct SessionHandle *data, int cleanup); +void Curl_flush_cookies(struct Curl_easy *data, int cleanup); void Curl_cookie_cleanup(struct CookieInfo *); -struct CookieInfo *Curl_cookie_init(struct SessionHandle *data, +struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, const char *, struct CookieInfo *, bool); -struct curl_slist *Curl_cookie_list(struct SessionHandle *data); -void Curl_cookie_loadfiles(struct SessionHandle *data); +struct curl_slist *Curl_cookie_list(struct Curl_easy *data); +void Curl_cookie_loadfiles(struct Curl_easy *data); #endif #endif /* HEADER_CURL_COOKIE_H */ diff --git a/Utilities/cmcurl/lib/curl_addrinfo.c b/Utilities/cmcurl/lib/curl_addrinfo.c index 6627a6b..35eb2dd 100644 --- a/Utilities/cmcurl/lib/curl_addrinfo.c +++ b/Utilities/cmcurl/lib/curl_addrinfo.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -50,10 +50,9 @@ #include "curl_addrinfo.h" #include "inet_pton.h" #include "warnless.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" - -/* The last #include file should be: */ #include "memdebug.h" /* @@ -521,7 +520,11 @@ void curl_dofreeaddrinfo(struct addrinfo *freethis, int line, const char *source) { +#ifdef USE_LWIPSOCK + lwip_freeaddrinfo(freethis); +#else (freeaddrinfo)(freethis); +#endif curl_memlog("ADDR %s:%d freeaddrinfo(%p)\n", source, line, (void *)freethis); } @@ -544,7 +547,11 @@ curl_dogetaddrinfo(const char *hostname, struct addrinfo **result, int line, const char *source) { +#ifdef USE_LWIPSOCK + int res=lwip_getaddrinfo(hostname, service, hints, result); +#else int res=(getaddrinfo)(hostname, service, hints, result); +#endif if(0 == res) /* success */ curl_memlog("ADDR %s:%d getaddrinfo() = %p\n", @@ -556,3 +563,32 @@ curl_dogetaddrinfo(const char *hostname, } #endif /* defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) */ +#if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS) +/* + * Work-arounds the sin6_port is always zero bug on iOS 9.3.2 and Mac OS X + * 10.11.5. + */ +void Curl_addrinfo_set_port(Curl_addrinfo *addrinfo, int port) +{ + Curl_addrinfo *ca; + struct sockaddr_in *addr; +#ifdef ENABLE_IPV6 + struct sockaddr_in6 *addr6; +#endif + for(ca = addrinfo; ca != NULL; ca = ca->ai_next) { + switch (ca->ai_family) { + case AF_INET: + addr = (void *)ca->ai_addr; /* storage area for this info */ + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef ENABLE_IPV6 + case AF_INET6: + addr6 = (void *)ca->ai_addr; /* storage area for this info */ + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + } +} +#endif diff --git a/Utilities/cmcurl/lib/curl_addrinfo.h b/Utilities/cmcurl/lib/curl_addrinfo.h index 4ef8827..1a681e6 100644 --- a/Utilities/cmcurl/lib/curl_addrinfo.h +++ b/Utilities/cmcurl/lib/curl_addrinfo.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -83,7 +83,8 @@ Curl_addrinfo *Curl_str2addr(char *dotted, int port); Curl_addrinfo *Curl_unix2addr(const char *path); #endif -#if defined(CURLDEBUG) && defined(HAVE_FREEADDRINFO) +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(HAVE_FREEADDRINFO) void curl_dofreeaddrinfo(struct addrinfo *freethis, int line, const char *source); @@ -98,4 +99,12 @@ curl_dogetaddrinfo(const char *hostname, int line, const char *source); #endif +#ifdef HAVE_GETADDRINFO +#ifdef USE_RESOLVE_ON_IPS +void Curl_addrinfo_set_port(Curl_addrinfo *addrinfo, int port); +#else +#define Curl_addrinfo_set_port(x,y) +#endif +#endif + #endif /* HEADER_CURL_ADDRINFO_H */ diff --git a/Utilities/cmcurl/lib/curl_base64.h b/Utilities/cmcurl/lib/curl_base64.h index 92896fe..7e9fc26 100644 --- a/Utilities/cmcurl/lib/curl_base64.h +++ b/Utilities/cmcurl/lib/curl_base64.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,10 +22,10 @@ * ***************************************************************************/ -CURLcode Curl_base64_encode(struct SessionHandle *data, +CURLcode Curl_base64_encode(struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen); -CURLcode Curl_base64url_encode(struct SessionHandle *data, +CURLcode Curl_base64url_encode(struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen); diff --git a/Utilities/cmcurl/lib/curl_config.h.cmake b/Utilities/cmcurl/lib/curl_config.h.cmake index 06201ec..20f212b 100644 --- a/Utilities/cmcurl/lib/curl_config.h.cmake +++ b/Utilities/cmcurl/lib/curl_config.h.cmake @@ -18,6 +18,12 @@ /* to disable FTP */ #cmakedefine CURL_DISABLE_FTP 1 +/* to disable GOPHER */ +#cmakedefine CURL_DISABLE_GOPHER 1 + +/* to disable IMAP */ +#cmakedefine CURL_DISABLE_IMAP 1 + /* to disable HTTP */ #cmakedefine CURL_DISABLE_HTTP 1 @@ -27,9 +33,24 @@ /* to disable LDAPS */ #cmakedefine CURL_DISABLE_LDAPS 1 +/* to disable POP3 */ +#cmakedefine CURL_DISABLE_POP3 1 + /* to disable proxies */ #cmakedefine CURL_DISABLE_PROXY 1 +/* to disable RTSP */ +#cmakedefine CURL_DISABLE_RTSP 1 + +/* to disable RTMP */ +#cmakedefine CURL_DISABLE_RTMP 1 + +/* to disable SMB */ +#cmakedefine CURL_DISABLE_SMB 1 + +/* to disable SMTP */ +#cmakedefine CURL_DISABLE_SMTP 1 + /* to disable TELNET */ #cmakedefine CURL_DISABLE_TELNET 1 @@ -888,6 +909,9 @@ /* if PolarSSL is enabled */ #cmakedefine USE_POLARSSL 1 +/* if mbedTLS is enabled */ +#cmakedefine USE_MBEDTLS 1 + /* if libSSH2 is in use */ #cmakedefine USE_LIBSSH2 1 @@ -909,6 +933,9 @@ /* to enable SSPI support */ #cmakedefine USE_WINDOWS_SSPI 1 +/* to enable Windows SSL */ +#cmakedefine USE_SCHANNEL 1 + /* Define to 1 if using yaSSL in OpenSSL compatibility mode. */ #cmakedefine USE_YASSLEMUL 1 diff --git a/Utilities/cmcurl/lib/curl_des.c b/Utilities/cmcurl/lib/curl_des.c index 42c1df9..421c9f7 100644 --- a/Utilities/cmcurl/lib/curl_des.c +++ b/Utilities/cmcurl/lib/curl_des.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,7 +22,7 @@ #include "curl_setup.h" -#if defined(USE_NTLM) && (!defined(USE_OPENSSL) || defined(HAVE_BORINGSSL)) +#if defined(USE_NTLM) && !defined(USE_OPENSSL) #include "curl_des.h" @@ -60,4 +60,4 @@ void Curl_des_set_odd_parity(unsigned char *bytes, size_t len) } } -#endif /* USE_NTLM && (!USE_OPENSSL || HAVE_BORINGSSL) */ +#endif /* USE_NTLM && !USE_OPENSSL */ diff --git a/Utilities/cmcurl/lib/curl_des.h b/Utilities/cmcurl/lib/curl_des.h index b855db4..129060f 100644 --- a/Utilities/cmcurl/lib/curl_des.h +++ b/Utilities/cmcurl/lib/curl_des.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,11 +24,11 @@ #include "curl_setup.h" -#if defined(USE_NTLM) && (!defined(USE_OPENSSL) || defined(HAVE_BORINGSSL)) +#if defined(USE_NTLM) && !defined(USE_OPENSSL) /* Applies odd parity to the given byte array */ void Curl_des_set_odd_parity(unsigned char *bytes, size_t length); -#endif /* USE_NTLM && (!USE_OPENSSL || HAVE_BORINGSSL) */ +#endif /* USE_NTLM && !USE_OPENSSL */ #endif /* HEADER_CURL_DES_H */ diff --git a/Utilities/cmcurl/lib/curl_endian.c b/Utilities/cmcurl/lib/curl_endian.c index bcd66ed..76deca6 100644 --- a/Utilities/cmcurl/lib/curl_endian.c +++ b/Utilities/cmcurl/lib/curl_endian.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_endian.h b/Utilities/cmcurl/lib/curl_endian.h index e384279..df8398c 100644 --- a/Utilities/cmcurl/lib/curl_endian.h +++ b/Utilities/cmcurl/lib/curl_endian.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_fnmatch.c b/Utilities/cmcurl/lib/curl_fnmatch.c index 1e53918..e8108bb 100644 --- a/Utilities/cmcurl/lib/curl_fnmatch.c +++ b/Utilities/cmcurl/lib/curl_fnmatch.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,6 +22,8 @@ #include "curl_setup.h" +#include <curl/curl.h> + #include "curl_fnmatch.h" #include "curl_memory.h" diff --git a/Utilities/cmcurl/lib/curl_fnmatch.h b/Utilities/cmcurl/lib/curl_fnmatch.h index 6335d03..69ffe39 100644 --- a/Utilities/cmcurl/lib/curl_fnmatch.h +++ b/Utilities/cmcurl/lib/curl_fnmatch.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_gethostname.c b/Utilities/cmcurl/lib/curl_gethostname.c index ded1e6f..2591fd8 100644 --- a/Utilities/cmcurl/lib/curl_gethostname.c +++ b/Utilities/cmcurl/lib/curl_gethostname.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_gethostname.h b/Utilities/cmcurl/lib/curl_gethostname.h index 48740f6..07517c5 100644 --- a/Utilities/cmcurl/lib/curl_gethostname.h +++ b/Utilities/cmcurl/lib/curl_gethostname.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_gssapi.c b/Utilities/cmcurl/lib/curl_gssapi.c index 9baece5..bf7c766 100644 --- a/Utilities/cmcurl/lib/curl_gssapi.c +++ b/Utilities/cmcurl/lib/curl_gssapi.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2011 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2011 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -33,7 +33,7 @@ static char krb5_oid_bytes[] = "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"; gss_OID_desc Curl_krb5_mech_oid = { 9, &krb5_oid_bytes }; OM_uint32 Curl_gss_init_sec_context( - struct SessionHandle *data, + struct Curl_easy *data, OM_uint32 *minor_status, gss_ctx_id_t *context, gss_name_t target_name, @@ -76,45 +76,56 @@ OM_uint32 Curl_gss_init_sec_context( NULL /* time_rec */); } -/* - * Curl_gss_log_error() - * - * This is used to log a GSS-API error status. - * - * Parameters: - * - * data [in] - The session handle. - * status [in] - The status code. - * prefix [in] - The prefix of the log message. - */ -void Curl_gss_log_error(struct SessionHandle *data, OM_uint32 status, - const char *prefix) -{ +#define GSS_LOG_BUFFER_LEN 1024 +static size_t display_gss_error(OM_uint32 status, int type, + char *buf, size_t len) { OM_uint32 maj_stat; OM_uint32 min_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; - char buf[1024]; - size_t len; - snprintf(buf, sizeof(buf), "%s", prefix); - len = strlen(buf); do { maj_stat = gss_display_status(&min_stat, status, - GSS_C_MECH_CODE, + type, GSS_C_NO_OID, &msg_ctx, &status_string); - if(sizeof(buf) > len + status_string.length + 1) { - snprintf(buf + len, sizeof(buf) - len, - ": %s", (char*)status_string.value); - len += status_string.length; + if(GSS_LOG_BUFFER_LEN > len + status_string.length + 3) { + len += snprintf(buf + len, GSS_LOG_BUFFER_LEN - len, + "%.*s. ", (int)status_string.length, + (char*)status_string.value); } gss_release_buffer(&min_stat, &status_string); } while(!GSS_ERROR(maj_stat) && msg_ctx != 0); - infof(data, "%s\n", buf); + return len; +} + +/* + * Curl_gss_log_error() + * + * This is used to log a GSS-API error status. + * + * Parameters: + * + * data [in] - The session handle. + * prefix [in] - The prefix of the log message. + * major [in] - The major status code. + * minor [in] - The minor status code. + */ +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor) +{ + char buf[GSS_LOG_BUFFER_LEN]; + size_t len = 0; + + if(major != GSS_S_FAILURE) + len = display_gss_error(major, GSS_C_GSS_CODE, buf, len); + + display_gss_error(minor, GSS_C_MECH_CODE, buf, len); + + infof(data, "%s%s\n", prefix, buf); } #endif /* HAVE_GSSAPI */ diff --git a/Utilities/cmcurl/lib/curl_gssapi.h b/Utilities/cmcurl/lib/curl_gssapi.h index 19aab64..9700a28 100644 --- a/Utilities/cmcurl/lib/curl_gssapi.h +++ b/Utilities/cmcurl/lib/curl_gssapi.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -44,7 +44,7 @@ extern gss_OID_desc Curl_krb5_mech_oid; /* Common method for using GSS-API */ OM_uint32 Curl_gss_init_sec_context( - struct SessionHandle *data, + struct Curl_easy *data, OM_uint32 *minor_status, gss_ctx_id_t *context, gss_name_t target_name, @@ -56,8 +56,8 @@ OM_uint32 Curl_gss_init_sec_context( OM_uint32 *ret_flags); /* Helper to log a GSS-API error status */ -void Curl_gss_log_error(struct SessionHandle *data, OM_uint32 status, - const char *prefix); +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor); /* Provide some definitions missing in old headers */ #ifdef HAVE_OLD_GSSMIT diff --git a/Utilities/cmcurl/lib/curl_hmac.h b/Utilities/cmcurl/lib/curl_hmac.h index 9b65c8c..41703b4 100644 --- a/Utilities/cmcurl/lib/curl_hmac.h +++ b/Utilities/cmcurl/lib/curl_hmac.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_ldap.h b/Utilities/cmcurl/lib/curl_ldap.h index 93fb4b0..27d0381 100644 --- a/Utilities/cmcurl/lib/curl_ldap.h +++ b/Utilities/cmcurl/lib/curl_ldap.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_md4.h b/Utilities/cmcurl/lib/curl_md4.h index 13c7903..8c26d12 100644 --- a/Utilities/cmcurl/lib/curl_md4.h +++ b/Utilities/cmcurl/lib/curl_md4.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_md5.h b/Utilities/cmcurl/lib/curl_md5.h index 9c0e0b5..5f70c96 100644 --- a/Utilities/cmcurl/lib/curl_md5.h +++ b/Utilities/cmcurl/lib/curl_md5.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_memory.h b/Utilities/cmcurl/lib/curl_memory.h index bc744cc..6f792ff 100644 --- a/Utilities/cmcurl/lib/curl_memory.h +++ b/Utilities/cmcurl/lib/curl_memory.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -83,7 +83,20 @@ #ifndef CURLX_NO_MEMORY_CALLBACKS -#include <curl/curl.h> /* for the callback typedefs */ +#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* only if not already done */ +/* + * The following memory function replacement typedef's are COPIED from + * curl/curl.h and MUST match the originals. We copy them to avoid having to + * include curl/curl.h here. We avoid that include since it includes stdio.h + * and other headers that may get messed up with defines done here. + */ +typedef void *(*curl_malloc_callback)(size_t size); +typedef void (*curl_free_callback)(void *ptr); +typedef void *(*curl_realloc_callback)(void *ptr, size_t size); +typedef char *(*curl_strdup_callback)(const char *str); +typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); +#define CURL_DID_MEMORY_FUNC_TYPEDEFS +#endif extern curl_malloc_callback Curl_cmalloc; extern curl_free_callback Curl_cfree; diff --git a/Utilities/cmcurl/lib/curl_memrchr.c b/Utilities/cmcurl/lib/curl_memrchr.c index 6722c6a..c521497 100644 --- a/Utilities/cmcurl/lib/curl_memrchr.c +++ b/Utilities/cmcurl/lib/curl_memrchr.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -21,6 +21,9 @@ ***************************************************************************/ #include "curl_setup.h" + +#include <curl/curl.h> + #include "curl_memrchr.h" #include "curl_memory.h" diff --git a/Utilities/cmcurl/lib/curl_memrchr.h b/Utilities/cmcurl/lib/curl_memrchr.h index 324c73a..747509c 100644 --- a/Utilities/cmcurl/lib/curl_memrchr.h +++ b/Utilities/cmcurl/lib/curl_memrchr.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_multibyte.c b/Utilities/cmcurl/lib/curl_multibyte.c index 403d005..e78bb50 100644 --- a/Utilities/cmcurl/lib/curl_multibyte.c +++ b/Utilities/cmcurl/lib/curl_multibyte.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,6 +22,8 @@ #include "curl_setup.h" +#include <curl/curl.h> + #if defined(USE_WIN32_IDN) || ((defined(USE_WINDOWS_SSPI) || \ defined(USE_WIN32_LDAP)) && defined(UNICODE)) diff --git a/Utilities/cmcurl/lib/curl_multibyte.h b/Utilities/cmcurl/lib/curl_multibyte.h index dc7ed4c..615f5c0 100644 --- a/Utilities/cmcurl/lib/curl_multibyte.h +++ b/Utilities/cmcurl/lib/curl_multibyte.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_ntlm_core.c b/Utilities/cmcurl/lib/curl_ntlm_core.c index 2e5b573..f3fb013 100644 --- a/Utilities/cmcurl/lib/curl_ntlm_core.c +++ b/Utilities/cmcurl/lib/curl_ntlm_core.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,7 +28,7 @@ * NTLM details: * * http://davenport.sourceforge.net/ntlm.html - * http://www.innovation.ch/java/ntlm.html + * https://www.innovation.ch/java/ntlm.html */ #if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO) @@ -107,9 +107,8 @@ #include "warnless.h" #include "curl_endian.h" #include "curl_des.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -143,14 +142,10 @@ static void setup_des_key(const unsigned char *key_56, DES_cblock key; /* Expand the 56-bit key to 64-bits */ - extend_key_56_to_64(key_56, (char *) key); + extend_key_56_to_64(key_56, (char *) &key); /* Set the key parity to odd */ -#if defined(HAVE_BORINGSSL) - Curl_des_set_odd_parity((unsigned char *) &key, sizeof(key)); -#else DES_set_odd_parity(&key); -#endif /* Set the key */ DES_set_key(&key, ks); @@ -416,7 +411,7 @@ void Curl_ntlm_core_lm_resp(const unsigned char *keys, /* * Set up lanmanager hashed password */ -CURLcode Curl_ntlm_core_mk_lm_hash(struct SessionHandle *data, +CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data, const char *password, unsigned char *lmbuffer /* 21 bytes */) { @@ -510,7 +505,7 @@ static void ascii_uppercase_to_unicode_le(unsigned char *dest, * Set up nt hashed passwords * @unittest: 1600 */ -CURLcode Curl_ntlm_core_mk_nt_hash(struct SessionHandle *data, +CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data, const char *password, unsigned char *ntbuffer /* 21 bytes */) { @@ -664,21 +659,22 @@ CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash, unsigned int len = 0; unsigned char *ptr = NULL; unsigned char hmac_output[NTLM_HMAC_MD5_LEN]; -#if defined(HAVE_LONGLONG) - long long tw; -#else - __int64 tw; -#endif + curl_off_t tw; + CURLcode result = CURLE_OK; +#if CURL_SIZEOF_CURL_OFF_T < 8 +#error "this section needs 64bit support to work" +#endif + /* Calculate the timestamp */ #ifdef DEBUGBUILD char *force_timestamp = getenv("CURL_FORCETIME"); if(force_timestamp) - tw = 11644473600ULL * 10000000ULL; + tw = CURL_OFF_T_C(11644473600) * 10000000; else #endif - tw = ((long long)time(NULL) + 11644473600ULL) * 10000000ULL; + tw = ((curl_off_t)time(NULL) + CURL_OFF_T_C(11644473600)) * 10000000; /* Calculate the response len */ len = NTLM_HMAC_MD5_LEN + NTLMv2_BLOB_LEN; diff --git a/Utilities/cmcurl/lib/curl_ntlm_core.h b/Utilities/cmcurl/lib/curl_ntlm_core.h index 3a76359..c5f90e7 100644 --- a/Utilities/cmcurl/lib/curl_ntlm_core.h +++ b/Utilities/cmcurl/lib/curl_ntlm_core.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -64,12 +64,12 @@ void Curl_ntlm_core_lm_resp(const unsigned char *keys, const unsigned char *plaintext, unsigned char *results); -CURLcode Curl_ntlm_core_mk_lm_hash(struct SessionHandle *data, +CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data, const char *password, unsigned char *lmbuffer /* 21 bytes */); #if USE_NTRESPONSES -CURLcode Curl_ntlm_core_mk_nt_hash(struct SessionHandle *data, +CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data, const char *password, unsigned char *ntbuffer /* 21 bytes */); diff --git a/Utilities/cmcurl/lib/curl_ntlm_wb.c b/Utilities/cmcurl/lib/curl_ntlm_wb.c index b2a5fb3..afdea16 100644 --- a/Utilities/cmcurl/lib/curl_ntlm_wb.c +++ b/Utilities/cmcurl/lib/curl_ntlm_wb.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -29,7 +29,7 @@ * NTLM details: * * http://davenport.sourceforge.net/ntlm.html - * http://www.innovation.ch/java/ntlm.html + * https://www.innovation.ch/java/ntlm.html */ #define DEBUG_ME 0 @@ -47,13 +47,12 @@ #include "urldata.h" #include "sendf.h" #include "select.h" -#include "curl_ntlm_msgs.h" +#include "vauth/ntlm.h" #include "curl_ntlm_wb.h" #include "url.h" #include "strerror.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -373,8 +372,8 @@ CURLcode Curl_output_ntlm_wb(struct connectdata *conn, * by delegating the NTLM challenge/response protocal to a helper * in ntlm_auth. * http://devel.squid-cache.org/ntlm/squid_helper_protocol.html - * http://www.samba.org/samba/docs/man/manpages-3/winbindd.8.html - * http://www.samba.org/samba/docs/man/manpages-3/ntlm_auth.1.html + * https://www.samba.org/samba/docs/man/manpages-3/winbindd.8.html + * https://www.samba.org/samba/docs/man/manpages-3/ntlm_auth.1.html * Preprocessor symbol 'NTLM_WB_ENABLED' is defined when this * feature is enabled and 'NTLM_WB_FILE' symbol holds absolute * filename of ntlm_auth helper. diff --git a/Utilities/cmcurl/lib/curl_ntlm_wb.h b/Utilities/cmcurl/lib/curl_ntlm_wb.h index 828bb57..aba3d46 100644 --- a/Utilities/cmcurl/lib/curl_ntlm_wb.h +++ b/Utilities/cmcurl/lib/curl_ntlm_wb.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_printf.h b/Utilities/cmcurl/lib/curl_printf.h index 086923f..49857cd 100644 --- a/Utilities/cmcurl/lib/curl_printf.h +++ b/Utilities/cmcurl/lib/curl_printf.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_rtmp.c b/Utilities/cmcurl/lib/curl_rtmp.c index 2938972..06dd047 100644 --- a/Utilities/cmcurl/lib/curl_rtmp.c +++ b/Utilities/cmcurl/lib/curl_rtmp.c @@ -10,7 +10,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -55,7 +55,7 @@ static Curl_recv rtmp_recv; static Curl_send rtmp_send; /* - * RTMP protocol handler.h, based on http://rtmpdump.mplayerhq.hu + * RTMP protocol handler.h, based on https://rtmpdump.mplayerhq.hu */ const struct Curl_handler Curl_handler_rtmp = { diff --git a/Utilities/cmcurl/lib/curl_rtmp.h b/Utilities/cmcurl/lib/curl_rtmp.h index 4a9e9e6..3306e22 100644 --- a/Utilities/cmcurl/lib/curl_rtmp.h +++ b/Utilities/cmcurl/lib/curl_rtmp.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_sasl.c b/Utilities/cmcurl/lib/curl_sasl.c index 68646bc..35e9fea 100644 --- a/Utilities/cmcurl/lib/curl_sasl.c +++ b/Utilities/cmcurl/lib/curl_sasl.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,6 +24,7 @@ * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC6749 OAuth 2.0 Authorization Framework + * RFC7628 A Set of SASL Mechanisms for OAuth * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ @@ -35,6 +36,7 @@ #include "curl_base64.h" #include "curl_md5.h" +#include "vauth/vauth.h" #include "vtls/vtls.h" #include "curl_hmac.h" #include "curl_sasl.h" @@ -44,9 +46,8 @@ #include "rawstr.h" #include "sendf.h" #include "non-ascii.h" /* included for Curl_convert_... prototypes */ +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -56,1140 +57,18 @@ const struct { size_t len; /* Name length */ unsigned int bit; /* Flag bit */ } mechtable[] = { - { "LOGIN", 5, SASL_MECH_LOGIN }, - { "PLAIN", 5, SASL_MECH_PLAIN }, - { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, - { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, - { "GSSAPI", 6, SASL_MECH_GSSAPI }, - { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, - { "NTLM", 4, SASL_MECH_NTLM }, - { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, - { ZERO_NULL, 0, 0 } + { "LOGIN", 5, SASL_MECH_LOGIN }, + { "PLAIN", 5, SASL_MECH_PLAIN }, + { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, + { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, + { "GSSAPI", 6, SASL_MECH_GSSAPI }, + { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, + { "NTLM", 4, SASL_MECH_NTLM }, + { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, + { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, + { ZERO_NULL, 0, 0 } }; -#if !defined(CURL_DISABLE_CRYPTO_AUTH) && !defined(USE_WINDOWS_SSPI) -#define DIGEST_QOP_VALUE_AUTH (1 << 0) -#define DIGEST_QOP_VALUE_AUTH_INT (1 << 1) -#define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2) - -#define DIGEST_QOP_VALUE_STRING_AUTH "auth" -#define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int" -#define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf" - -/* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines. - It converts digest text to ASCII so the MD5 will be correct for - what ultimately goes over the network. -*/ -#define CURL_OUTPUT_DIGEST_CONV(a, b) \ - result = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \ - if(result) { \ - free(b); \ - return result; \ - } - -#endif - -#if !defined(CURL_DISABLE_CRYPTO_AUTH) -/* - * Returns 0 on success and then the buffers are filled in fine. - * - * Non-zero means failure to parse. - */ -int Curl_sasl_digest_get_pair(const char *str, char *value, char *content, - const char **endptr) -{ - int c; - bool starts_with_quote = FALSE; - bool escape = FALSE; - - for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--); ) - *value++ = *str++; - *value = 0; - - if('=' != *str++) - /* eek, no match */ - return 1; - - if('\"' == *str) { - /* this starts with a quote so it must end with one as well! */ - str++; - starts_with_quote = TRUE; - } - - for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) { - switch(*str) { - case '\\': - if(!escape) { - /* possibly the start of an escaped quote */ - escape = TRUE; - *content++ = '\\'; /* even though this is an escape character, we still - store it as-is in the target buffer */ - continue; - } - break; - case ',': - if(!starts_with_quote) { - /* this signals the end of the content if we didn't get a starting - quote and then we do "sloppy" parsing */ - c = 0; /* the end */ - continue; - } - break; - case '\r': - case '\n': - /* end of string */ - c = 0; - continue; - case '\"': - if(!escape && starts_with_quote) { - /* end of string */ - c = 0; - continue; - } - break; - } - escape = FALSE; - *content++ = *str; - } - *content = 0; - - *endptr = str; - - return 0; /* all is fine! */ -} -#endif - -#if !defined(CURL_DISABLE_CRYPTO_AUTH) && !defined(USE_WINDOWS_SSPI) -/* Convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/ -static void sasl_digest_md5_to_ascii(unsigned char *source, /* 16 bytes */ - unsigned char *dest) /* 33 bytes */ -{ - int i; - for(i = 0; i < 16; i++) - snprintf((char *)&dest[i*2], 3, "%02x", source[i]); -} - -/* Perform quoted-string escaping as described in RFC2616 and its errata */ -static char *sasl_digest_string_quoted(const char *source) -{ - char *dest, *d; - const char *s = source; - size_t n = 1; /* null terminator */ - - /* Calculate size needed */ - while(*s) { - ++n; - if(*s == '"' || *s == '\\') { - ++n; - } - ++s; - } - - dest = malloc(n); - if(dest) { - s = source; - d = dest; - while(*s) { - if(*s == '"' || *s == '\\') { - *d++ = '\\'; - } - *d++ = *s++; - } - *d = 0; - } - - return dest; -} - -/* Retrieves the value for a corresponding key from the challenge string - * returns TRUE if the key could be found, FALSE if it does not exists - */ -static bool sasl_digest_get_key_value(const char *chlg, - const char *key, - char *value, - size_t max_val_len, - char end_char) -{ - char *find_pos; - size_t i; - - find_pos = strstr(chlg, key); - if(!find_pos) - return FALSE; - - find_pos += strlen(key); - - for(i = 0; *find_pos && *find_pos != end_char && i < max_val_len - 1; ++i) - value[i] = *find_pos++; - value[i] = '\0'; - - return TRUE; -} - -static CURLcode sasl_digest_get_qop_values(const char *options, int *value) -{ - char *tmp; - char *token; - char *tok_buf; - - /* Initialise the output */ - *value = 0; - - /* Tokenise the list of qop values. Use a temporary clone of the buffer since - strtok_r() ruins it. */ - tmp = strdup(options); - if(!tmp) - return CURLE_OUT_OF_MEMORY; - - token = strtok_r(tmp, ",", &tok_buf); - while(token != NULL) { - if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH)) - *value |= DIGEST_QOP_VALUE_AUTH; - else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) - *value |= DIGEST_QOP_VALUE_AUTH_INT; - else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF)) - *value |= DIGEST_QOP_VALUE_AUTH_CONF; - - token = strtok_r(NULL, ",", &tok_buf); - } - - free(tmp); - - return CURLE_OK; -} -#endif /* !CURL_DISABLE_CRYPTO_AUTH && !USE_WINDOWS_SSPI */ - -#if !defined(USE_WINDOWS_SSPI) -/* - * Curl_sasl_build_spn() - * - * This is used to build a SPN string in the format service/host. - * - * Parameters: - * - * service [in] - The service type such as www, smtp, pop or imap. - * host [in] - The host name or realm. - * - * Returns a pointer to the newly allocated SPN. - */ -char *Curl_sasl_build_spn(const char *service, const char *host) -{ - /* Generate and return our SPN */ - return aprintf("%s/%s", service, host); -} -#endif - -/* - * sasl_create_plain_message() - * - * This is used to generate an already encoded PLAIN message ready - * for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * userp [in] - The user name. - * passdwp [in] - The user's password. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_create_plain_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - char **outptr, size_t *outlen) -{ - CURLcode result; - char *plainauth; - size_t ulen; - size_t plen; - - ulen = strlen(userp); - plen = strlen(passwdp); - - plainauth = malloc(2 * ulen + plen + 2); - if(!plainauth) { - *outlen = 0; - *outptr = NULL; - return CURLE_OUT_OF_MEMORY; - } - - /* Calculate the reply */ - memcpy(plainauth, userp, ulen); - plainauth[ulen] = '\0'; - memcpy(plainauth + ulen + 1, userp, ulen); - plainauth[2 * ulen + 1] = '\0'; - memcpy(plainauth + 2 * ulen + 2, passwdp, plen); - - /* Base64 encode the reply */ - result = Curl_base64_encode(data, plainauth, 2 * ulen + plen + 2, outptr, - outlen); - free(plainauth); - return result; -} - -/* - * sasl_create_login_message() - * - * This is used to generate an already encoded LOGIN message containing the - * user name or password ready for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * valuep [in] - The user name or user's password. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_create_login_message(struct SessionHandle *data, - const char *valuep, char **outptr, - size_t *outlen) -{ - size_t vlen = strlen(valuep); - - if(!vlen) { - /* Calculate an empty reply */ - *outptr = strdup("="); - if(*outptr) { - *outlen = (size_t) 1; - return CURLE_OK; - } - - *outlen = 0; - return CURLE_OUT_OF_MEMORY; - } - - /* Base64 encode the value */ - return Curl_base64_encode(data, valuep, vlen, outptr, outlen); -} - -/* - * sasl_create_external_message() - * - * This is used to generate an already encoded EXTERNAL message containing - * the user name ready for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * user [in] - The user name. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_create_external_message(struct SessionHandle *data, - const char *user, char **outptr, - size_t *outlen) -{ - /* This is the same formatting as the login message. */ - return sasl_create_login_message(data, user, outptr, outlen); -} - -#ifndef CURL_DISABLE_CRYPTO_AUTH - /* - * sasl_decode_cram_md5_message() - * - * This is used to decode an already encoded CRAM-MD5 challenge message. - * - * Parameters: - * - * chlg64 [in] - The base64 encoded challenge message. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_decode_cram_md5_message(const char *chlg64, char **outptr, - size_t *outlen) -{ - CURLcode result = CURLE_OK; - size_t chlg64len = strlen(chlg64); - - *outptr = NULL; - *outlen = 0; - - /* Decode the challenge if necessary */ - if(chlg64len && *chlg64 != '=') - result = Curl_base64_decode(chlg64, (unsigned char **) outptr, outlen); - - return result; - } - - /* - * sasl_create_cram_md5_message() - * - * This is used to generate an already encoded CRAM-MD5 response message ready - * for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * chlg [in] - The challenge. - * userp [in] - The user name. - * passdwp [in] - The user's password. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_create_cram_md5_message(struct SessionHandle *data, - const char *chlg, - const char *userp, - const char *passwdp, - char **outptr, size_t *outlen) -{ - CURLcode result = CURLE_OK; - size_t chlglen = 0; - HMAC_context *ctxt; - unsigned char digest[MD5_DIGEST_LEN]; - char *response; - - if(chlg) - chlglen = strlen(chlg); - - /* Compute the digest using the password as the key */ - ctxt = Curl_HMAC_init(Curl_HMAC_MD5, - (const unsigned char *) passwdp, - curlx_uztoui(strlen(passwdp))); - if(!ctxt) - return CURLE_OUT_OF_MEMORY; - - /* Update the digest with the given challenge */ - if(chlglen > 0) - Curl_HMAC_update(ctxt, (const unsigned char *) chlg, - curlx_uztoui(chlglen)); - - /* Finalise the digest */ - Curl_HMAC_final(ctxt, digest); - - /* Generate the response */ - response = aprintf( - "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - userp, digest[0], digest[1], digest[2], digest[3], digest[4], - digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], - digest[11], digest[12], digest[13], digest[14], digest[15]); - if(!response) - return CURLE_OUT_OF_MEMORY; - - /* Base64 encode the response */ - result = Curl_base64_encode(data, response, 0, outptr, outlen); - - free(response); - - return result; -} - -#ifndef USE_WINDOWS_SSPI -/* - * sasl_decode_digest_md5_message() - * - * This is used internally to decode an already encoded DIGEST-MD5 challenge - * message into the seperate attributes. - * - * Parameters: - * - * chlg64 [in] - The base64 encoded challenge message. - * nonce [in/out] - The buffer where the nonce will be stored. - * nlen [in] - The length of the nonce buffer. - * realm [in/out] - The buffer where the realm will be stored. - * rlen [in] - The length of the realm buffer. - * alg [in/out] - The buffer where the algorithm will be stored. - * alen [in] - The length of the algorithm buffer. - * qop [in/out] - The buffer where the qop-options will be stored. - * qlen [in] - The length of the qop buffer. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_decode_digest_md5_message(const char *chlg64, - char *nonce, size_t nlen, - char *realm, size_t rlen, - char *alg, size_t alen, - char *qop, size_t qlen) -{ - CURLcode result = CURLE_OK; - unsigned char *chlg = NULL; - size_t chlglen = 0; - size_t chlg64len = strlen(chlg64); - - /* Decode the base-64 encoded challenge message */ - if(chlg64len && *chlg64 != '=') { - result = Curl_base64_decode(chlg64, &chlg, &chlglen); - if(result) - return result; - } - - /* Ensure we have a valid challenge message */ - if(!chlg) - return CURLE_BAD_CONTENT_ENCODING; - - /* Retrieve nonce string from the challenge */ - if(!sasl_digest_get_key_value((char *)chlg, "nonce=\"", nonce, nlen, '\"')) { - free(chlg); - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Retrieve realm string from the challenge */ - if(!sasl_digest_get_key_value((char *)chlg, "realm=\"", realm, rlen, '\"')) { - /* Challenge does not have a realm, set empty string [RFC2831] page 6 */ - strcpy(realm, ""); - } - - /* Retrieve algorithm string from the challenge */ - if(!sasl_digest_get_key_value((char *)chlg, "algorithm=", alg, alen, ',')) { - free(chlg); - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Retrieve qop-options string from the challenge */ - if(!sasl_digest_get_key_value((char *)chlg, "qop=\"", qop, qlen, '\"')) { - free(chlg); - return CURLE_BAD_CONTENT_ENCODING; - } - - free(chlg); - - return CURLE_OK; -} - -/* - * Curl_sasl_create_digest_md5_message() - * - * This is used to generate an already encoded DIGEST-MD5 response message - * ready for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * chlg64 [in] - The base64 encoded challenge message. - * userp [in] - The user name. - * passdwp [in] - The user's password. - * service [in] - The service type such as www, smtp, pop or imap. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_create_digest_md5_message(struct SessionHandle *data, - const char *chlg64, - const char *userp, - const char *passwdp, - const char *service, - char **outptr, size_t *outlen) -{ - CURLcode result = CURLE_OK; - size_t i; - MD5_context *ctxt; - char *response = NULL; - unsigned char digest[MD5_DIGEST_LEN]; - char HA1_hex[2 * MD5_DIGEST_LEN + 1]; - char HA2_hex[2 * MD5_DIGEST_LEN + 1]; - char resp_hash_hex[2 * MD5_DIGEST_LEN + 1]; - char nonce[64]; - char realm[128]; - char algorithm[64]; - char qop_options[64]; - int qop_values; - char cnonce[33]; - unsigned int entropy[4]; - char nonceCount[] = "00000001"; - char method[] = "AUTHENTICATE"; - char qop[] = DIGEST_QOP_VALUE_STRING_AUTH; - char *spn = NULL; - - /* Decode the challange message */ - result = sasl_decode_digest_md5_message(chlg64, nonce, sizeof(nonce), - realm, sizeof(realm), - algorithm, sizeof(algorithm), - qop_options, sizeof(qop_options)); - if(result) - return result; - - /* We only support md5 sessions */ - if(strcmp(algorithm, "md5-sess") != 0) - return CURLE_BAD_CONTENT_ENCODING; - - /* Get the qop-values from the qop-options */ - result = sasl_digest_get_qop_values(qop_options, &qop_values); - if(result) - return result; - - /* We only support auth quality-of-protection */ - if(!(qop_values & DIGEST_QOP_VALUE_AUTH)) - return CURLE_BAD_CONTENT_ENCODING; - - /* Generate 16 bytes of random data */ - entropy[0] = Curl_rand(data); - entropy[1] = Curl_rand(data); - entropy[2] = Curl_rand(data); - entropy[3] = Curl_rand(data); - - /* Convert the random data into a 32 byte hex string */ - snprintf(cnonce, sizeof(cnonce), "%08x%08x%08x%08x", - entropy[0], entropy[1], entropy[2], entropy[3]); - - /* So far so good, now calculate A1 and H(A1) according to RFC 2831 */ - ctxt = Curl_MD5_init(Curl_DIGEST_MD5); - if(!ctxt) - return CURLE_OUT_OF_MEMORY; - - Curl_MD5_update(ctxt, (const unsigned char *) userp, - curlx_uztoui(strlen(userp))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) realm, - curlx_uztoui(strlen(realm))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) passwdp, - curlx_uztoui(strlen(passwdp))); - Curl_MD5_final(ctxt, digest); - - ctxt = Curl_MD5_init(Curl_DIGEST_MD5); - if(!ctxt) - return CURLE_OUT_OF_MEMORY; - - Curl_MD5_update(ctxt, (const unsigned char *) digest, MD5_DIGEST_LEN); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) nonce, - curlx_uztoui(strlen(nonce))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) cnonce, - curlx_uztoui(strlen(cnonce))); - Curl_MD5_final(ctxt, digest); - - /* Convert calculated 16 octet hex into 32 bytes string */ - for(i = 0; i < MD5_DIGEST_LEN; i++) - snprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]); - - /* Generate our SPN */ - spn = Curl_sasl_build_spn(service, realm); - if(!spn) - return CURLE_OUT_OF_MEMORY; - - /* Calculate H(A2) */ - ctxt = Curl_MD5_init(Curl_DIGEST_MD5); - if(!ctxt) { - free(spn); - - return CURLE_OUT_OF_MEMORY; - } - - Curl_MD5_update(ctxt, (const unsigned char *) method, - curlx_uztoui(strlen(method))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) spn, - curlx_uztoui(strlen(spn))); - Curl_MD5_final(ctxt, digest); - - for(i = 0; i < MD5_DIGEST_LEN; i++) - snprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]); - - /* Now calculate the response hash */ - ctxt = Curl_MD5_init(Curl_DIGEST_MD5); - if(!ctxt) { - free(spn); - - return CURLE_OUT_OF_MEMORY; - } - - Curl_MD5_update(ctxt, (const unsigned char *) HA1_hex, 2 * MD5_DIGEST_LEN); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) nonce, - curlx_uztoui(strlen(nonce))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - - Curl_MD5_update(ctxt, (const unsigned char *) nonceCount, - curlx_uztoui(strlen(nonceCount))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) cnonce, - curlx_uztoui(strlen(cnonce))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - Curl_MD5_update(ctxt, (const unsigned char *) qop, - curlx_uztoui(strlen(qop))); - Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); - - Curl_MD5_update(ctxt, (const unsigned char *) HA2_hex, 2 * MD5_DIGEST_LEN); - Curl_MD5_final(ctxt, digest); - - for(i = 0; i < MD5_DIGEST_LEN; i++) - snprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]); - - /* Generate the response */ - response = aprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\"," - "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\",response=%s," - "qop=%s", - userp, realm, nonce, - cnonce, nonceCount, spn, resp_hash_hex, qop); - free(spn); - if(!response) - return CURLE_OUT_OF_MEMORY; - - /* Base64 encode the response */ - result = Curl_base64_encode(data, response, 0, outptr, outlen); - - free(response); - - return result; -} - -/* - * Curl_sasl_decode_digest_http_message() - * - * This is used to decode a HTTP DIGEST challenge message into the seperate - * attributes. - * - * Parameters: - * - * chlg [in] - The challenge message. - * digest [in/out] - The digest data struct being used and modified. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_decode_digest_http_message(const char *chlg, - struct digestdata *digest) -{ - bool before = FALSE; /* got a nonce before */ - bool foundAuth = FALSE; - bool foundAuthInt = FALSE; - char *token = NULL; - char *tmp = NULL; - - /* If we already have received a nonce, keep that in mind */ - if(digest->nonce) - before = TRUE; - - /* Clean up any former leftovers and initialise to defaults */ - Curl_sasl_digest_cleanup(digest); - - for(;;) { - char value[DIGEST_MAX_VALUE_LENGTH]; - char content[DIGEST_MAX_CONTENT_LENGTH]; - - /* Pass all additional spaces here */ - while(*chlg && ISSPACE(*chlg)) - chlg++; - - /* Extract a value=content pair */ - if(!Curl_sasl_digest_get_pair(chlg, value, content, &chlg)) { - if(Curl_raw_equal(value, "nonce")) { - digest->nonce = strdup(content); - if(!digest->nonce) - return CURLE_OUT_OF_MEMORY; - } - else if(Curl_raw_equal(value, "stale")) { - if(Curl_raw_equal(content, "true")) { - digest->stale = TRUE; - digest->nc = 1; /* we make a new nonce now */ - } - } - else if(Curl_raw_equal(value, "realm")) { - digest->realm = strdup(content); - if(!digest->realm) - return CURLE_OUT_OF_MEMORY; - } - else if(Curl_raw_equal(value, "opaque")) { - digest->opaque = strdup(content); - if(!digest->opaque) - return CURLE_OUT_OF_MEMORY; - } - else if(Curl_raw_equal(value, "qop")) { - char *tok_buf; - /* Tokenize the list and choose auth if possible, use a temporary - clone of the buffer since strtok_r() ruins it */ - tmp = strdup(content); - if(!tmp) - return CURLE_OUT_OF_MEMORY; - - token = strtok_r(tmp, ",", &tok_buf); - while(token != NULL) { - if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH)) { - foundAuth = TRUE; - } - else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) { - foundAuthInt = TRUE; - } - token = strtok_r(NULL, ",", &tok_buf); - } - - free(tmp); - - /* Select only auth or auth-int. Otherwise, ignore */ - if(foundAuth) { - digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH); - if(!digest->qop) - return CURLE_OUT_OF_MEMORY; - } - else if(foundAuthInt) { - digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT); - if(!digest->qop) - return CURLE_OUT_OF_MEMORY; - } - } - else if(Curl_raw_equal(value, "algorithm")) { - digest->algorithm = strdup(content); - if(!digest->algorithm) - return CURLE_OUT_OF_MEMORY; - - if(Curl_raw_equal(content, "MD5-sess")) - digest->algo = CURLDIGESTALGO_MD5SESS; - else if(Curl_raw_equal(content, "MD5")) - digest->algo = CURLDIGESTALGO_MD5; - else - return CURLE_BAD_CONTENT_ENCODING; - } - else { - /* unknown specifier, ignore it! */ - } - } - else - break; /* we're done here */ - - /* Pass all additional spaces here */ - while(*chlg && ISSPACE(*chlg)) - chlg++; - - /* Allow the list to be comma-separated */ - if(',' == *chlg) - chlg++; - } - - /* We had a nonce since before, and we got another one now without - 'stale=true'. This means we provided bad credentials in the previous - request */ - if(before && !digest->stale) - return CURLE_BAD_CONTENT_ENCODING; - - /* We got this header without a nonce, that's a bad Digest line! */ - if(!digest->nonce) - return CURLE_BAD_CONTENT_ENCODING; - - return CURLE_OK; -} - -/* - * Curl_sasl_create_digest_http_message() - * - * This is used to generate a HTTP DIGEST response message ready for sending - * to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * userp [in] - The user name. - * passdwp [in] - The user's password. - * request [in] - The HTTP request. - * uripath [in] - The path of the HTTP uri. - * digest [in/out] - The digest data struct being used and modified. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_create_digest_http_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - const unsigned char *request, - const unsigned char *uripath, - struct digestdata *digest, - char **outptr, size_t *outlen) -{ - CURLcode result; - unsigned char md5buf[16]; /* 16 bytes/128 bits */ - unsigned char request_digest[33]; - unsigned char *md5this; - unsigned char ha1[33];/* 32 digits and 1 zero byte */ - unsigned char ha2[33];/* 32 digits and 1 zero byte */ - char cnoncebuf[33]; - char *cnonce = NULL; - size_t cnonce_sz = 0; - char *userp_quoted; - char *response = NULL; - char *tmp = NULL; - - if(!digest->nc) - digest->nc = 1; - - if(!digest->cnonce) { - snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x", - Curl_rand(data), Curl_rand(data), - Curl_rand(data), Curl_rand(data)); - - result = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf), - &cnonce, &cnonce_sz); - if(result) - return result; - - digest->cnonce = cnonce; - } - - /* - if the algorithm is "MD5" or unspecified (which then defaults to MD5): - - A1 = unq(username-value) ":" unq(realm-value) ":" passwd - - if the algorithm is "MD5-sess" then: - - A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd ) - ":" unq(nonce-value) ":" unq(cnonce-value) - */ - - md5this = (unsigned char *) - aprintf("%s:%s:%s", userp, digest->realm, passwdp); - if(!md5this) - return CURLE_OUT_OF_MEMORY; - - CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ - Curl_md5it(md5buf, md5this); - free(md5this); - sasl_digest_md5_to_ascii(md5buf, ha1); - - if(digest->algo == CURLDIGESTALGO_MD5SESS) { - /* nonce and cnonce are OUTSIDE the hash */ - tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce); - if(!tmp) - return CURLE_OUT_OF_MEMORY; - - CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */ - Curl_md5it(md5buf, (unsigned char *)tmp); - free(tmp); - sasl_digest_md5_to_ascii(md5buf, ha1); - } - - /* - If the "qop" directive's value is "auth" or is unspecified, then A2 is: - - A2 = Method ":" digest-uri-value - - If the "qop" value is "auth-int", then A2 is: - - A2 = Method ":" digest-uri-value ":" H(entity-body) - - (The "Method" value is the HTTP request method as specified in section - 5.1.1 of RFC 2616) - */ - - md5this = (unsigned char *)aprintf("%s:%s", request, uripath); - - if(digest->qop && Curl_raw_equal(digest->qop, "auth-int")) { - /* We don't support auth-int for PUT or POST at the moment. - TODO: replace md5 of empty string with entity-body for PUT/POST */ - unsigned char *md5this2 = (unsigned char *) - aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e"); - free(md5this); - md5this = md5this2; - } - - if(!md5this) - return CURLE_OUT_OF_MEMORY; - - CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ - Curl_md5it(md5buf, md5this); - free(md5this); - sasl_digest_md5_to_ascii(md5buf, ha2); - - if(digest->qop) { - md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s", - ha1, - digest->nonce, - digest->nc, - digest->cnonce, - digest->qop, - ha2); - } - else { - md5this = (unsigned char *)aprintf("%s:%s:%s", - ha1, - digest->nonce, - ha2); - } - - if(!md5this) - return CURLE_OUT_OF_MEMORY; - - CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ - Curl_md5it(md5buf, md5this); - free(md5this); - sasl_digest_md5_to_ascii(md5buf, request_digest); - - /* for test case 64 (snooped from a Mozilla 1.3a request) - - Authorization: Digest username="testuser", realm="testrealm", \ - nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" - - Digest parameters are all quoted strings. Username which is provided by - the user will need double quotes and backslashes within it escaped. For - the other fields, this shouldn't be an issue. realm, nonce, and opaque - are copied as is from the server, escapes and all. cnonce is generated - with web-safe characters. uri is already percent encoded. nc is 8 hex - characters. algorithm and qop with standard values only contain web-safe - chracters. - */ - userp_quoted = sasl_digest_string_quoted(userp); - if(!userp_quoted) - return CURLE_OUT_OF_MEMORY; - - if(digest->qop) { - response = aprintf("username=\"%s\", " - "realm=\"%s\", " - "nonce=\"%s\", " - "uri=\"%s\", " - "cnonce=\"%s\", " - "nc=%08x, " - "qop=%s, " - "response=\"%s\"", - userp_quoted, - digest->realm, - digest->nonce, - uripath, - digest->cnonce, - digest->nc, - digest->qop, - request_digest); - - if(Curl_raw_equal(digest->qop, "auth")) - digest->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 - padded which tells to the server how many times you are - using the same nonce in the qop=auth mode */ - } - else { - response = aprintf("username=\"%s\", " - "realm=\"%s\", " - "nonce=\"%s\", " - "uri=\"%s\", " - "response=\"%s\"", - userp_quoted, - digest->realm, - digest->nonce, - uripath, - request_digest); - } - free(userp_quoted); - if(!response) - return CURLE_OUT_OF_MEMORY; - - /* Add the optional fields */ - if(digest->opaque) { - /* Append the opaque */ - tmp = aprintf("%s, opaque=\"%s\"", response, digest->opaque); - free(response); - if(!tmp) - return CURLE_OUT_OF_MEMORY; - - response = tmp; - } - - if(digest->algorithm) { - /* Append the algorithm */ - tmp = aprintf("%s, algorithm=\"%s\"", response, digest->algorithm); - free(response); - if(!tmp) - return CURLE_OUT_OF_MEMORY; - - response = tmp; - } - - /* Return the output */ - *outptr = response; - *outlen = strlen(response); - - return CURLE_OK; -} - -/* - * Curl_sasl_digest_cleanup() - * - * This is used to clean up the digest specific data. - * - * Parameters: - * - * digest [in/out] - The digest data struct being cleaned up. - * - */ -void Curl_sasl_digest_cleanup(struct digestdata *digest) -{ - Curl_safefree(digest->nonce); - Curl_safefree(digest->cnonce); - Curl_safefree(digest->realm); - Curl_safefree(digest->opaque); - Curl_safefree(digest->qop); - Curl_safefree(digest->algorithm); - - digest->nc = 0; - digest->algo = CURLDIGESTALGO_MD5; /* default algorithm */ - digest->stale = FALSE; /* default means normal, not stale */ -} -#endif /* !USE_WINDOWS_SSPI */ - -#endif /* CURL_DISABLE_CRYPTO_AUTH */ - -#if defined(USE_NTLM) && !defined(USE_WINDOWS_SSPI) -/* - * Curl_sasl_ntlm_cleanup() - * - * This is used to clean up the ntlm specific data. - * - * Parameters: - * - * ntlm [in/out] - The ntlm data struct being cleaned up. - * - */ -void Curl_sasl_ntlm_cleanup(struct ntlmdata *ntlm) -{ - /* Free the target info */ - Curl_safefree(ntlm->target_info); - - /* Reset any variables */ - ntlm->target_info_len = 0; -} -#endif /* USE_NTLM && !USE_WINDOWS_SSPI*/ - -/* - * sasl_create_xoauth2_message() - * - * This is used to generate an already encoded OAuth 2.0 message ready for - * sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * user [in] - The user name. - * bearer [in] - The bearer token. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -static CURLcode sasl_create_xoauth2_message(struct SessionHandle *data, - const char *user, - const char *bearer, - char **outptr, size_t *outlen) -{ - CURLcode result = CURLE_OK; - char *xoauth = NULL; - - /* Generate the message */ - xoauth = aprintf("user=%s\1auth=Bearer %s\1\1", user, bearer); - if(!xoauth) - return CURLE_OUT_OF_MEMORY; - - /* Base64 encode the reply */ - result = Curl_base64_encode(data, xoauth, strlen(xoauth), outptr, outlen); - - free(xoauth); - - return result; -} - /* * Curl_sasl_cleanup() * @@ -1206,14 +85,14 @@ void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused) #if defined(USE_KERBEROS5) /* Cleanup the gssapi structure */ if(authused == SASL_MECH_GSSAPI) { - Curl_sasl_gssapi_cleanup(&conn->krb5); + Curl_auth_gssapi_cleanup(&conn->krb5); } #endif #if defined(USE_NTLM) - /* Cleanup the ntlm structure */ + /* Cleanup the NTLM structure */ if(authused == SASL_MECH_NTLM) { - Curl_sasl_ntlm_cleanup(&conn->ntlm); + Curl_auth_ntlm_cleanup(&conn->ntlm); } #endif @@ -1275,18 +154,20 @@ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, if(!len) return CURLE_URL_MALFORMAT; - if(sasl->resetprefs) { - sasl->resetprefs = FALSE; - sasl->prefmech = SASL_AUTH_NONE; - } + if(sasl->resetprefs) { + sasl->resetprefs = FALSE; + sasl->prefmech = SASL_AUTH_NONE; + } - if(strnequal(value, "*", len)) - sasl->prefmech = SASL_AUTH_DEFAULT; - else if((mechbit = Curl_sasl_decode_mech(value, len, &mechlen)) && - mechlen == len) + if(strnequal(value, "*", len)) + sasl->prefmech = SASL_AUTH_DEFAULT; + else { + mechbit = Curl_sasl_decode_mech(value, len, &mechlen); + if(mechbit && mechlen == len) sasl->prefmech |= mechbit; else result = CURLE_URL_MALFORMAT; + } return result; } @@ -1332,7 +213,8 @@ static void state(struct SASL *sasl, struct connectdata *conn, "GSSAPI", "GSSAPI_TOKEN", "GSSAPI_NO_DATA", - "XOAUTH2", + "OAUTH2", + "OAUTH2_RESP", "CANCEL", "FINAL", /* LAST */ @@ -1375,13 +257,18 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, bool force_ir, saslprogress *progress) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; unsigned int enabledmechs; const char *mech = NULL; char *resp = NULL; size_t len = 0; saslstate state1 = SASL_STOP; saslstate state2 = SASL_FINAL; +#if defined(USE_KERBEROS5) + const char* service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + sasl->params->service; +#endif sasl->force_ir = force_ir; /* Latch for future use */ sasl->authused = 0; /* No mechanism used yet */ @@ -1396,7 +283,8 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, sasl->authused = SASL_MECH_EXTERNAL; if(force_ir || data->set.sasl_ir) - result = sasl_create_external_message(data, conn->user, &resp, &len); + result = Curl_auth_create_external_message(data, conn->user, &resp, + &len); } else if(conn->bits.user_passwd) { #if defined(USE_KERBEROS5) @@ -1408,9 +296,11 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, sasl->authused = SASL_MECH_GSSAPI; if(force_ir || data->set.sasl_ir) - result = Curl_sasl_create_gssapi_user_message(data, conn->user, + result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, - sasl->params->service, + service, + data->easy_conn-> + host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp, &len); @@ -1438,20 +328,34 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, sasl->authused = SASL_MECH_NTLM; if(force_ir || data->set.sasl_ir) - result = Curl_sasl_create_ntlm_type1_message(conn->user, conn->passwd, + result = Curl_auth_create_ntlm_type1_message(conn->user, conn->passwd, &conn->ntlm, &resp, &len); } else #endif - if((enabledmechs & SASL_MECH_XOAUTH2) || conn->xoauth2_bearer) { + if((enabledmechs & SASL_MECH_OAUTHBEARER) && conn->oauth_bearer) { + mech = SASL_MECH_STRING_OAUTHBEARER; + state1 = SASL_OAUTH2; + state2 = SASL_OAUTH2_RESP; + sasl->authused = SASL_MECH_OAUTHBEARER; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_oauth_bearer_message(data, conn->user, + conn->host.name, + conn->port, + conn->oauth_bearer, + &resp, &len); + } + else if((enabledmechs & SASL_MECH_XOAUTH2) && conn->oauth_bearer) { mech = SASL_MECH_STRING_XOAUTH2; - state1 = SASL_XOAUTH2; + state1 = SASL_OAUTH2; sasl->authused = SASL_MECH_XOAUTH2; if(force_ir || data->set.sasl_ir) - result = sasl_create_xoauth2_message(data, conn->user, - conn->xoauth2_bearer, - &resp, &len); + result = Curl_auth_create_oauth_bearer_message(data, conn->user, + NULL, 0, + conn->oauth_bearer, + &resp, &len); } else if(enabledmechs & SASL_MECH_LOGIN) { mech = SASL_MECH_STRING_LOGIN; @@ -1460,7 +364,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, sasl->authused = SASL_MECH_LOGIN; if(force_ir || data->set.sasl_ir) - result = sasl_create_login_message(data, conn->user, &resp, &len); + result = Curl_auth_create_login_message(data, conn->user, &resp, &len); } else if(enabledmechs & SASL_MECH_PLAIN) { mech = SASL_MECH_STRING_PLAIN; @@ -1468,24 +372,22 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, sasl->authused = SASL_MECH_PLAIN; if(force_ir || data->set.sasl_ir) - result = sasl_create_plain_message(data, conn->user, conn->passwd, - &resp, &len); + result = Curl_auth_create_plain_message(data, conn->user, conn->passwd, + &resp, &len); } } - if(!result) { + if(!result && mech) { if(resp && sasl->params->maxirlen && strlen(mech) + len > sasl->params->maxirlen) { free(resp); resp = NULL; } - if(mech) { - result = sasl->params->sendauth(conn, mech, resp); - if(!result) { - *progress = SASL_INPROGRESS; - state(sasl, conn, resp? state2: state1); - } + result = sasl->params->sendauth(conn, mech, resp); + if(!result) { + *progress = SASL_INPROGRESS; + state(sasl, conn, resp ? state2 : state1); } } @@ -1503,7 +405,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, int code, saslprogress *progress) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; saslstate newstate = SASL_FINAL; char *resp = NULL; #if !defined(CURL_DISABLE_CRYPTO_AUTH) @@ -1511,6 +413,11 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, char *chlg = NULL; size_t chlglen = 0; #endif +#if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + sasl->params->service; +#endif size_t len = 0; *progress = SASL_INPROGRESS; @@ -1523,7 +430,8 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, return result; } - if(sasl->state != SASL_CANCEL && code != sasl->params->contcode) { + if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && + code != sasl->params->contcode) { *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return CURLE_LOGIN_DENIED; @@ -1534,39 +442,41 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, *progress = SASL_DONE; return result; case SASL_PLAIN: - result = sasl_create_plain_message(data, conn->user, conn->passwd, &resp, - &len); + result = Curl_auth_create_plain_message(data, conn->user, conn->passwd, + &resp, + &len); break; case SASL_LOGIN: - result = sasl_create_login_message(data, conn->user, &resp, &len); + result = Curl_auth_create_login_message(data, conn->user, &resp, &len); newstate = SASL_LOGIN_PASSWD; break; case SASL_LOGIN_PASSWD: - result = sasl_create_login_message(data, conn->passwd, &resp, &len); + result = Curl_auth_create_login_message(data, conn->passwd, &resp, &len); break; case SASL_EXTERNAL: - result = sasl_create_external_message(data, conn->user, &resp, &len); + result = Curl_auth_create_external_message(data, conn->user, &resp, &len); break; #ifndef CURL_DISABLE_CRYPTO_AUTH case SASL_CRAMMD5: sasl->params->getmessage(data->state.buffer, &serverdata); - result = sasl_decode_cram_md5_message(serverdata, &chlg, &chlglen); + result = Curl_auth_decode_cram_md5_message(serverdata, &chlg, &chlglen); if(!result) - result = sasl_create_cram_md5_message(data, chlg, conn->user, - conn->passwd, &resp, &len); + result = Curl_auth_create_cram_md5_message(data, chlg, conn->user, + conn->passwd, &resp, &len); free(chlg); break; case SASL_DIGESTMD5: sasl->params->getmessage(data->state.buffer, &serverdata); - result = Curl_sasl_create_digest_md5_message(data, serverdata, + result = Curl_auth_create_digest_md5_message(data, serverdata, conn->user, conn->passwd, - sasl->params->service, + service, &resp, &len); newstate = SASL_DIGESTMD5_RESP; break; case SASL_DIGESTMD5_RESP: - if(!(resp = strdup(""))) + resp = strdup(""); + if(!resp) result = CURLE_OUT_OF_MEMORY; break; #endif @@ -1574,17 +484,17 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, #ifdef USE_NTLM case SASL_NTLM: /* Create the type-1 message */ - result = Curl_sasl_create_ntlm_type1_message(conn->user, conn->passwd, + result = Curl_auth_create_ntlm_type1_message(conn->user, conn->passwd, &conn->ntlm, &resp, &len); newstate = SASL_NTLM_TYPE2MSG; break; case SASL_NTLM_TYPE2MSG: /* Decode the type-2 message */ sasl->params->getmessage(data->state.buffer, &serverdata); - result = Curl_sasl_decode_ntlm_type2_message(data, serverdata, + result = Curl_auth_decode_ntlm_type2_message(data, serverdata, &conn->ntlm); if(!result) - result = Curl_sasl_create_ntlm_type3_message(data, conn->user, + result = Curl_auth_create_ntlm_type3_message(data, conn->user, conn->passwd, &conn->ntlm, &resp, &len); break; @@ -1592,9 +502,10 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, #if defined(USE_KERBEROS5) case SASL_GSSAPI: - result = Curl_sasl_create_gssapi_user_message(data, conn->user, + result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, - sasl->params->service, + service, + data->easy_conn->host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp, &len); @@ -1605,7 +516,8 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, if(sasl->mutual_auth) { /* Decode the user token challenge and create the optional response message */ - result = Curl_sasl_create_gssapi_user_message(data, NULL, NULL, NULL, + result = Curl_auth_create_gssapi_user_message(data, NULL, NULL, + NULL, NULL, sasl->mutual_auth, serverdata, &conn->krb5, &resp, &len); @@ -1613,24 +525,60 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, } else /* Decode the security challenge and create the response message */ - result = Curl_sasl_create_gssapi_security_message(data, serverdata, + result = Curl_auth_create_gssapi_security_message(data, serverdata, &conn->krb5, &resp, &len); break; case SASL_GSSAPI_NO_DATA: sasl->params->getmessage(data->state.buffer, &serverdata); /* Decode the security challenge and create the response message */ - result = Curl_sasl_create_gssapi_security_message(data, serverdata, + result = Curl_auth_create_gssapi_security_message(data, serverdata, &conn->krb5, &resp, &len); break; #endif - case SASL_XOAUTH2: + case SASL_OAUTH2: /* Create the authorisation message */ - result = sasl_create_xoauth2_message(data, conn->user, - conn->xoauth2_bearer, &resp, &len); + if(sasl->authused == SASL_MECH_OAUTHBEARER) { + result = Curl_auth_create_oauth_bearer_message(data, conn->user, + conn->host.name, + conn->port, + conn->oauth_bearer, + &resp, &len); + + /* Failures maybe sent by the server as continuations for OAUTHBEARER */ + newstate = SASL_OAUTH2_RESP; + } + else + result = Curl_auth_create_oauth_bearer_message(data, conn->user, + NULL, 0, + conn->oauth_bearer, + &resp, &len); break; + + case SASL_OAUTH2_RESP: + /* The continuation is optional so check the response code */ + if(code == sasl->params->finalcode) { + /* Final response was received so we are done */ + *progress = SASL_DONE; + state(sasl, conn, SASL_STOP); + return result; + } + else if(code == sasl->params->contcode) { + /* Acknowledge the continuation by sending a 0x01 response base64 + encoded */ + resp = strdup("AQ=="); + if(!resp) + result = CURLE_OUT_OF_MEMORY; + break; + } + else { + *progress = SASL_DONE; + state(sasl, conn, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + case SASL_CANCEL: /* Remove the offending mechanism from the supported list */ sasl->authmechs ^= sasl->authused; diff --git a/Utilities/cmcurl/lib/curl_sasl.h b/Utilities/cmcurl/lib/curl_sasl.h index 117d60e..7647a48 100644 --- a/Utilities/cmcurl/lib/curl_sasl.h +++ b/Utilities/cmcurl/lib/curl_sasl.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,21 +24,9 @@ #include <curl/curl.h> -struct SessionHandle; +struct Curl_easy; struct connectdata; -#if !defined(CURL_DISABLE_CRYPTO_AUTH) -struct digestdata; -#endif - -#if defined(USE_NTLM) -struct ntlmdata; -#endif - -#if defined(USE_KERBEROS5) -struct kerberos5data; -#endif - /* Authentication mechanism flags */ #define SASL_MECH_LOGIN (1 << 0) #define SASL_MECH_PLAIN (1 << 1) @@ -48,32 +36,23 @@ struct kerberos5data; #define SASL_MECH_EXTERNAL (1 << 5) #define SASL_MECH_NTLM (1 << 6) #define SASL_MECH_XOAUTH2 (1 << 7) +#define SASL_MECH_OAUTHBEARER (1 << 8) /* Authentication mechanism values */ #define SASL_AUTH_NONE 0 #define SASL_AUTH_ANY ~0U -#define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & \ - ~(SASL_MECH_EXTERNAL | SASL_MECH_XOAUTH2)) +#define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & ~SASL_MECH_EXTERNAL) /* Authentication mechanism strings */ -#define SASL_MECH_STRING_LOGIN "LOGIN" -#define SASL_MECH_STRING_PLAIN "PLAIN" -#define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5" -#define SASL_MECH_STRING_DIGEST_MD5 "DIGEST-MD5" -#define SASL_MECH_STRING_GSSAPI "GSSAPI" -#define SASL_MECH_STRING_EXTERNAL "EXTERNAL" -#define SASL_MECH_STRING_NTLM "NTLM" -#define SASL_MECH_STRING_XOAUTH2 "XOAUTH2" - -#if !defined(CURL_DISABLE_CRYPTO_AUTH) -#define DIGEST_MAX_VALUE_LENGTH 256 -#define DIGEST_MAX_CONTENT_LENGTH 1024 -#endif - -enum { - CURLDIGESTALGO_MD5, - CURLDIGESTALGO_MD5SESS -}; +#define SASL_MECH_STRING_LOGIN "LOGIN" +#define SASL_MECH_STRING_PLAIN "PLAIN" +#define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5" +#define SASL_MECH_STRING_DIGEST_MD5 "DIGEST-MD5" +#define SASL_MECH_STRING_GSSAPI "GSSAPI" +#define SASL_MECH_STRING_EXTERNAL "EXTERNAL" +#define SASL_MECH_STRING_NTLM "NTLM" +#define SASL_MECH_STRING_XOAUTH2 "XOAUTH2" +#define SASL_MECH_STRING_OAUTHBEARER "OAUTHBEARER" /* SASL machine states */ typedef enum { @@ -90,7 +69,8 @@ typedef enum { SASL_GSSAPI, SASL_GSSAPI_TOKEN, SASL_GSSAPI_NO_DATA, - SASL_XOAUTH2, + SASL_OAUTH2, + SASL_OAUTH2_RESP, SASL_CANCEL, SASL_FINAL } saslstate; @@ -134,97 +114,6 @@ struct SASL { (wordlen == (sizeof(mech) - 1) / sizeof(char) && \ !memcmp(line, mech, wordlen)) -/* This is used to build a SPN string */ -#if !defined(USE_WINDOWS_SSPI) -char *Curl_sasl_build_spn(const char *service, const char *instance); -#else -TCHAR *Curl_sasl_build_spn(const char *service, const char *instance); -#endif - -/* This is used to extract the realm from a challenge message */ -int Curl_sasl_digest_get_pair(const char *str, char *value, char *content, - const char **endptr); - -#if defined(HAVE_GSSAPI) -char *Curl_sasl_build_gssapi_spn(const char *service, const char *host); -#endif - -#ifndef CURL_DISABLE_CRYPTO_AUTH - -/* This is used to generate a base64 encoded DIGEST-MD5 response message */ -CURLcode Curl_sasl_create_digest_md5_message(struct SessionHandle *data, - const char *chlg64, - const char *userp, - const char *passwdp, - const char *service, - char **outptr, size_t *outlen); - -/* This is used to decode a HTTP DIGEST challenge message */ -CURLcode Curl_sasl_decode_digest_http_message(const char *chlg, - struct digestdata *digest); - -/* This is used to generate a HTTP DIGEST response message */ -CURLcode Curl_sasl_create_digest_http_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - const unsigned char *request, - const unsigned char *uri, - struct digestdata *digest, - char **outptr, size_t *outlen); - -/* This is used to clean up the digest specific data */ -void Curl_sasl_digest_cleanup(struct digestdata *digest); -#endif - -#ifdef USE_NTLM -/* This is used to generate a base64 encoded NTLM type-1 message */ -CURLcode Curl_sasl_create_ntlm_type1_message(const char *userp, - const char *passwdp, - struct ntlmdata *ntlm, - char **outptr, - size_t *outlen); - -/* This is used to decode a base64 encoded NTLM type-2 message */ -CURLcode Curl_sasl_decode_ntlm_type2_message(struct SessionHandle *data, - const char *type2msg, - struct ntlmdata *ntlm); - -/* This is used to generate a base64 encoded NTLM type-3 message */ -CURLcode Curl_sasl_create_ntlm_type3_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - struct ntlmdata *ntlm, - char **outptr, size_t *outlen); - -/* This is used to clean up the ntlm specific data */ -void Curl_sasl_ntlm_cleanup(struct ntlmdata *ntlm); - -#endif /* USE_NTLM */ - -#if defined(USE_KERBEROS5) -/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) user token - message */ -CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - const char *service, - const bool mutual, - const char *chlg64, - struct kerberos5data *krb5, - char **outptr, size_t *outlen); - -/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) security - token message */ -CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, - const char *input, - struct kerberos5data *krb5, - char **outptr, - size_t *outlen); - -/* This is used to clean up the gssapi specific data */ -void Curl_sasl_gssapi_cleanup(struct kerberos5data *krb5); -#endif /* USE_KERBEROS5 */ - /* This is used to cleanup any libraries or curl modules used by the sasl functions */ void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused); diff --git a/Utilities/cmcurl/lib/curl_sasl_sspi.c b/Utilities/cmcurl/lib/curl_sasl_sspi.c deleted file mode 100644 index e96b55c..0000000 --- a/Utilities/cmcurl/lib/curl_sasl_sspi.c +++ /dev/null @@ -1,1281 +0,0 @@ -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 2014 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. - * Copyright (C) 2014, Steve Holme, <steve_holme@hotmail.com>. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * RFC2617 Basic and Digest Access Authentication - * RFC2831 DIGEST-MD5 authentication - * RFC4422 Simple Authentication and Security Layer (SASL) - * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism - * - ***************************************************************************/ - -#include "curl_setup.h" - -#if defined(USE_WINDOWS_SSPI) - -#include <curl/curl.h> - -#include "curl_sasl.h" -#include "urldata.h" -#include "curl_base64.h" -#include "warnless.h" -#include "curl_multibyte.h" -#include "sendf.h" -#include "strdup.h" -#include "curl_printf.h" -#include "rawstr.h" - -/* The last #include files should be: */ -#include "curl_memory.h" -#include "memdebug.h" - -/* - * Curl_sasl_build_spn() - * - * This is used to build a SPN string in the format service/host. - * - * Parameters: - * - * serivce [in] - The service type such as www, smtp, pop or imap. - * host [in] - The host name or realm. - * - * Returns a pointer to the newly allocated SPN. - */ -TCHAR *Curl_sasl_build_spn(const char *service, const char *host) -{ - char *utf8_spn = NULL; - TCHAR *tchar_spn = NULL; - - /* Note: We could use DsMakeSPN() or DsClientMakeSpnForTargetServer() rather - than doing this ourselves but the first is only available in Windows XP - and Windows Server 2003 and the latter is only available in Windows 2000 - but not Windows95/98/ME or Windows NT4.0 unless the Active Directory - Client Extensions are installed. As such it is far simpler for us to - formulate the SPN instead. */ - - /* Allocate our UTF8 based SPN */ - utf8_spn = aprintf("%s/%s", service, host); - if(!utf8_spn) { - return NULL; - } - - /* Allocate our TCHAR based SPN */ - tchar_spn = Curl_convert_UTF8_to_tchar(utf8_spn); - if(!tchar_spn) { - free(utf8_spn); - - return NULL; - } - - /* Release the UTF8 variant when operating with Unicode */ - Curl_unicodefree(utf8_spn); - - /* Return our newly allocated SPN */ - return tchar_spn; -} - -#if !defined(CURL_DISABLE_CRYPTO_AUTH) -/* - * Curl_sasl_create_digest_md5_message() - * - * This is used to generate an already encoded DIGEST-MD5 response message - * ready for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * chlg64 [in] - The base64 encoded challenge message. - * userp [in] - The user name in the format User or Domain\User. - * passdwp [in] - The user's password. - * service [in] - The service type such as www, smtp, pop or imap. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_create_digest_md5_message(struct SessionHandle *data, - const char *chlg64, - const char *userp, - const char *passwdp, - const char *service, - char **outptr, size_t *outlen) -{ - CURLcode result = CURLE_OK; - TCHAR *spn = NULL; - size_t chlglen = 0; - size_t token_max = 0; - unsigned char *input_token = NULL; - unsigned char *output_token = NULL; - CredHandle credentials; - CtxtHandle context; - PSecPkgInfo SecurityPackage; - SEC_WINNT_AUTH_IDENTITY identity; - SEC_WINNT_AUTH_IDENTITY *p_identity; - SecBuffer chlg_buf; - SecBuffer resp_buf; - SecBufferDesc chlg_desc; - SecBufferDesc resp_desc; - SECURITY_STATUS status; - unsigned long attrs; - TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ - - /* Decode the base-64 encoded challenge message */ - if(strlen(chlg64) && *chlg64 != '=') { - result = Curl_base64_decode(chlg64, &input_token, &chlglen); - if(result) - return result; - } - - /* Ensure we have a valid challenge message */ - if(!input_token) { - infof(data, "DIGEST-MD5 handshake failure (empty challenge message)\n"); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Query the security package for DigestSSP */ - status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), - &SecurityPackage); - if(status != SEC_E_OK) { - free(input_token); - - return CURLE_NOT_BUILT_IN; - } - - token_max = SecurityPackage->cbMaxToken; - - /* Release the package buffer as it is not required anymore */ - s_pSecFn->FreeContextBuffer(SecurityPackage); - - /* Allocate our response buffer */ - output_token = malloc(token_max); - if(!output_token) { - free(input_token); - - return CURLE_OUT_OF_MEMORY; - } - - /* Generate our SPN */ - spn = Curl_sasl_build_spn(service, data->easy_conn->host.name); - if(!spn) { - free(output_token); - free(input_token); - - return CURLE_OUT_OF_MEMORY; - } - - if(userp && *userp) { - /* Populate our identity structure */ - result = Curl_create_sspi_identity(userp, passwdp, &identity); - if(result) { - free(spn); - free(output_token); - free(input_token); - - return result; - } - - /* Allow proper cleanup of the identity structure */ - p_identity = &identity; - } - else - /* Use the current Windows user */ - p_identity = NULL; - - /* Acquire our credentials handle */ - status = s_pSecFn->AcquireCredentialsHandle(NULL, - (TCHAR *) TEXT(SP_NAME_DIGEST), - SECPKG_CRED_OUTBOUND, NULL, - p_identity, NULL, NULL, - &credentials, &expiry); - - if(status != SEC_E_OK) { - Curl_sspi_free_identity(p_identity); - free(spn); - free(output_token); - free(input_token); - - return CURLE_LOGIN_DENIED; - } - - /* Setup the challenge "input" security buffer */ - chlg_desc.ulVersion = SECBUFFER_VERSION; - chlg_desc.cBuffers = 1; - chlg_desc.pBuffers = &chlg_buf; - chlg_buf.BufferType = SECBUFFER_TOKEN; - chlg_buf.pvBuffer = input_token; - chlg_buf.cbBuffer = curlx_uztoul(chlglen); - - /* Setup the response "output" security buffer */ - resp_desc.ulVersion = SECBUFFER_VERSION; - resp_desc.cBuffers = 1; - resp_desc.pBuffers = &resp_buf; - resp_buf.BufferType = SECBUFFER_TOKEN; - resp_buf.pvBuffer = output_token; - resp_buf.cbBuffer = curlx_uztoul(token_max); - - /* Generate our response message */ - status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, spn, - 0, 0, 0, &chlg_desc, 0, - &context, &resp_desc, &attrs, - &expiry); - - if(status == SEC_I_COMPLETE_NEEDED || - status == SEC_I_COMPLETE_AND_CONTINUE) - s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); - else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { - s_pSecFn->FreeCredentialsHandle(&credentials); - Curl_sspi_free_identity(p_identity); - free(spn); - free(output_token); - free(input_token); - - return CURLE_RECV_ERROR; - } - - /* Base64 encode the response */ - result = Curl_base64_encode(data, (char *) output_token, resp_buf.cbBuffer, - outptr, outlen); - - /* Free our handles */ - s_pSecFn->DeleteSecurityContext(&context); - s_pSecFn->FreeCredentialsHandle(&credentials); - - /* Free the identity structure */ - Curl_sspi_free_identity(p_identity); - - /* Free the SPN */ - free(spn); - - /* Free the response buffer */ - free(output_token); - - /* Free the decoded challenge message */ - free(input_token); - - return result; -} - -/* -* Curl_override_sspi_http_realm() -* -* This is used to populate the domain in a SSPI identity structure -* The realm is extracted from the challenge message and used as the -* domain if it is not already explicitly set. -* -* Parameters: -* -* chlg [in] - The challenge message. -* identity [in/out] - The identity structure. -* -* Returns CURLE_OK on success. -*/ -CURLcode Curl_override_sspi_http_realm(const char *chlg, - SEC_WINNT_AUTH_IDENTITY *identity) -{ - xcharp_u domain, dup_domain; - - /* If domain is blank or unset, check challenge message for realm */ - if(!identity->Domain || !identity->DomainLength) { - for(;;) { - char value[DIGEST_MAX_VALUE_LENGTH]; - char content[DIGEST_MAX_CONTENT_LENGTH]; - - /* Pass all additional spaces here */ - while(*chlg && ISSPACE(*chlg)) - chlg++; - - /* Extract a value=content pair */ - if(!Curl_sasl_digest_get_pair(chlg, value, content, &chlg)) { - if(Curl_raw_equal(value, "realm")) { - - /* Setup identity's domain and length */ - domain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *)content); - if(!domain.tchar_ptr) - return CURLE_OUT_OF_MEMORY; - dup_domain.tchar_ptr = _tcsdup(domain.tchar_ptr); - if(!dup_domain.tchar_ptr) { - Curl_unicodefree(domain.tchar_ptr); - return CURLE_OUT_OF_MEMORY; - } - identity->Domain = dup_domain.tbyte_ptr; - identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr)); - dup_domain.tchar_ptr = NULL; - - Curl_unicodefree(domain.tchar_ptr); - } - else { - /* unknown specifier, ignore it! */ - } - } - else - break; /* we're done here */ - - /* Pass all additional spaces here */ - while(*chlg && ISSPACE(*chlg)) - chlg++; - - /* Allow the list to be comma-separated */ - if(',' == *chlg) - chlg++; - } - } - - return CURLE_OK; -} - -/* - * Curl_sasl_decode_digest_http_message() - * - * This is used to decode a HTTP DIGEST challenge message into the seperate - * attributes. - * - * Parameters: - * - * chlg [in] - The challenge message. - * digest [in/out] - The digest data struct being used and modified. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_decode_digest_http_message(const char *chlg, - struct digestdata *digest) -{ - size_t chlglen = strlen(chlg); - - /* We had an input token before and we got another one now. This means we - provided bad credentials in the previous request. */ - if(digest->input_token) - return CURLE_BAD_CONTENT_ENCODING; - - /* Simply store the challenge for use later */ - digest->input_token = (BYTE *) Curl_memdup(chlg, chlglen); - if(!digest->input_token) - return CURLE_OUT_OF_MEMORY; - - digest->input_token_len = chlglen; - - return CURLE_OK; -} - -/* - * Curl_sasl_create_digest_http_message() - * - * This is used to generate a HTTP DIGEST response message ready for sending - * to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * userp [in] - The user name in the format User or Domain\User. - * passdwp [in] - The user's password. - * request [in] - The HTTP request. - * uripath [in] - The path of the HTTP uri. - * digest [in/out] - The digest data struct being used and modified. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_create_digest_http_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - const unsigned char *request, - const unsigned char *uripath, - struct digestdata *digest, - char **outptr, size_t *outlen) -{ - size_t token_max; - CredHandle credentials; - CtxtHandle context; - char *resp; - BYTE *output_token; - PSecPkgInfo SecurityPackage; - SEC_WINNT_AUTH_IDENTITY identity; - SEC_WINNT_AUTH_IDENTITY *p_identity; - SecBuffer chlg_buf[3]; - SecBuffer resp_buf; - SecBufferDesc chlg_desc; - SecBufferDesc resp_desc; - SECURITY_STATUS status; - unsigned long attrs; - TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ - - (void) data; - - /* Query the security package for DigestSSP */ - status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), - &SecurityPackage); - if(status != SEC_E_OK) - return CURLE_NOT_BUILT_IN; - - token_max = SecurityPackage->cbMaxToken; - - /* Release the package buffer as it is not required anymore */ - s_pSecFn->FreeContextBuffer(SecurityPackage); - - /* Allocate the output buffer according to the max token size as indicated - by the security package */ - output_token = malloc(token_max); - if(!output_token) - return CURLE_OUT_OF_MEMORY; - - if(userp && *userp) { - /* Populate our identity structure */ - if(Curl_create_sspi_identity(userp, passwdp, &identity)) - return CURLE_OUT_OF_MEMORY; - - /* Populate our identity domain */ - if(Curl_override_sspi_http_realm((const char*)digest->input_token, - &identity)) - return CURLE_OUT_OF_MEMORY; - - /* Allow proper cleanup of the identity structure */ - p_identity = &identity; - } - else - /* Use the current Windows user */ - p_identity = NULL; - - /* Acquire our credentials handle */ - status = s_pSecFn->AcquireCredentialsHandle(NULL, - (TCHAR *) TEXT(SP_NAME_DIGEST), - SECPKG_CRED_OUTBOUND, NULL, - p_identity, NULL, NULL, - &credentials, &expiry); - if(status != SEC_E_OK) { - free(output_token); - - return CURLE_LOGIN_DENIED; - } - - /* Setup the challenge "input" security buffer if present */ - chlg_desc.ulVersion = SECBUFFER_VERSION; - chlg_desc.cBuffers = 3; - chlg_desc.pBuffers = chlg_buf; - chlg_buf[0].BufferType = SECBUFFER_TOKEN; - chlg_buf[0].pvBuffer = digest->input_token; - chlg_buf[0].cbBuffer = curlx_uztoul(digest->input_token_len); - chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; - chlg_buf[1].pvBuffer = (void *)request; - chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *) request)); - chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; - chlg_buf[2].pvBuffer = NULL; - chlg_buf[2].cbBuffer = 0; - - /* Setup the response "output" security buffer */ - resp_desc.ulVersion = SECBUFFER_VERSION; - resp_desc.cBuffers = 1; - resp_desc.pBuffers = &resp_buf; - resp_buf.BufferType = SECBUFFER_TOKEN; - resp_buf.pvBuffer = output_token; - resp_buf.cbBuffer = curlx_uztoul(token_max); - - /* Generate our reponse message */ - status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, - (TCHAR *) uripath, - ISC_REQ_USE_HTTP_STYLE, 0, 0, - &chlg_desc, 0, &context, - &resp_desc, &attrs, &expiry); - - if(status == SEC_I_COMPLETE_NEEDED || - status == SEC_I_COMPLETE_AND_CONTINUE) - s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); - else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { - s_pSecFn->FreeCredentialsHandle(&credentials); - - free(output_token); - - return CURLE_OUT_OF_MEMORY; - } - - resp = malloc(resp_buf.cbBuffer + 1); - if(!resp) { - s_pSecFn->DeleteSecurityContext(&context); - s_pSecFn->FreeCredentialsHandle(&credentials); - - free(output_token); - - return CURLE_OUT_OF_MEMORY; - } - - /* Copy the generated reponse */ - memcpy(resp, resp_buf.pvBuffer, resp_buf.cbBuffer); - resp[resp_buf.cbBuffer] = 0x00; - - /* Return the response */ - *outptr = resp; - *outlen = resp_buf.cbBuffer; - - /* Free our handles */ - s_pSecFn->DeleteSecurityContext(&context); - s_pSecFn->FreeCredentialsHandle(&credentials); - - /* Free the identity structure */ - Curl_sspi_free_identity(p_identity); - - /* Free the response buffer */ - free(output_token); - - return CURLE_OK; -} - -/* - * Curl_sasl_digest_cleanup() - * - * This is used to clean up the digest specific data. - * - * Parameters: - * - * digest [in/out] - The digest data struct being cleaned up. - * - */ -void Curl_sasl_digest_cleanup(struct digestdata *digest) -{ - /* Free the input token */ - Curl_safefree(digest->input_token); - - /* Reset any variables */ - digest->input_token_len = 0; -} -#endif /* !CURL_DISABLE_CRYPTO_AUTH */ - -#if defined USE_NTLM -/* -* Curl_sasl_create_ntlm_type1_message() -* -* This is used to generate an already encoded NTLM type-1 message ready for -* sending to the recipient. -* -* Parameters: -* -* userp [in] - The user name in the format User or Domain\User. -* passdwp [in] - The user's password. -* ntlm [in/out] - The ntlm data struct being used and modified. -* outptr [in/out] - The address where a pointer to newly allocated memory -* holding the result will be stored upon completion. -* outlen [out] - The length of the output message. -* -* Returns CURLE_OK on success. -*/ -CURLcode Curl_sasl_create_ntlm_type1_message(const char *userp, - const char *passwdp, - struct ntlmdata *ntlm, - char **outptr, size_t *outlen) -{ - PSecPkgInfo SecurityPackage; - SecBuffer type_1_buf; - SecBufferDesc type_1_desc; - SECURITY_STATUS status; - unsigned long attrs; - TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ - - /* Clean up any former leftovers and initialise to defaults */ - Curl_sasl_ntlm_cleanup(ntlm); - - /* Query the security package for NTLM */ - status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), - &SecurityPackage); - if(status != SEC_E_OK) - return CURLE_NOT_BUILT_IN; - - ntlm->token_max = SecurityPackage->cbMaxToken; - - /* Release the package buffer as it is not required anymore */ - s_pSecFn->FreeContextBuffer(SecurityPackage); - - /* Allocate our output buffer */ - ntlm->output_token = malloc(ntlm->token_max); - if(!ntlm->output_token) - return CURLE_OUT_OF_MEMORY; - - if(userp && *userp) { - CURLcode result; - - /* Populate our identity structure */ - result = Curl_create_sspi_identity(userp, passwdp, &ntlm->identity); - if(result) - return result; - - /* Allow proper cleanup of the identity structure */ - ntlm->p_identity = &ntlm->identity; - } - else - /* Use the current Windows user */ - ntlm->p_identity = NULL; - - /* Allocate our credentials handle */ - ntlm->credentials = malloc(sizeof(CredHandle)); - if(!ntlm->credentials) - return CURLE_OUT_OF_MEMORY; - - memset(ntlm->credentials, 0, sizeof(CredHandle)); - - /* Acquire our credentials handle */ - status = s_pSecFn->AcquireCredentialsHandle(NULL, - (TCHAR *) TEXT(SP_NAME_NTLM), - SECPKG_CRED_OUTBOUND, NULL, - ntlm->p_identity, NULL, NULL, - ntlm->credentials, &expiry); - if(status != SEC_E_OK) - return CURLE_LOGIN_DENIED; - - /* Allocate our new context handle */ - ntlm->context = malloc(sizeof(CtxtHandle)); - if(!ntlm->context) - return CURLE_OUT_OF_MEMORY; - - memset(ntlm->context, 0, sizeof(CtxtHandle)); - - /* Setup the type-1 "output" security buffer */ - type_1_desc.ulVersion = SECBUFFER_VERSION; - type_1_desc.cBuffers = 1; - type_1_desc.pBuffers = &type_1_buf; - type_1_buf.BufferType = SECBUFFER_TOKEN; - type_1_buf.pvBuffer = ntlm->output_token; - type_1_buf.cbBuffer = curlx_uztoul(ntlm->token_max); - - /* Generate our type-1 message */ - status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, NULL, - (TCHAR *) TEXT(""), - 0, 0, SECURITY_NETWORK_DREP, - NULL, 0, - ntlm->context, &type_1_desc, - &attrs, &expiry); - if(status == SEC_I_COMPLETE_NEEDED || - status == SEC_I_COMPLETE_AND_CONTINUE) - s_pSecFn->CompleteAuthToken(ntlm->context, &type_1_desc); - else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) - return CURLE_RECV_ERROR; - - /* Base64 encode the response */ - return Curl_base64_encode(NULL, (char *) ntlm->output_token, - type_1_buf.cbBuffer, outptr, outlen); -} - -/* -* Curl_sasl_decode_ntlm_type2_message() -* -* This is used to decode an already encoded NTLM type-2 message. -* -* Parameters: -* -* data [in] - The session handle. -* type2msg [in] - The base64 encoded type-2 message. -* ntlm [in/out] - The ntlm data struct being used and modified. -* -* Returns CURLE_OK on success. -*/ -CURLcode Curl_sasl_decode_ntlm_type2_message(struct SessionHandle *data, - const char *type2msg, - struct ntlmdata *ntlm) -{ - CURLcode result = CURLE_OK; - unsigned char *type2 = NULL; - size_t type2_len = 0; - -#if defined(CURL_DISABLE_VERBOSE_STRINGS) - (void) data; -#endif - - /* Decode the base-64 encoded type-2 message */ - if(strlen(type2msg) && *type2msg != '=') { - result = Curl_base64_decode(type2msg, &type2, &type2_len); - if(result) - return result; - } - - /* Ensure we have a valid type-2 message */ - if(!type2) { - infof(data, "NTLM handshake failure (empty type-2 message)\n"); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Simply store the challenge for use later */ - ntlm->input_token = type2; - ntlm->input_token_len = type2_len; - - return result; -} - -/* -* Curl_sasl_create_ntlm_type3_message() -* -* This is used to generate an already encoded NTLM type-3 message ready for -* sending to the recipient. -* -* Parameters: -* -* data [in] - The session handle. -* userp [in] - The user name in the format User or Domain\User. -* passdwp [in] - The user's password. -* ntlm [in/out] - The ntlm data struct being used and modified. -* outptr [in/out] - The address where a pointer to newly allocated memory -* holding the result will be stored upon completion. -* outlen [out] - The length of the output message. -* -* Returns CURLE_OK on success. -*/ -CURLcode Curl_sasl_create_ntlm_type3_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - struct ntlmdata *ntlm, - char **outptr, size_t *outlen) -{ - CURLcode result = CURLE_OK; - SecBuffer type_2_buf; - SecBuffer type_3_buf; - SecBufferDesc type_2_desc; - SecBufferDesc type_3_desc; - SECURITY_STATUS status; - unsigned long attrs; - TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ - - (void) passwdp; - (void) userp; - - /* Setup the type-2 "input" security buffer */ - type_2_desc.ulVersion = SECBUFFER_VERSION; - type_2_desc.cBuffers = 1; - type_2_desc.pBuffers = &type_2_buf; - type_2_buf.BufferType = SECBUFFER_TOKEN; - type_2_buf.pvBuffer = ntlm->input_token; - type_2_buf.cbBuffer = curlx_uztoul(ntlm->input_token_len); - - /* Setup the type-3 "output" security buffer */ - type_3_desc.ulVersion = SECBUFFER_VERSION; - type_3_desc.cBuffers = 1; - type_3_desc.pBuffers = &type_3_buf; - type_3_buf.BufferType = SECBUFFER_TOKEN; - type_3_buf.pvBuffer = ntlm->output_token; - type_3_buf.cbBuffer = curlx_uztoul(ntlm->token_max); - - /* Generate our type-3 message */ - status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, - ntlm->context, - (TCHAR *) TEXT(""), - 0, 0, SECURITY_NETWORK_DREP, - &type_2_desc, - 0, ntlm->context, - &type_3_desc, - &attrs, &expiry); - if(status != SEC_E_OK) { - infof(data, "NTLM handshake failure (type-3 message): Status=%x\n", - status); - - return CURLE_RECV_ERROR; - } - - /* Base64 encode the response */ - result = Curl_base64_encode(data, (char *) ntlm->output_token, - type_3_buf.cbBuffer, outptr, outlen); - - Curl_sasl_ntlm_cleanup(ntlm); - - return result; -} - -/* - * Curl_sasl_ntlm_cleanup() - * - * This is used to clean up the ntlm specific data. - * - * Parameters: - * - * ntlm [in/out] - The ntlm data struct being cleaned up. - * - */ -void Curl_sasl_ntlm_cleanup(struct ntlmdata *ntlm) -{ - /* Free our security context */ - if(ntlm->context) { - s_pSecFn->DeleteSecurityContext(ntlm->context); - free(ntlm->context); - ntlm->context = NULL; - } - - /* Free our credentials handle */ - if(ntlm->credentials) { - s_pSecFn->FreeCredentialsHandle(ntlm->credentials); - free(ntlm->credentials); - ntlm->credentials = NULL; - } - - /* Free our identity */ - Curl_sspi_free_identity(ntlm->p_identity); - ntlm->p_identity = NULL; - - /* Free the input and output tokens */ - Curl_safefree(ntlm->input_token); - Curl_safefree(ntlm->output_token); - - /* Reset any variables */ - ntlm->token_max = 0; -} -#endif /* USE_NTLM */ - -#if defined(USE_KERBEROS5) -/* - * Curl_sasl_create_gssapi_user_message() - * - * This is used to generate an already encoded GSSAPI (Kerberos V5) user token - * message ready for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * userp [in] - The user name in the format User or Domain\User. - * passdwp [in] - The user's password. - * service [in] - The service type such as www, smtp, pop or imap. - * mutual_auth [in] - Flag specifying whether or not mutual authentication - * is enabled. - * chlg64 [in] - The optional base64 encoded challenge message. - * krb5 [in/out] - The gssapi data struct being used and modified. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, - const char *userp, - const char *passwdp, - const char *service, - const bool mutual_auth, - const char *chlg64, - struct kerberos5data *krb5, - char **outptr, size_t *outlen) -{ - CURLcode result = CURLE_OK; - size_t chlglen = 0; - unsigned char *chlg = NULL; - CtxtHandle context; - PSecPkgInfo SecurityPackage; - SecBuffer chlg_buf; - SecBuffer resp_buf; - SecBufferDesc chlg_desc; - SecBufferDesc resp_desc; - SECURITY_STATUS status; - unsigned long attrs; - TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ - - if(!krb5->credentials) { - /* Query the security package for Kerberos */ - status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) - TEXT(SP_NAME_KERBEROS), - &SecurityPackage); - if(status != SEC_E_OK) { - return CURLE_NOT_BUILT_IN; - } - - krb5->token_max = SecurityPackage->cbMaxToken; - - /* Release the package buffer as it is not required anymore */ - s_pSecFn->FreeContextBuffer(SecurityPackage); - - /* Allocate our response buffer */ - krb5->output_token = malloc(krb5->token_max); - if(!krb5->output_token) - return CURLE_OUT_OF_MEMORY; - - /* Generate our SPN */ - krb5->spn = Curl_sasl_build_spn(service, data->easy_conn->host.name); - if(!krb5->spn) - return CURLE_OUT_OF_MEMORY; - - if(userp && *userp) { - /* Populate our identity structure */ - result = Curl_create_sspi_identity(userp, passwdp, &krb5->identity); - if(result) - return result; - - /* Allow proper cleanup of the identity structure */ - krb5->p_identity = &krb5->identity; - } - else - /* Use the current Windows user */ - krb5->p_identity = NULL; - - /* Allocate our credentials handle */ - krb5->credentials = malloc(sizeof(CredHandle)); - if(!krb5->credentials) - return CURLE_OUT_OF_MEMORY; - - memset(krb5->credentials, 0, sizeof(CredHandle)); - - /* Acquire our credentials handle */ - status = s_pSecFn->AcquireCredentialsHandle(NULL, - (TCHAR *) - TEXT(SP_NAME_KERBEROS), - SECPKG_CRED_OUTBOUND, NULL, - krb5->p_identity, NULL, NULL, - krb5->credentials, &expiry); - if(status != SEC_E_OK) - return CURLE_LOGIN_DENIED; - - /* Allocate our new context handle */ - krb5->context = malloc(sizeof(CtxtHandle)); - if(!krb5->context) - return CURLE_OUT_OF_MEMORY; - - memset(krb5->context, 0, sizeof(CtxtHandle)); - } - else { - /* Decode the base-64 encoded challenge message */ - if(strlen(chlg64) && *chlg64 != '=') { - result = Curl_base64_decode(chlg64, &chlg, &chlglen); - if(result) - return result; - } - - /* Ensure we have a valid challenge message */ - if(!chlg) { - infof(data, "GSSAPI handshake failure (empty challenge message)\n"); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Setup the challenge "input" security buffer */ - chlg_desc.ulVersion = SECBUFFER_VERSION; - chlg_desc.cBuffers = 1; - chlg_desc.pBuffers = &chlg_buf; - chlg_buf.BufferType = SECBUFFER_TOKEN; - chlg_buf.pvBuffer = chlg; - chlg_buf.cbBuffer = curlx_uztoul(chlglen); - } - - /* Setup the response "output" security buffer */ - resp_desc.ulVersion = SECBUFFER_VERSION; - resp_desc.cBuffers = 1; - resp_desc.pBuffers = &resp_buf; - resp_buf.BufferType = SECBUFFER_TOKEN; - resp_buf.pvBuffer = krb5->output_token; - resp_buf.cbBuffer = curlx_uztoul(krb5->token_max); - - /* Generate our challenge-response message */ - status = s_pSecFn->InitializeSecurityContext(krb5->credentials, - chlg ? krb5->context : NULL, - krb5->spn, - (mutual_auth ? - ISC_REQ_MUTUAL_AUTH : 0), - 0, SECURITY_NATIVE_DREP, - chlg ? &chlg_desc : NULL, 0, - &context, - &resp_desc, &attrs, - &expiry); - - if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { - free(chlg); - - return CURLE_RECV_ERROR; - } - - if(memcmp(&context, krb5->context, sizeof(context))) { - s_pSecFn->DeleteSecurityContext(krb5->context); - - memcpy(krb5->context, &context, sizeof(context)); - } - - if(resp_buf.cbBuffer) { - /* Base64 encode the response */ - result = Curl_base64_encode(data, (char *)resp_buf.pvBuffer, - resp_buf.cbBuffer, outptr, outlen); - } - - /* Free the decoded challenge */ - free(chlg); - - return result; -} - -/* - * Curl_sasl_create_gssapi_security_message() - * - * This is used to generate an already encoded GSSAPI (Kerberos V5) security - * token message ready for sending to the recipient. - * - * Parameters: - * - * data [in] - The session handle. - * chlg64 [in] - The optional base64 encoded challenge message. - * krb5 [in/out] - The gssapi data struct being used and modified. - * outptr [in/out] - The address where a pointer to newly allocated memory - * holding the result will be stored upon completion. - * outlen [out] - The length of the output message. - * - * Returns CURLE_OK on success. - */ -CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, - const char *chlg64, - struct kerberos5data *krb5, - char **outptr, - size_t *outlen) -{ - CURLcode result = CURLE_OK; - size_t offset = 0; - size_t chlglen = 0; - size_t messagelen = 0; - size_t appdatalen = 0; - unsigned char *chlg = NULL; - unsigned char *trailer = NULL; - unsigned char *message = NULL; - unsigned char *padding = NULL; - unsigned char *appdata = NULL; - SecBuffer input_buf[2]; - SecBuffer wrap_buf[3]; - SecBufferDesc input_desc; - SecBufferDesc wrap_desc; - unsigned long indata = 0; - unsigned long outdata = 0; - unsigned long qop = 0; - unsigned long sec_layer = 0; - unsigned long max_size = 0; - SecPkgContext_Sizes sizes; - SecPkgCredentials_Names names; - SECURITY_STATUS status; - char *user_name; - - /* Decode the base-64 encoded input message */ - if(strlen(chlg64) && *chlg64 != '=') { - result = Curl_base64_decode(chlg64, &chlg, &chlglen); - if(result) - return result; - } - - /* Ensure we have a valid challenge message */ - if(!chlg) { - infof(data, "GSSAPI handshake failure (empty security message)\n"); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Get our response size information */ - status = s_pSecFn->QueryContextAttributes(krb5->context, - SECPKG_ATTR_SIZES, - &sizes); - if(status != SEC_E_OK) { - free(chlg); - - return CURLE_OUT_OF_MEMORY; - } - - /* Get the fully qualified username back from the context */ - status = s_pSecFn->QueryCredentialsAttributes(krb5->credentials, - SECPKG_CRED_ATTR_NAMES, - &names); - if(status != SEC_E_OK) { - free(chlg); - - return CURLE_RECV_ERROR; - } - - /* Setup the "input" security buffer */ - input_desc.ulVersion = SECBUFFER_VERSION; - input_desc.cBuffers = 2; - input_desc.pBuffers = input_buf; - input_buf[0].BufferType = SECBUFFER_STREAM; - input_buf[0].pvBuffer = chlg; - input_buf[0].cbBuffer = curlx_uztoul(chlglen); - input_buf[1].BufferType = SECBUFFER_DATA; - input_buf[1].pvBuffer = NULL; - input_buf[1].cbBuffer = 0; - - /* Decrypt the inbound challenge and obtain the qop */ - status = s_pSecFn->DecryptMessage(krb5->context, &input_desc, 0, &qop); - if(status != SEC_E_OK) { - infof(data, "GSSAPI handshake failure (empty security message)\n"); - - free(chlg); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ - if(input_buf[1].cbBuffer != 4) { - infof(data, "GSSAPI handshake failure (invalid security data)\n"); - - free(chlg); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Copy the data out and free the challenge as it is not required anymore */ - memcpy(&indata, input_buf[1].pvBuffer, 4); - s_pSecFn->FreeContextBuffer(input_buf[1].pvBuffer); - free(chlg); - - /* Extract the security layer */ - sec_layer = indata & 0x000000FF; - if(!(sec_layer & KERB_WRAP_NO_ENCRYPT)) { - infof(data, "GSSAPI handshake failure (invalid security layer)\n"); - - return CURLE_BAD_CONTENT_ENCODING; - } - - /* Extract the maximum message size the server can receive */ - max_size = ntohl(indata & 0xFFFFFF00); - if(max_size > 0) { - /* The server has told us it supports a maximum receive buffer, however, as - we don't require one unless we are encrypting data, we tell the server - our receive buffer is zero. */ - max_size = 0; - } - - /* Allocate the trailer */ - trailer = malloc(sizes.cbSecurityTrailer); - if(!trailer) - return CURLE_OUT_OF_MEMORY; - - /* Convert the user name to UTF8 when operating with Unicode */ - user_name = Curl_convert_tchar_to_UTF8(names.sUserName); - if(!user_name) { - free(trailer); - - return CURLE_OUT_OF_MEMORY; - } - - /* Allocate our message */ - messagelen = sizeof(outdata) + strlen(user_name) + 1; - message = malloc(messagelen); - if(!message) { - free(trailer); - Curl_unicodefree(user_name); - - return CURLE_OUT_OF_MEMORY; - } - - /* Populate the message with the security layer, client supported receive - message size and authorization identity including the 0x00 based - terminator. Note: Dispite RFC4752 Section 3.1 stating "The authorization - identity is not terminated with the zero-valued (%x00) octet." it seems - necessary to include it. */ - outdata = htonl(max_size) | sec_layer; - memcpy(message, &outdata, sizeof(outdata)); - strcpy((char *) message + sizeof(outdata), user_name); - Curl_unicodefree(user_name); - - /* Allocate the padding */ - padding = malloc(sizes.cbBlockSize); - if(!padding) { - free(message); - free(trailer); - - return CURLE_OUT_OF_MEMORY; - } - - /* Setup the "authentication data" security buffer */ - wrap_desc.ulVersion = SECBUFFER_VERSION; - wrap_desc.cBuffers = 3; - wrap_desc.pBuffers = wrap_buf; - wrap_buf[0].BufferType = SECBUFFER_TOKEN; - wrap_buf[0].pvBuffer = trailer; - wrap_buf[0].cbBuffer = sizes.cbSecurityTrailer; - wrap_buf[1].BufferType = SECBUFFER_DATA; - wrap_buf[1].pvBuffer = message; - wrap_buf[1].cbBuffer = curlx_uztoul(messagelen); - wrap_buf[2].BufferType = SECBUFFER_PADDING; - wrap_buf[2].pvBuffer = padding; - wrap_buf[2].cbBuffer = sizes.cbBlockSize; - - /* Encrypt the data */ - status = s_pSecFn->EncryptMessage(krb5->context, KERB_WRAP_NO_ENCRYPT, - &wrap_desc, 0); - if(status != SEC_E_OK) { - free(padding); - free(message); - free(trailer); - - return CURLE_OUT_OF_MEMORY; - } - - /* Allocate the encryption (wrap) buffer */ - appdatalen = wrap_buf[0].cbBuffer + wrap_buf[1].cbBuffer + - wrap_buf[2].cbBuffer; - appdata = malloc(appdatalen); - if(!appdata) { - free(padding); - free(message); - free(trailer); - - return CURLE_OUT_OF_MEMORY; - } - - /* Populate the encryption buffer */ - memcpy(appdata, wrap_buf[0].pvBuffer, wrap_buf[0].cbBuffer); - offset += wrap_buf[0].cbBuffer; - memcpy(appdata + offset, wrap_buf[1].pvBuffer, wrap_buf[1].cbBuffer); - offset += wrap_buf[1].cbBuffer; - memcpy(appdata + offset, wrap_buf[2].pvBuffer, wrap_buf[2].cbBuffer); - - /* Base64 encode the response */ - result = Curl_base64_encode(data, (char *)appdata, appdatalen, outptr, - outlen); - - /* Free all of our local buffers */ - free(appdata); - free(padding); - free(message); - free(trailer); - - return result; -} - -/* - * Curl_sasl_gssapi_cleanup() - * - * This is used to clean up the gssapi specific data. - * - * Parameters: - * - * krb5 [in/out] - The kerberos 5 data struct being cleaned up. - * - */ -void Curl_sasl_gssapi_cleanup(struct kerberos5data *krb5) -{ - /* Free our security context */ - if(krb5->context) { - s_pSecFn->DeleteSecurityContext(krb5->context); - free(krb5->context); - krb5->context = NULL; - } - - /* Free our credentials handle */ - if(krb5->credentials) { - s_pSecFn->FreeCredentialsHandle(krb5->credentials); - free(krb5->credentials); - krb5->credentials = NULL; - } - - /* Free our identity */ - Curl_sspi_free_identity(krb5->p_identity); - krb5->p_identity = NULL; - - /* Free the SPN and output token */ - Curl_safefree(krb5->spn); - Curl_safefree(krb5->output_token); - - /* Reset any variables */ - krb5->token_max = 0; -} -#endif /* USE_KERBEROS5 */ - -#endif /* USE_WINDOWS_SSPI */ diff --git a/Utilities/cmcurl/lib/curl_sec.h b/Utilities/cmcurl/lib/curl_sec.h index 6c48da2..3f94e14 100644 --- a/Utilities/cmcurl/lib/curl_sec.h +++ b/Utilities/cmcurl/lib/curl_sec.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_setup.h b/Utilities/cmcurl/lib/curl_setup.h index 19c1baf..2122220 100644 --- a/Utilities/cmcurl/lib/curl_setup.h +++ b/Utilities/cmcurl/lib/curl_setup.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -185,9 +185,6 @@ # ifndef CURL_DISABLE_SMTP # define CURL_DISABLE_SMTP # endif -# ifndef CURL_DISABLE_RTSP -# define CURL_DISABLE_RTSP -# endif # ifndef CURL_DISABLE_RTMP # define CURL_DISABLE_RTMP # endif @@ -229,6 +226,15 @@ #endif /* + * Use getaddrinfo to resolve the IPv4 address literal. If the current network + * interface doesn’t support IPv4, but supports IPv6, NAT64, and DNS64, + * performing this task will result in a synthesized IPv6 address. + */ +#ifdef __APPLE__ +#define USE_RESOLVE_ON_IPS 1 +#endif + +/* * Include header files for windows builds before redefining anything. * Use this preprocessor block only to include or exclude windows.h, * winsock2.h, ws2tcpip.h or winsock.h. Any other windows thing belongs @@ -253,7 +259,7 @@ # ifdef HAVE_WINSOCK2_H # include <winsock2.h> # ifdef HAVE_WS2TCPIP_H -# include <ws2tcpip.h> +# include <ws2tcpip.h> # endif # else # ifdef HAVE_WINSOCK_H @@ -491,7 +497,7 @@ # endif # ifndef fileno /* sunos 4 have this as a macro! */ - int fileno( FILE *stream); + int fileno(FILE *stream); # endif #endif /* WIN32 */ @@ -499,9 +505,10 @@ /* * msvc 6.0 requires PSDK in order to have INET6_ADDRSTRLEN * defined in ws2tcpip.h as well as to provide IPv6 support. + * Does not apply if lwIP is used. */ -#if defined(_MSC_VER) && !defined(__POCC__) +#if defined(_MSC_VER) && !defined(__POCC__) && !defined(USE_LWIPSOCK) # if !defined(HAVE_WS2TCPIP_H) || \ ((_MSC_VER < 1300) && !defined(INET6_ADDRSTRLEN)) # undef HAVE_GETADDRINFO_THREADSAFE @@ -545,6 +552,7 @@ # define CURLRES_ARES /* now undef the stock libc functions just to avoid them being used */ # undef HAVE_GETADDRINFO +# undef HAVE_FREEADDRINFO # undef HAVE_GETHOSTBYNAME #elif defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) # define CURLRES_ASYNCH @@ -620,7 +628,7 @@ int netware_init(void); #define LIBIDN_REQUIRED_VERSION "0.4.1" #if defined(USE_GNUTLS) || defined(USE_OPENSSL) || defined(USE_NSS) || \ - defined(USE_POLARSSL) || defined(USE_AXTLS) || \ + defined(USE_POLARSSL) || defined(USE_AXTLS) || defined(USE_MBEDTLS) || \ defined(USE_CYASSL) || defined(USE_SCHANNEL) || \ defined(USE_DARWINSSL) || defined(USE_GSKIT) #define USE_SSL /* SSL support has been enabled */ @@ -644,13 +652,9 @@ int netware_init(void); defined(USE_GNUTLS) || defined(USE_NSS) || defined(USE_DARWINSSL) || \ defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) -#ifdef HAVE_BORINGSSL /* BoringSSL is not NTLM capable */ -#undef USE_NTLM -#else #define USE_NTLM #endif #endif -#endif /* non-configure builds may define CURL_WANTS_CA_BUNDLE_ENV */ #if defined(CURL_WANTS_CA_BUNDLE_ENV) && !defined(CURL_CA_BUNDLE) @@ -692,7 +696,7 @@ int netware_init(void); * Ensure that Winsock and lwIP TCP/IP stacks are not mixed. */ -#if defined(__LWIP_OPT_H__) +#if defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H) # if defined(SOCKET) || \ defined(USE_WINSOCK) || \ defined(HAVE_WINSOCK_H) || \ @@ -723,7 +727,7 @@ int netware_init(void); #endif /* In Windows the default file mode is text but an application can override it. -Therefore we specify it explicitly. https://github.com/bagder/curl/pull/258 +Therefore we specify it explicitly. https://github.com/curl/curl/pull/258 */ #if defined(WIN32) || defined(MSDOS) #define FOPEN_READTEXT "rt" @@ -742,4 +746,19 @@ endings either CRLF or LF so 't' is appropriate. #define FOPEN_WRITETEXT "w" #endif +/* WinSock destroys recv() buffer when send() failed. + * Enabled automatically for Windows and for Cygwin as Cygwin sockets are + * wrappers for WinSock sockets. https://github.com/curl/curl/issues/657 + * Define DONT_USE_RECV_BEFORE_SEND_WORKAROUND to force disable workaround. + */ +#if !defined(DONT_USE_RECV_BEFORE_SEND_WORKAROUND) +# if defined(WIN32) || defined(__CYGWIN__) +# define USE_RECV_BEFORE_SEND_WORKAROUND +# endif +#else /* DONT_USE_RECV_BEFORE_SEND_WORKAROUNDS */ +# ifdef USE_RECV_BEFORE_SEND_WORKAROUND +# undef USE_RECV_BEFORE_SEND_WORKAROUND +# endif +#endif /* DONT_USE_RECV_BEFORE_SEND_WORKAROUNDS */ + #endif /* HEADER_CURL_SETUP_H */ diff --git a/Utilities/cmcurl/lib/curl_setup_once.h b/Utilities/cmcurl/lib/curl_setup_once.h index 69d6d47..4da8349 100644 --- a/Utilities/cmcurl/lib/curl_setup_once.h +++ b/Utilities/cmcurl/lib/curl_setup_once.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curl_sspi.c b/Utilities/cmcurl/lib/curl_sspi.c index 070424d..ee3f1b1 100644 --- a/Utilities/cmcurl/lib/curl_sspi.c +++ b/Utilities/cmcurl/lib/curl_sspi.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -27,6 +27,7 @@ #include <curl/curl.h> #include "curl_sspi.h" #include "curl_multibyte.h" +#include "system_win32.h" #include "warnless.h" /* The last #include files should be: */ @@ -66,7 +67,6 @@ PSecurityFunctionTable s_pSecFn = NULL; */ CURLcode Curl_sspi_global_init(void) { - bool securityDll = FALSE; INITSECURITYINTERFACE_FN pInitSecurityInterface; /* If security interface is not yet initialized try to do this */ @@ -74,52 +74,12 @@ CURLcode Curl_sspi_global_init(void) /* Security Service Provider Interface (SSPI) functions are located in * security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP * have both these DLLs (security.dll forwards calls to secur32.dll) */ - DWORD majorVersion = 4; - DWORD platformId = VER_PLATFORM_WIN32_NT; - -#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \ - (_WIN32_WINNT < _WIN32_WINNT_WIN2K) - OSVERSIONINFO osver; - - memset(&osver, 0, sizeof(osver)); - osver.dwOSVersionInfoSize = sizeof(osver); - - /* Find out Windows version */ - if(!GetVersionEx(&osver)) - return CURLE_FAILED_INIT; - - /* Verify the major version number == 4 and platform id == WIN_NT */ - if(osver.dwMajorVersion == majorVersion && - osver.dwPlatformId == platformId) - securityDll = TRUE; -#else - ULONGLONG cm; - OSVERSIONINFOEX osver; - - memset(&osver, 0, sizeof(osver)); - osver.dwOSVersionInfoSize = sizeof(osver); - osver.dwMajorVersion = majorVersion; - osver.dwPlatformId = platformId; - - cm = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL); - cm = VerSetConditionMask(cm, VER_MINORVERSION, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_PLATFORMID, VER_EQUAL); - - /* Verify the major version number == 4 and platform id == WIN_NT */ - if(VerifyVersionInfo(&osver, (VER_MAJORVERSION | VER_MINORVERSION | - VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR | - VER_PLATFORMID), - cm)) - securityDll = TRUE; -#endif /* Load SSPI dll into the address space of the calling process */ - if(securityDll) - s_hSecDll = LoadLibrary(TEXT("security.dll")); + if(Curl_verify_windows_version(4, 0, PLATFORM_WINNT, VERSION_EQUAL)) + s_hSecDll = Curl_load_library(TEXT("security.dll")); else - s_hSecDll = LoadLibrary(TEXT("secur32.dll")); + s_hSecDll = Curl_load_library(TEXT("secur32.dll")); if(!s_hSecDll) return CURLE_FAILED_INIT; diff --git a/Utilities/cmcurl/lib/curl_sspi.h b/Utilities/cmcurl/lib/curl_sspi.h index 8655715..2bbf947 100644 --- a/Utilities/cmcurl/lib/curl_sspi.h +++ b/Utilities/cmcurl/lib/curl_sspi.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -327,6 +327,10 @@ extern PSecurityFunctionTable s_pSecFn; # define SEC_I_SIGNATURE_NEEDED ((HRESULT)0x0009035CL) #endif +#ifndef CRYPT_E_REVOKED +# define CRYPT_E_REVOKED ((HRESULT)0x80092010L) +#endif + #ifdef UNICODE # define SECFLAG_WINNT_AUTH_IDENTITY \ (unsigned long)SEC_WINNT_AUTH_IDENTITY_UNICODE diff --git a/Utilities/cmcurl/lib/curl_threads.c b/Utilities/cmcurl/lib/curl_threads.c index f9b812e..c98d8bb 100644 --- a/Utilities/cmcurl/lib/curl_threads.c +++ b/Utilities/cmcurl/lib/curl_threads.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,6 +22,8 @@ #include "curl_setup.h" +#include <curl/curl.h> + #if defined(USE_THREADS_POSIX) # ifdef HAVE_PTHREAD_H # include <pthread.h> diff --git a/Utilities/cmcurl/lib/curl_threads.h b/Utilities/cmcurl/lib/curl_threads.h index 0f3191a..8cbac63 100644 --- a/Utilities/cmcurl/lib/curl_threads.h +++ b/Utilities/cmcurl/lib/curl_threads.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/curlx.h b/Utilities/cmcurl/lib/curlx.h index 979e7d7..448a34f 100644 --- a/Utilities/cmcurl/lib/curlx.h +++ b/Utilities/cmcurl/lib/curlx.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/dict.c b/Utilities/cmcurl/lib/dict.c index 06d7699..a7b5965 100644 --- a/Utilities/cmcurl/lib/dict.c +++ b/Utilities/cmcurl/lib/dict.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -91,7 +91,7 @@ const struct Curl_handler Curl_handler_dict = { PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */ }; -static char *unescape_word(struct SessionHandle *data, const char *inputbuff) +static char *unescape_word(struct Curl_easy *data, const char *inputbuff) { char *newp; char *dictp; @@ -133,7 +133,7 @@ static CURLcode dict_do(struct connectdata *conn, bool *done) char *nthdef = NULL; /* This is not part of the protocol, but required by RFC 2229 */ CURLcode result=CURLE_OK; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; char *path = data->state.path; diff --git a/Utilities/cmcurl/lib/dict.h b/Utilities/cmcurl/lib/dict.h index 44fd9d4..12c0f33 100644 --- a/Utilities/cmcurl/lib/dict.h +++ b/Utilities/cmcurl/lib/dict.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/dotdot.c b/Utilities/cmcurl/lib/dotdot.c index ae16941..ea7c8a0 100644 --- a/Utilities/cmcurl/lib/dotdot.c +++ b/Utilities/cmcurl/lib/dotdot.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,19 +22,22 @@ #include "curl_setup.h" -#include "dotdot.h" +#include <curl/curl.h> +#include "dotdot.h" #include "curl_memory.h" + /* The last #include file should be: */ #include "memdebug.h" /* * "Remove Dot Segments" - * http://tools.ietf.org/html/rfc3986#section-5.2.4 + * https://tools.ietf.org/html/rfc3986#section-5.2.4 */ /* * Curl_dedotdotify() + * @unittest: 1395 * * This function gets a zero-terminated path with dot and dotdot sequences * passed in and strips them off according to the rules in RFC 3986 section @@ -68,6 +71,12 @@ char *Curl_dedotdotify(const char *input) orgclone = clone; outptr = out; + if(!*clone) { + /* zero length string, return that */ + free(out); + return clone; + } + /* * To handle query-parts properly, we must find it and remove it during the * dotdot-operation and then append it again at the end to the output diff --git a/Utilities/cmcurl/lib/dotdot.h b/Utilities/cmcurl/lib/dotdot.h index cd57822..fac8e6f 100644 --- a/Utilities/cmcurl/lib/dotdot.h +++ b/Utilities/cmcurl/lib/dotdot.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/easy.c b/Utilities/cmcurl/lib/easy.c index 316acb1..dc7139f 100644 --- a/Utilities/cmcurl/lib/easy.c +++ b/Utilities/cmcurl/lib/easy.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -64,7 +64,6 @@ #include "easyif.h" #include "select.h" #include "sendf.h" /* for failf function prototype */ -#include "curl_ntlm.h" #include "connect.h" /* for Curl_getconnectinfo */ #include "slist.h" #include "amigaos.h" @@ -74,12 +73,13 @@ #include "multiif.h" #include "sigpipe.h" #include "ssh.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" +void Curl_version_init(void); + /* win32_cleanup() is for win32 socket cleanup functionality, the opposite of win32_init() */ static void win32_cleanup(void) @@ -120,8 +120,8 @@ static CURLcode win32_init(void) /* wVersionRequested in wVersion. wHighVersion contains the */ /* highest supported version. */ - if(LOBYTE( wsaData.wVersion ) != LOBYTE(wVersionRequested) || - HIBYTE( wsaData.wVersion ) != HIBYTE(wVersionRequested) ) { + if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) || + HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested) ) { /* Tell the user that we couldn't find a useable */ /* winsock.dll. */ @@ -220,20 +220,22 @@ curl_calloc_callback Curl_ccalloc; * curl_global_init() globally initializes cURL given a bitwise set of the * different features of what to initialize. */ -CURLcode curl_global_init(long flags) +static CURLcode global_init(long flags, bool memoryfuncs) { if(initialized++) return CURLE_OK; - /* Setup the default memory functions here (again) */ - Curl_cmalloc = (curl_malloc_callback)malloc; - Curl_cfree = (curl_free_callback)free; - Curl_crealloc = (curl_realloc_callback)realloc; - Curl_cstrdup = (curl_strdup_callback)system_strdup; - Curl_ccalloc = (curl_calloc_callback)calloc; + if(memoryfuncs) { + /* Setup the default memory functions here (again) */ + Curl_cmalloc = (curl_malloc_callback)malloc; + Curl_cfree = (curl_free_callback)free; + Curl_crealloc = (curl_realloc_callback)realloc; + Curl_cstrdup = (curl_strdup_callback)system_strdup; + Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) - Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; + Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif + } if(flags & CURL_GLOBAL_SSL) if(!Curl_ssl_init()) { @@ -269,6 +271,8 @@ CURLcode curl_global_init(long flags) return CURLE_FAILED_INIT; } + (void)Curl_ipv6works(); + #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_INIT) if(libssh2_init(0)) { DEBUGF(fprintf(stderr, "Error: libssh2_init failed\n")); @@ -279,11 +283,23 @@ CURLcode curl_global_init(long flags) if(flags & CURL_GLOBAL_ACK_EINTR) Curl_ack_eintr = 1; - init_flags = flags; + init_flags = flags; + + Curl_version_init(); return CURLE_OK; } + +/** + * curl_global_init() globally initializes cURL given a bitwise set of the + * different features of what to initialize. + */ +CURLcode curl_global_init(long flags) +{ + return global_init(flags, TRUE); +} + /* * curl_global_init_mem() globally initializes cURL and also registers the * user provided callback routines. @@ -292,8 +308,6 @@ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c) { - CURLcode result = CURLE_OK; - /* Invalid input, return immediately */ if(!m || !f || !r || !s || !c) return CURLE_FAILED_INIT; @@ -306,17 +320,16 @@ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, return CURLE_OK; } - /* Call the actual init function first */ - result = curl_global_init(flags); - if(!result) { - Curl_cmalloc = m; - Curl_cfree = f; - Curl_cstrdup = s; - Curl_crealloc = r; - Curl_ccalloc = c; - } + /* set memory functions before global_init() in case it wants memory + functions */ + Curl_cmalloc = m; + Curl_cfree = f; + Curl_cstrdup = s; + Curl_crealloc = r; + Curl_ccalloc = c; - return result; + /* Call the actual init function, but without setting */ + return global_init(flags, FALSE); } /** @@ -354,10 +367,10 @@ void curl_global_cleanup(void) * curl_easy_init() is the external interface to alloc, setup and init an * easy handle that is returned. If anything goes wrong, NULL is returned. */ -CURL *curl_easy_init(void) +struct Curl_easy *curl_easy_init(void) { CURLcode result; - struct SessionHandle *data; + struct Curl_easy *data; /* Make sure we inited the global SSL stuff */ if(!initialized) { @@ -385,13 +398,12 @@ CURL *curl_easy_init(void) */ #undef curl_easy_setopt -CURLcode curl_easy_setopt(CURL *curl, CURLoption tag, ...) +CURLcode curl_easy_setopt(struct Curl_easy *data, CURLoption tag, ...) { va_list arg; - struct SessionHandle *data = curl; CURLcode result; - if(!curl) + if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; va_start(arg, tag); @@ -423,7 +435,7 @@ struct events { * updated. */ -static int events_timer(CURLM *multi, /* multi handle */ +static int events_timer(struct Curl_multi *multi, /* multi handle */ long timeout_ms, /* see above */ void *userp) /* private callback pointer */ { @@ -478,7 +490,7 @@ static short socketcb2poll(int pollmask) * Callback that gets called with information about socket activity to * monitor. */ -static int events_socket(CURL *easy, /* easy handle */ +static int events_socket(struct Curl_easy *easy, /* easy handle */ curl_socket_t s, /* socket */ int what, /* see above */ void *userp, /* private callback @@ -532,14 +544,18 @@ static int events_socket(CURL *easy, /* easy handle */ } else { m = malloc(sizeof(struct socketmonitor)); - m->next = ev->list; - m->socket.fd = s; - m->socket.events = socketcb2poll(what); - m->socket.revents = 0; - ev->list = m; - infof(easy, "socket cb: socket %d ADDED as %s%s\n", s, - what&CURL_POLL_IN?"IN":"", - what&CURL_POLL_OUT?"OUT":""); + if(m) { + m->next = ev->list; + m->socket.fd = s; + m->socket.events = socketcb2poll(what); + m->socket.revents = 0; + ev->list = m; + infof(easy, "socket cb: socket %d ADDED as %s%s\n", s, + what&CURL_POLL_IN?"IN":"", + what&CURL_POLL_OUT?"OUT":""); + } + else + return CURLE_OUT_OF_MEMORY; } } @@ -552,7 +568,7 @@ static int events_socket(CURL *easy, /* easy handle */ * * Do the multi handle setups that only event-based transfers need. */ -static void events_setup(CURLM *multi, struct events *ev) +static void events_setup(struct Curl_multi *multi, struct events *ev) { /* timer callback */ curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer); @@ -609,7 +625,7 @@ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) if(0 == pollrc) { /* timeout! */ ev->ms = 0; - /* fprintf(stderr, "call curl_multi_socket_action( TIMEOUT )\n"); */ + /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */ mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, &ev->running_handles); } @@ -619,7 +635,7 @@ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) if(fds[i].revents) { /* socket activity, tell libcurl */ int act = poll2cselect(fds[i].revents); /* convert */ - infof(multi->easyp, "call curl_multi_socket_action( socket %d )\n", + infof(multi->easyp, "call curl_multi_socket_action(socket %d)\n", fds[i].fd); mcode = curl_multi_socket_action(multi, fds[i].fd, act, &ev->running_handles); @@ -656,7 +672,7 @@ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) * * Runs a transfer in a blocking manner using the events-based API */ -static CURLcode easy_events(CURLM *multi) +static CURLcode easy_events(struct Curl_multi *multi) { struct events evs= {2, FALSE, 0, NULL, 0}; @@ -670,7 +686,7 @@ static CURLcode easy_events(CURLM *multi) #define easy_events(x) CURLE_NOT_BUILT_IN #endif -static CURLcode easy_transfer(CURLM *multi) +static CURLcode easy_transfer(struct Curl_multi *multi) { bool done = FALSE; CURLMcode mcode = CURLM_OK; @@ -681,26 +697,22 @@ static CURLcode easy_transfer(CURLM *multi) while(!done && !mcode) { int still_running = 0; - int ret; + int rc; before = curlx_tvnow(); - mcode = curl_multi_wait(multi, NULL, 0, 1000, &ret); + mcode = curl_multi_wait(multi, NULL, 0, 1000, &rc); - if(mcode == CURLM_OK) { - if(ret == -1) { - /* poll() failed not on EINTR, indicate a network problem */ - result = CURLE_RECV_ERROR; - break; - } - else if(ret == 0) { + if(!mcode) { + if(!rc) { struct timeval after = curlx_tvnow(); + /* If it returns without any filedescriptor instantly, we need to avoid busy-looping during periods where it has nothing particular to wait for */ if(curlx_tvdiff(after, before) <= 10) { without_fds++; if(without_fds > 2) { - int sleep_ms = without_fds < 10 ? (1 << (without_fds-1)): 1000; + int sleep_ms = without_fds < 10 ? (1 << (without_fds - 1)) : 1000; Curl_wait_ms(sleep_ms); } } @@ -716,8 +728,7 @@ static CURLcode easy_transfer(CURLM *multi) } /* only read 'still_running' if curl_multi_perform() return OK */ - if((mcode == CURLM_OK) && !still_running) { - int rc; + if(!mcode && !still_running) { CURLMsg *msg = curl_multi_info_read(multi, &rc); if(msg) { result = msg->data.result; @@ -728,10 +739,10 @@ static CURLcode easy_transfer(CURLM *multi) /* Make sure to return some kind of error if there was a multi problem */ if(mcode) { - return (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : - /* The other multi errors should never happen, so return - something suitably generic */ - CURLE_BAD_FUNCTION_ARGUMENT; + result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : + /* The other multi errors should never happen, so return + something suitably generic */ + CURLE_BAD_FUNCTION_ARGUMENT; } return result; @@ -755,9 +766,9 @@ static CURLcode easy_transfer(CURLM *multi) * DEBUG: if 'events' is set TRUE, this function will use a replacement engine * instead of curl_multi_perform() and use curl_multi_socket_action(). */ -static CURLcode easy_perform(struct SessionHandle *data, bool events) +static CURLcode easy_perform(struct Curl_easy *data, bool events) { - CURLM *multi; + struct Curl_multi *multi; CURLMcode mcode; CURLcode result = CURLE_OK; SIGPIPE_VARIABLE(pipe_st); @@ -817,9 +828,9 @@ static CURLcode easy_perform(struct SessionHandle *data, bool events) * curl_easy_perform() is the external interface that performs a blocking * transfer as previously setup. */ -CURLcode curl_easy_perform(CURL *easy) +CURLcode curl_easy_perform(struct Curl_easy *data) { - return easy_perform(easy, FALSE); + return easy_perform(data, FALSE); } #ifdef CURLDEBUG @@ -827,9 +838,9 @@ CURLcode curl_easy_perform(CURL *easy) * curl_easy_perform_ev() is the external interface that performs a blocking * transfer using the event-based API internally. */ -CURLcode curl_easy_perform_ev(CURL *easy) +CURLcode curl_easy_perform_ev(struct Curl_easy *data) { - return easy_perform(easy, TRUE); + return easy_perform(data, TRUE); } #endif @@ -838,9 +849,8 @@ CURLcode curl_easy_perform_ev(CURL *easy) * curl_easy_cleanup() is the external interface to cleaning/freeing the given * easy handle. */ -void curl_easy_cleanup(CURL *curl) +void curl_easy_cleanup(struct Curl_easy *data) { - struct SessionHandle *data = (struct SessionHandle *)curl; SIGPIPE_VARIABLE(pipe_st); if(!data) @@ -856,12 +866,11 @@ void curl_easy_cleanup(CURL *curl) * information from a performed transfer and similar. */ #undef curl_easy_getinfo -CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...) +CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; void *paramp; CURLcode result; - struct SessionHandle *data = (struct SessionHandle *)curl; va_start(arg, info); paramp = va_arg(arg, void *); @@ -877,11 +886,9 @@ CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...) * given input easy handle. The returned handle will be a new working handle * with all options set exactly as the input source handle. */ -CURL *curl_easy_duphandle(CURL *incurl) +struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data) { - struct SessionHandle *data=(struct SessionHandle *)incurl; - - struct SessionHandle *outcurl = calloc(1, sizeof(struct SessionHandle)); + struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy)); if(NULL == outcurl) goto fail; @@ -972,10 +979,8 @@ CURL *curl_easy_duphandle(CURL *incurl) * curl_easy_reset() is an external interface that allows an app to re- * initialize a session handle to the default values. */ -void curl_easy_reset(CURL *curl) +void curl_easy_reset(struct Curl_easy *data) { - struct SessionHandle *data = (struct SessionHandle *)curl; - Curl_safefree(data->state.pathbuffer); data->state.path = NULL; @@ -1004,9 +1009,8 @@ void curl_easy_reset(CURL *curl) * * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h */ -CURLcode curl_easy_pause(CURL *curl, int action) +CURLcode curl_easy_pause(struct Curl_easy *data, int action) { - struct SessionHandle *data = (struct SessionHandle *)curl; struct SingleRequest *k = &data->req; CURLcode result = CURLE_OK; @@ -1046,7 +1050,7 @@ CURLcode curl_easy_pause(CURL *curl, int action) } -static CURLcode easy_connection(struct SessionHandle *data, +static CURLcode easy_connection(struct Curl_easy *data, curl_socket_t *sfd, struct connectdata **connp) { @@ -1074,13 +1078,13 @@ static CURLcode easy_connection(struct SessionHandle *data, * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. * Returns CURLE_OK on success, error code on error. */ -CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n) +CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen, + size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c; - struct SessionHandle *data = (struct SessionHandle *)curl; result = easy_connection(data, &sfd, &c); if(result) @@ -1101,14 +1105,13 @@ CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n) * Sends data over the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. */ -CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen, - size_t *n) +CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c = NULL; - struct SessionHandle *data = (struct SessionHandle *)curl; result = easy_connection(data, &sfd, &c); if(result) diff --git a/Utilities/cmcurl/lib/easyif.h b/Utilities/cmcurl/lib/easyif.h index 043ff43..f6132cc 100644 --- a/Utilities/cmcurl/lib/easyif.h +++ b/Utilities/cmcurl/lib/easyif.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,7 +26,7 @@ * Prototypes for library-wide functions provided by easy.c */ #ifdef CURLDEBUG -CURL_EXTERN CURLcode curl_easy_perform_ev(CURL *easy); +CURL_EXTERN CURLcode curl_easy_perform_ev(struct Curl_easy *easy); #endif #endif /* HEADER_CURL_EASYIF_H */ diff --git a/Utilities/cmcurl/lib/escape.c b/Utilities/cmcurl/lib/escape.c index 24abb93..04230b4 100644 --- a/Utilities/cmcurl/lib/escape.c +++ b/Utilities/cmcurl/lib/escape.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -31,15 +31,14 @@ #include "warnless.h" #include "non-ascii.h" #include "escape.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* Portable character check (remember EBCDIC). Do not use isalnum() because its behavior is altered by the current locale. - See http://tools.ietf.org/html/rfc3986#section-2.3 + See https://tools.ietf.org/html/rfc3986#section-2.3 */ static bool Curl_isunreserved(unsigned char in) { @@ -76,7 +75,8 @@ char *curl_unescape(const char *string, int length) return curl_easy_unescape(NULL, string, length, NULL); } -char *curl_easy_escape(CURL *handle, const char *string, int inlength) +char *curl_easy_escape(struct Curl_easy *data, const char *string, + int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; @@ -105,7 +105,7 @@ char *curl_easy_escape(CURL *handle, const char *string, int inlength) alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { - free( ns ); + free(ns); return NULL; } else { @@ -113,7 +113,7 @@ char *curl_easy_escape(CURL *handle, const char *string, int inlength) } } - result = Curl_convert_to_network(handle, &in, 1); + result = Curl_convert_to_network(data, &in, 1); if(result) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); @@ -140,7 +140,7 @@ char *curl_easy_escape(CURL *handle, const char *string, int inlength) * *olen. If length == 0, the length is assumed to be strlen(string). * */ -CURLcode Curl_urldecode(struct SessionHandle *data, +CURLcode Curl_urldecode(struct Curl_easy *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) @@ -207,13 +207,13 @@ CURLcode Curl_urldecode(struct SessionHandle *data, * If length == 0, the length is assumed to be strlen(string). * If olen == NULL, no output length is stored. */ -char *curl_easy_unescape(CURL *handle, const char *string, int length, - int *olen) +char *curl_easy_unescape(struct Curl_easy *data, const char *string, + int length, int *olen) { char *str = NULL; size_t inputlen = length; size_t outputlen; - CURLcode res = Curl_urldecode(handle, string, inputlen, &str, &outputlen, + CURLcode res = Curl_urldecode(data, string, inputlen, &str, &outputlen, FALSE); if(res) return NULL; diff --git a/Utilities/cmcurl/lib/escape.h b/Utilities/cmcurl/lib/escape.h index 731b136..638666f 100644 --- a/Utilities/cmcurl/lib/escape.h +++ b/Utilities/cmcurl/lib/escape.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,7 +24,7 @@ /* Escape and unescape URL encoding in strings. The functions return a new * allocated string or NULL if an error occurred. */ -CURLcode Curl_urldecode(struct SessionHandle *data, +CURLcode Curl_urldecode(struct Curl_easy *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_crlf); diff --git a/Utilities/cmcurl/lib/file.c b/Utilities/cmcurl/lib/file.c index 175b107..b534ec1 100644 --- a/Utilities/cmcurl/lib/file.c +++ b/Utilities/cmcurl/lib/file.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -61,9 +61,8 @@ #include "url.h" #include "parsedate.h" /* for the week day and month names */ #include "warnless.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -136,7 +135,7 @@ static CURLcode file_range(struct connectdata *conn) curl_off_t totalsize=-1; char *ptr; char *ptr2; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(data->state.use_range && data->state.range) { from=curlx_strtoofft(data->state.range, &ptr, 0); @@ -186,7 +185,7 @@ static CURLcode file_range(struct connectdata *conn) */ static CURLcode file_connect(struct connectdata *conn, bool *done) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char *real_path; struct FILEPROTO *file = data->req.protop; int fd; @@ -228,15 +227,19 @@ static CURLcode file_connect(struct connectdata *conn, bool *done) for(i=0; i < real_path_len; ++i) if(actual_path[i] == '/') actual_path[i] = '\\'; - else if(!actual_path[i]) /* binary zero */ + else if(!actual_path[i]) { /* binary zero */ + Curl_safefree(real_path); return CURLE_URL_MALFORMAT; + } fd = open_readonly(actual_path, O_RDONLY|O_BINARY); file->path = actual_path; #else - if(memchr(real_path, 0, real_path_len)) + if(memchr(real_path, 0, real_path_len)) { /* binary zeroes indicate foul play */ + Curl_safefree(real_path); return CURLE_URL_MALFORMAT; + } fd = open_readonly(real_path, O_RDONLY); file->path = real_path; @@ -302,7 +305,7 @@ static CURLcode file_upload(struct connectdata *conn) int fd; int mode; CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char *buf = data->state.buffer; size_t nread; size_t nwrite; @@ -368,7 +371,7 @@ static CURLcode file_upload(struct connectdata *conn) /*skip bytes before resume point*/ if(data->state.resume_from) { - if((curl_off_t)nread <= data->state.resume_from ) { + if((curl_off_t)nread <= data->state.resume_from) { data->state.resume_from -= nread; nread = 0; buf2 = buf; @@ -426,9 +429,10 @@ static CURLcode file_do(struct connectdata *conn, bool *done) Windows version to have a different struct without having to redefine the simple word 'stat' */ curl_off_t expected_size=0; + bool size_known; bool fstated=FALSE; ssize_t nread; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char *buf = data->state.buffer; curl_off_t bytecount = 0; int fd; @@ -468,6 +472,9 @@ static CURLcode file_do(struct connectdata *conn, bool *done) information. Which for FILE can't be much more than the file size and date. */ if(data->set.opt_no_body && data->set.include_header && fstated) { + time_t filetime; + struct tm buffer; + const struct tm *tm = &buffer; snprintf(buf, sizeof(data->state.buffer), "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", expected_size); result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0); @@ -479,29 +486,24 @@ static CURLcode file_do(struct connectdata *conn, bool *done) if(result) return result; - if(fstated) { - time_t filetime = (time_t)statbuf.st_mtime; - struct tm buffer; - const struct tm *tm = &buffer; - result = Curl_gmtime(filetime, &buffer); - if(result) - return result; - - /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ - snprintf(buf, BUFSIZE-1, - "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", - Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], - tm->tm_mday, - Curl_month[tm->tm_mon], - tm->tm_year + 1900, - tm->tm_hour, - tm->tm_min, - tm->tm_sec); - result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0); - } - /* if we fstat()ed the file, set the file size to make it available post- - transfer */ - if(fstated) + filetime = (time_t)statbuf.st_mtime; + result = Curl_gmtime(filetime, &buffer); + if(result) + return result; + + /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ + snprintf(buf, BUFSIZE-1, + "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", + Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0); + if(!result) + /* set the file size to make it available post transfer */ Curl_pgrsSetDownloadSize(data, expected_size); return result; } @@ -531,8 +533,10 @@ static CURLcode file_do(struct connectdata *conn, bool *done) if(data->req.maxdownload > 0) expected_size = data->req.maxdownload; - if(fstated && (expected_size == 0)) - return CURLE_OK; + if(!fstated || (expected_size == 0)) + size_known = FALSE; + else + size_known = TRUE; /* The following is a shortcut implementation of file reading this is both more efficient than the former call to download() and @@ -551,20 +555,27 @@ static CURLcode file_do(struct connectdata *conn, bool *done) while(!result) { /* Don't fill a whole buffer if we want less than all data */ - size_t bytestoread = - (expected_size < CURL_OFF_T_C(BUFSIZE) - CURL_OFF_T_C(1)) ? - curlx_sotouz(expected_size) : BUFSIZE - 1; + size_t bytestoread; + + if(size_known) { + bytestoread = + (expected_size < CURL_OFF_T_C(BUFSIZE) - CURL_OFF_T_C(1)) ? + curlx_sotouz(expected_size) : BUFSIZE - 1; + } + else + bytestoread = BUFSIZE-1; nread = read(fd, buf, bytestoread); if(nread > 0) buf[nread] = 0; - if(nread <= 0 || expected_size == 0) + if(nread <= 0 || (size_known && (expected_size == 0))) break; bytecount += nread; - expected_size -= nread; + if(size_known) + expected_size -= nread; result = Curl_client_write(conn, CLIENTWRITE_BODY, buf, nread); if(result) diff --git a/Utilities/cmcurl/lib/file.h b/Utilities/cmcurl/lib/file.h index 997474b..c12ae0e 100644 --- a/Utilities/cmcurl/lib/file.h +++ b/Utilities/cmcurl/lib/file.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/fileinfo.c b/Utilities/cmcurl/lib/fileinfo.c index 0904937..144c65b 100644 --- a/Utilities/cmcurl/lib/fileinfo.c +++ b/Utilities/cmcurl/lib/fileinfo.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/fileinfo.h b/Utilities/cmcurl/lib/fileinfo.h index b0e5e59..5324f1a 100644 --- a/Utilities/cmcurl/lib/fileinfo.h +++ b/Utilities/cmcurl/lib/fileinfo.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/formdata.c b/Utilities/cmcurl/lib/formdata.c index 9e8ce4e..673759d 100644 --- a/Utilities/cmcurl/lib/formdata.c +++ b/Utilities/cmcurl/lib/formdata.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -30,15 +30,14 @@ #include <libgen.h> #endif -#include "urldata.h" /* for struct SessionHandle */ +#include "urldata.h" /* for struct Curl_easy */ #include "formdata.h" #include "vtls/vtls.h" #include "strequal.h" #include "sendf.h" #include "strdup.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -48,7 +47,7 @@ static char *Curl_basename(char *path); #endif static size_t readfromfile(struct Form *form, char *buffer, size_t size); -static char *formboundary(struct SessionHandle *data); +static char *formboundary(struct Curl_easy *data); /* What kind of Content-Type to use on un-specified files with unrecognized extensions. */ @@ -57,6 +56,14 @@ static char *formboundary(struct SessionHandle *data); #define FORM_FILE_SEPARATOR ',' #define FORM_TYPE_SEPARATOR ';' +#define HTTPPOST_PTRNAME CURL_HTTPPOST_PTRNAME +#define HTTPPOST_FILENAME CURL_HTTPPOST_FILENAME +#define HTTPPOST_PTRCONTENTS CURL_HTTPPOST_PTRCONTENTS +#define HTTPPOST_READFILE CURL_HTTPPOST_READFILE +#define HTTPPOST_PTRBUFFER CURL_HTTPPOST_PTRBUFFER +#define HTTPPOST_CALLBACK CURL_HTTPPOST_CALLBACK +#define HTTPPOST_BUFFER CURL_HTTPPOST_BUFFER + /*************************************************************************** * * AddHttpPost() @@ -69,7 +76,7 @@ static char *formboundary(struct SessionHandle *data); ***************************************************************************/ static struct curl_httppost * AddHttpPost(char *name, size_t namelength, - char *value, size_t contentslength, + char *value, curl_off_t contentslength, char *buffer, size_t bufferlength, char *contenttype, long flags, @@ -85,14 +92,14 @@ AddHttpPost(char *name, size_t namelength, post->name = name; post->namelength = (long)(name?(namelength?namelength:strlen(name)):0); post->contents = value; - post->contentslength = (long)contentslength; + post->contentlen = contentslength; post->buffer = buffer; post->bufferlength = (long)bufferlength; post->contenttype = contenttype; post->contentheader = contentHeader; post->showfilename = showfilename; post->userp = userp, - post->flags = flags; + post->flags = flags | CURL_HTTPPOST_LARGE; } else return NULL; @@ -372,11 +379,14 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost, } break; case CURLFORM_CONTENTSLENGTH: - if(current_form->contentslength) - return_value = CURL_FORMADD_OPTION_TWICE; - else - current_form->contentslength = - array_state?(size_t)array_value:(size_t)va_arg(params, long); + current_form->contentslength = + array_state?(size_t)array_value:(size_t)va_arg(params, long); + break; + + case CURLFORM_CONTENTLEN: + current_form->flags |= CURL_HTTPPOST_LARGE; + current_form->contentslength = + array_state?(curl_off_t)(size_t)array_value:va_arg(params, curl_off_t); break; /* Get contents from a given file name */ @@ -538,7 +548,7 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost, /* this "cast increases required alignment of target type" but we consider it OK anyway */ struct curl_slist* list = array_state? - (struct curl_slist*)array_value: + (struct curl_slist*)(void*)array_value: va_arg(params, struct curl_slist*); if(current_form->contentheader) @@ -621,7 +631,7 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost, else { if(((form->flags & HTTPPOST_FILENAME) || (form->flags & HTTPPOST_BUFFER)) && - !form->contenttype ) { + !form->contenttype) { char *f = form->flags & HTTPPOST_BUFFER? form->showfilename : form->value; @@ -653,9 +663,12 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost, HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER | HTTPPOST_CALLBACK)) && form->value) { /* copy value (without strdup; possibly contains null characters) */ - form->value = Curl_memdup(form->value, form->contentslength? - form->contentslength: - strlen(form->value)+1); + size_t clen = (size_t) form->contentslength; + if(!clen) + clen = strlen(form->value)+1; + + form->value = Curl_memdup(form->value, clen); + if(!form->value) { return_value = CURL_FORMADD_MEMORY; break; @@ -756,7 +769,7 @@ curl_off_t VmsRealFileSize(const char * name, int ret_stat; FILE * file; - file = fopen(name, "r"); /* VMS */ + file = fopen(name, FOPEN_READTEXT); /* VMS */ if(file == NULL) return 0; @@ -808,10 +821,16 @@ static curl_off_t VmsSpecialSize(const char * name, static CURLcode AddFormData(struct FormData **formp, enum formtype type, const void *line, - size_t length, + curl_off_t length, curl_off_t *size) { - struct FormData *newform = malloc(sizeof(struct FormData)); + struct FormData *newform; + char *alloc2 = NULL; + CURLcode result = CURLE_OK; + if(length < 0 || (size && *size < 0)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + newform = malloc(sizeof(struct FormData)); if(!newform) return CURLE_OUT_OF_MEMORY; newform->next = NULL; @@ -820,15 +839,22 @@ static CURLcode AddFormData(struct FormData **formp, /* we make it easier for plain strings: */ if(!length) length = strlen((char *)line); +#if (SIZEOF_SIZE_T < CURL_SIZEOF_CURL_OFF_T) + else if(length >= (curl_off_t)(size_t)-1) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } +#endif - newform->line = malloc(length+1); + newform->line = malloc((size_t)length+1); if(!newform->line) { - free(newform); - return CURLE_OUT_OF_MEMORY; + result = CURLE_OUT_OF_MEMORY; + goto error; } - memcpy(newform->line, line, length); - newform->length = length; - newform->line[length]=0; /* zero terminate for easier debugging */ + alloc2 = newform->line; + memcpy(newform->line, line, (size_t)length); + newform->length = (size_t)length; + newform->line[(size_t)length]=0; /* zero terminate for easier debugging */ } else /* For callbacks and files we don't have any actual data so we just keep a @@ -856,12 +882,20 @@ static CURLcode AddFormData(struct FormData **formp, struct_stat file; if(!stat(newform->line, &file) && !S_ISDIR(file.st_mode)) *size += filesize(newform->line, file); - else - return CURLE_BAD_FUNCTION_ARGUMENT; + else { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } } } } return CURLE_OK; + error: + if(newform) + free(newform); + if(alloc2) + free(alloc2); + return result; } /* @@ -1102,7 +1136,7 @@ static CURLcode formdata_add_filename(const struct curl_httppost *file, * a NULL pointer in the 'data' argument. */ -CURLcode Curl_getformdata(struct SessionHandle *data, +CURLcode Curl_getformdata(struct Curl_easy *data, struct FormData **finalform, struct curl_httppost *post, const char *custom_content_type, @@ -1238,7 +1272,7 @@ CURLcode Curl_getformdata(struct SessionHandle *data, curList = file->contentheader; while(curList) { /* Process the additional headers specified for this form */ - result = AddFormDataf( &form, &size, "\r\n%s", curList->data ); + result = AddFormDataf(&form, &size, "\r\n%s", curList->data); if(result) break; curList = curList->next; @@ -1298,15 +1332,16 @@ CURLcode Curl_getformdata(struct SessionHandle *data, result = AddFormData(&form, FORM_CONTENT, post->buffer, post->bufferlength, &size); else if(post->flags & HTTPPOST_CALLBACK) - /* the contents should be read with the callback and the size - is set with the contentslength */ + /* the contents should be read with the callback and the size is set + with the contentslength */ result = AddFormData(&form, FORM_CALLBACK, post->userp, - post->contentslength, &size); + post->flags&CURL_HTTPPOST_LARGE? + post->contentlen:post->contentslength, &size); else /* include the contents we got */ result = AddFormData(&form, FORM_CONTENT, post->contents, - post->contentslength, &size); - + post->flags&CURL_HTTPPOST_LARGE? + post->contentlen:post->contentslength, &size); file = file->more; } while(file && !result); /* for each specified file for this field */ @@ -1350,7 +1385,7 @@ CURLcode Curl_getformdata(struct SessionHandle *data, * Curl_FormInit() inits the struct 'form' points to with the 'formdata' * and resets the 'sent' counter. */ -int Curl_FormInit(struct Form *form, struct FormData *formdata ) +int Curl_FormInit(struct Form *form, struct FormData *formdata) { if(!formdata) return 1; /* error */ @@ -1385,10 +1420,10 @@ static FILE * vmsfopenread(const char *file, const char *mode) { case FAB$C_VAR: case FAB$C_VFC: case FAB$C_STMCR: - return fopen(file, "r"); /* VMS */ + return fopen(file, FOPEN_READTEXT); /* VMS */ break; default: - return fopen(file, "r", "rfm=stmlf", "ctx=stm"); + return fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm"); } } #endif @@ -1463,9 +1498,9 @@ size_t Curl_FormReader(char *buffer, } do { - if((form->data->length - form->sent ) > wantedsize - gotsize) { + if((form->data->length - form->sent) > wantedsize - gotsize) { - memcpy(buffer + gotsize , form->data->line + form->sent, + memcpy(buffer + gotsize, form->data->line + form->sent, wantedsize - gotsize); form->sent += wantedsize-gotsize; @@ -1514,7 +1549,7 @@ char *Curl_formpostheader(void *formp, size_t *len) * formboundary() creates a suitable boundary string and returns an allocated * one. */ -static char *formboundary(struct SessionHandle *data) +static char *formboundary(struct Curl_easy *data) { /* 24 dashes and 16 hexadecimal digits makes 64 bit (18446744073709551615) combinations */ diff --git a/Utilities/cmcurl/lib/formdata.h b/Utilities/cmcurl/lib/formdata.h index 22f504b..6eb7c6c 100644 --- a/Utilities/cmcurl/lib/formdata.h +++ b/Utilities/cmcurl/lib/formdata.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -54,7 +54,7 @@ typedef struct FormInfo { size_t namelength; char *value; bool value_alloc; - size_t contentslength; + curl_off_t contentslength; char *contenttype; bool contenttype_alloc; long flags; @@ -68,9 +68,9 @@ typedef struct FormInfo { struct FormInfo *more; } FormInfo; -int Curl_FormInit(struct Form *form, struct FormData *formdata ); +int Curl_FormInit(struct Form *form, struct FormData *formdata); -CURLcode Curl_getformdata(struct SessionHandle *data, +CURLcode Curl_getformdata(struct Curl_easy *data, struct FormData **, struct curl_httppost *post, const char *custom_contenttype, @@ -93,6 +93,6 @@ char *Curl_FormBoundary(void); void Curl_formclean(struct FormData **); -CURLcode Curl_formconvert(struct SessionHandle *, struct FormData *); +CURLcode Curl_formconvert(struct Curl_easy *, struct FormData *); #endif /* HEADER_CURL_FORMDATA_H */ diff --git a/Utilities/cmcurl/lib/ftp.c b/Utilities/cmcurl/lib/ftp.c index 29c840c..b0165bc 100644 --- a/Utilities/cmcurl/lib/ftp.c +++ b/Utilities/cmcurl/lib/ftp.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -77,10 +77,9 @@ #include "warnless.h" #include "http_proxy.h" #include "non-ascii.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" #ifndef NI_MAXHOST @@ -155,8 +154,9 @@ static CURLcode ftp_dophase_done(struct connectdata *conn, bool connected); /* easy-to-use macro: */ -#define PPSENDF(x,y,z) if((result = Curl_pp_sendf(x,y,z))) \ - return result +#define PPSENDF(x,y,z) result = Curl_pp_sendf(x,y,z); \ + if(result) \ + return result /* @@ -265,6 +265,15 @@ static const struct Curl_handler Curl_handler_ftps_proxy = { #endif #endif +static void close_secondarysocket(struct connectdata *conn) +{ + if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) { + Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); + conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; + } + conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE; + conn->tunnel_state[SECONDARYSOCKET] = TUNNEL_INIT; +} /* * NOTE: back in the old days, we added code in the FTP code that made NOBODY @@ -318,7 +327,7 @@ static bool isBadFtpString(const char *string) */ static CURLcode AcceptServerConnect(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sock = conn->sock[SECONDARYSOCKET]; curl_socket_t s = CURL_SOCKET_BAD; #ifdef ENABLE_IPV6 @@ -340,6 +349,9 @@ static CURLcode AcceptServerConnect(struct connectdata *conn) return CURLE_FTP_PORT_FAILED; } infof(data, "Connection accepted from server\n"); + /* when this happens within the DO state it is important that we mark us as + not needing DO_MORE anymore */ + conn->bits.do_more = FALSE; conn->sock[SECONDARYSOCKET] = s; (void)curlx_nonblock(s, TRUE); /* enable non-blocking */ @@ -354,8 +366,7 @@ static CURLcode AcceptServerConnect(struct connectdata *conn) CURLSOCKTYPE_ACCEPT); if(error) { - Curl_closesocket(conn, s); /* close the socket and bail out */ - conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; + close_secondarysocket(conn); return CURLE_ABORTED_BY_CALLBACK; } } @@ -373,7 +384,7 @@ static CURLcode AcceptServerConnect(struct connectdata *conn) * Curl_pgrsTime(..., TIMER_STARTACCEPT); * */ -static long ftp_timeleft_accept(struct SessionHandle *data) +static long ftp_timeleft_accept(struct Curl_easy *data) { long timeout_ms = DEFAULT_ACCEPT_TIMEOUT; long other; @@ -413,7 +424,7 @@ static long ftp_timeleft_accept(struct SessionHandle *data) */ static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET]; curl_socket_t data_sock = conn->sock[SECONDARYSOCKET]; struct ftp_conn *ftpc = &conn->proto.ftpc; @@ -484,7 +495,7 @@ static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received) */ static CURLcode InitiateTransfer(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; CURLcode result = CURLE_OK; @@ -535,7 +546,7 @@ static CURLcode InitiateTransfer(struct connectdata *conn) */ static CURLcode AllowServerConnect(struct connectdata *conn, bool *connected) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; long timeout_ms; CURLcode result = CURLE_OK; @@ -606,7 +617,7 @@ static CURLcode ftp_readresp(curl_socket_t sockfd, size_t *size) /* size of the response */ { struct connectdata *conn = pp->conn; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; #ifdef HAVE_GSSAPI char * const buf = data->state.buffer; #endif @@ -678,7 +689,7 @@ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */ curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; long timeout; /* timeout in milliseconds */ long interval_ms; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; @@ -698,7 +709,7 @@ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */ /* check and reset timeout value every lap */ timeout = Curl_pp_state_timeout(pp); - if(timeout <=0 ) { + if(timeout <=0) { failf(data, "FTP response timeout"); return CURLE_OPERATION_TIMEDOUT; /* already too little time */ } @@ -969,7 +980,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn, { CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; curl_socket_t portsock= CURL_SOCKET_BAD; char myhost[256] = ""; @@ -1024,7 +1035,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn, if(*string_ftpport == '[') { /* [ipv6]:port(-range) */ ip_start = string_ftpport + 1; - if((ip_end = strchr(string_ftpport, ']')) != NULL ) + if((ip_end = strchr(string_ftpport, ']')) != NULL) strncpy(addr, ip_start, ip_end - ip_start); } else @@ -1045,7 +1056,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn, else #endif /* (ipv4|domain|interface):port(-range) */ - strncpy(addr, string_ftpport, ip_end - ip_start ); + strncpy(addr, string_ftpport, ip_end - ip_start); } else /* ipv4|interface */ @@ -1065,11 +1076,11 @@ static CURLcode ftp_state_use_port(struct connectdata *conn, /* correct errors like: * :1234-1230 - * :-4711 , in this case port_min is (unsigned)-1, + * :-4711, in this case port_min is (unsigned)-1, * therefore port_min > port_max for all cases * but port_max = (unsigned)-1 */ - if(port_min > port_max ) + if(port_min > port_max) port_min = port_max = 0; @@ -1322,11 +1333,11 @@ static CURLcode ftp_state_use_port(struct connectdata *conn, /* store which command was sent */ ftpc->count1 = fcmd; + close_secondarysocket(conn); + /* we set the secondary socket variable to this for now, it is only so that the cleanup function will close it in case we fail before the true secondary stuff is made */ - if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) - Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); conn->sock[SECONDARYSOCKET] = portsock; /* this tcpconnect assignment below is a hackish work-around to make the @@ -1392,7 +1403,7 @@ static CURLcode ftp_state_prepare_transfer(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(ftp->transfer != FTPTRANSFER_BODY) { /* doesn't transfer any data */ @@ -1475,7 +1486,7 @@ static CURLcode ftp_state_size(struct connectdata *conn) static CURLcode ftp_state_list(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* If this output is to be machine-parsed, the NLST command might be better to use, since the LIST command output is not specified or standard in any @@ -1513,12 +1524,12 @@ static CURLcode ftp_state_list(struct connectdata *conn) } } - cmd = aprintf( "%s%s%s", - data->set.str[STRING_CUSTOMREQUEST]? - data->set.str[STRING_CUSTOMREQUEST]: - (data->set.ftp_list_only?"NLST":"LIST"), - lstArg? " ": "", - lstArg? lstArg: "" ); + cmd = aprintf("%s%s%s", + data->set.str[STRING_CUSTOMREQUEST]? + data->set.str[STRING_CUSTOMREQUEST]: + (data->set.ftp_list_only?"NLST":"LIST"), + lstArg? " ": "", + lstArg? lstArg: ""); if(!cmd) { free(lstArg); @@ -1564,7 +1575,7 @@ static CURLcode ftp_state_type(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; /* If we have selected NOBODY and HEADER, it means that we only want file @@ -1596,7 +1607,7 @@ static CURLcode ftp_state_type(struct connectdata *conn) static CURLcode ftp_state_mdtm(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; /* Requested time of file or time-depended transfer? */ @@ -1621,7 +1632,7 @@ static CURLcode ftp_state_ul_setup(struct connectdata *conn, { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; int seekerr = CURL_SEEKFUNC_OK; @@ -1640,7 +1651,7 @@ static CURLcode ftp_state_ul_setup(struct connectdata *conn, /* 4. lower the infilesize counter */ /* => transfer as usual */ - if(data->state.resume_from < 0 ) { + if(data->state.resume_from < 0) { /* Got no given size to start from, figure it out */ PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); state(conn, FTP_STOR_SIZE); @@ -1670,8 +1681,8 @@ static CURLcode ftp_state_ul_setup(struct connectdata *conn, BUFSIZE : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = - data->set.fread_func(data->state.buffer, 1, readthisamountnow, - data->set.in); + data->state.fread_func(data->state.buffer, 1, readthisamountnow, + data->state.in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { @@ -1717,7 +1728,7 @@ static CURLcode ftp_state_quote(struct connectdata *conn, ftpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; bool quote=FALSE; @@ -1787,8 +1798,20 @@ static CURLcode ftp_state_quote(struct connectdata *conn, result = ftp_state_retr(conn, ftpc->known_filesize); } else { - PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); - state(conn, FTP_RETR_SIZE); + if(data->set.ignorecl) { + /* This code is to support download of growing files. It prevents + the state machine from requesting the file size from the + server. With an unknown file size the download continues until + the server terminates it, otherwise the client stops if the + received byte count exceeds the reported file size. Set option + CURLOPT_IGNORE_CONTENT_LENGTH to 1 to enable this behavior.*/ + PPSENDF(&ftpc->pp, "RETR %s", ftpc->file); + state(conn, FTP_RETR); + } + else { + PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); + state(conn, FTP_RETR_SIZE); + } } } break; @@ -1836,7 +1859,7 @@ static CURLcode proxy_magic(struct connectdata *conn, bool *magicdone) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; #if defined(CURL_DISABLE_PROXY) (void) newhost; @@ -1927,7 +1950,7 @@ static CURLcode ftp_state_pasv_resp(struct connectdata *conn, { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; struct Curl_dns_entry *addr=NULL; int rc; unsigned short connectport; /* the local port connect() should use! */ @@ -2102,7 +2125,7 @@ static CURLcode ftp_state_pasv_resp(struct connectdata *conn, static CURLcode ftp_state_port_resp(struct connectdata *conn, int ftpcode) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; ftpport fcmd = (ftpport)ftpc->count1; CURLcode result = CURLE_OK; @@ -2139,7 +2162,7 @@ static CURLcode ftp_state_mdtm_resp(struct connectdata *conn, int ftpcode) { CURLcode result = CURLE_OK; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; @@ -2244,7 +2267,7 @@ static CURLcode ftp_state_type_resp(struct connectdata *conn, ftpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; if(ftpcode/100 != 2) { /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a @@ -2273,7 +2296,7 @@ static CURLcode ftp_state_retr(struct connectdata *conn, curl_off_t filesize) { CURLcode result = CURLE_OK; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; @@ -2356,7 +2379,7 @@ static CURLcode ftp_state_size_resp(struct connectdata *conn, ftpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; curl_off_t filesize; char *buf = data->state.buffer; @@ -2428,7 +2451,7 @@ static CURLcode ftp_state_stor_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(ftpcode>=400) { failf(data, "Failed FTP upload: %0d", ftpcode); @@ -2467,7 +2490,7 @@ static CURLcode ftp_state_get_resp(struct connectdata *conn, ftpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; char *buf = data->state.buffer; @@ -2624,7 +2647,7 @@ static CURLcode ftp_state_user_resp(struct connectdata *conn, ftpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; (void)instate; /* no use for this yet */ @@ -2679,7 +2702,7 @@ static CURLcode ftp_state_acct_resp(struct connectdata *conn, int ftpcode) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(ftpcode != 230) { failf(data, "ACCT rejected by server: %03d", ftpcode); result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */ @@ -2695,7 +2718,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn) { CURLcode result; curl_socket_t sock = conn->sock[FIRSTSOCKET]; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; int ftpcode; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; @@ -3218,9 +3241,9 @@ static CURLcode ftp_connect(struct connectdata *conn, * Input argument is already checked for validity. */ static CURLcode ftp_done(struct connectdata *conn, CURLcode status, - bool premature) + bool premature) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; @@ -3232,11 +3255,6 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status, const char *path_to_use = data->state.path; if(!ftp) - /* When the easy handle is removed from the multi while libcurl is still - * trying to resolve the host name, it seems that the ftp struct is not - * yet initialized, but the removal action calls Curl_done() which calls - * this function. So we simply return success if no ftp pointer is set. - */ return CURLE_OK; switch(status) { @@ -3345,11 +3363,7 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status, /* Note that we keep "use" set to TRUE since that (next) connection is still requested to use SSL */ } - if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) { - Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); - conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; - conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE; - } + close_secondarysocket(conn); } if(!result && (ftp->transfer == FTPTRANSFER_BODY) && ftpc->ctl_valid && @@ -3573,7 +3587,7 @@ static CURLcode ftp_range(struct connectdata *conn) curl_off_t from, to; char *ptr; char *ptr2; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; if(data->state.use_range && data->state.range) { @@ -3631,7 +3645,7 @@ static CURLcode ftp_range(struct connectdata *conn) static CURLcode ftp_do_more(struct connectdata *conn, int *completep) { - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result = CURLE_OK; bool connected = FALSE; @@ -3720,7 +3734,13 @@ static CURLcode ftp_do_more(struct connectdata *conn, int *completep) return result; result = ftp_multi_statemach(conn, &complete); - *completep = (int)complete; + if(ftpc->wait_data_conn) + /* if we reach the end of the FTP state machine here, *complete will be + TRUE but so is ftpc->wait_data_conn, which says we need to wait for + the data connection and therefore we're not actually complete */ + *completep = 0; + else + *completep = (int)complete; } else { /* download */ @@ -4190,7 +4210,7 @@ static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection) (void)ftp_quit(conn); /* ignore errors on the QUIT */ if(ftpc->entrypath) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) { data->state.most_recent_ftp_entrypath = NULL; } @@ -4223,7 +4243,7 @@ static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection) static CURLcode ftp_parse_url_path(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* the ftp struct is already inited in ftp_connect() */ struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; @@ -4249,16 +4269,17 @@ CURLcode ftp_parse_url_path(struct connectdata *conn) the first condition in the if() right here, is there just in case someone decides to set path to NULL one day */ - if(data->state.path && - data->state.path[0] && - (data->state.path[strlen(data->state.path) - 1] != '/') ) - filename = data->state.path; /* this is a full file path */ - /* + if(path_to_use[0] && + (path_to_use[strlen(path_to_use) - 1] != '/') ) + filename = path_to_use; /* this is a full file path */ + /* + else { ftpc->file is not used anywhere other than for operations on a file. In other words, never for directory operations. So we can safely leave filename as NULL here and use it as a argument in dir/file decisions. - */ + } + */ break; case FTPFILE_SINGLECWD: @@ -4423,11 +4444,7 @@ static CURLcode ftp_dophase_done(struct connectdata *conn, CURLcode result = ftp_do_more(conn, &completed); if(result) { - if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) { - /* close the second socket if it was created already */ - Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); - conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; - } + close_secondarysocket(conn); return result; } } @@ -4478,7 +4495,7 @@ CURLcode ftp_regular_transfer(struct connectdata *conn, { CURLcode result=CURLE_OK; bool connected=FALSE; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; data->req.size = -1; /* make sure this is unknown at this point */ @@ -4512,7 +4529,7 @@ CURLcode ftp_regular_transfer(struct connectdata *conn, static CURLcode ftp_setup_connection(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char *type; char command; struct FTP *ftp; diff --git a/Utilities/cmcurl/lib/ftp.h b/Utilities/cmcurl/lib/ftp.h index 833447b..2ed5b43 100644 --- a/Utilities/cmcurl/lib/ftp.h +++ b/Utilities/cmcurl/lib/ftp.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -97,9 +97,9 @@ typedef enum { file */ } curl_ftpfile; -/* This FTP struct is used in the SessionHandle. All FTP data that is +/* This FTP struct is used in the Curl_easy. All FTP data that is connection-oriented must be in FTP_conn to properly deal with the fact that - perhaps the SessionHandle is changed between the times the connection is + perhaps the Curl_easy is changed between the times the connection is used. */ struct FTP { curl_off_t *bytecountp; diff --git a/Utilities/cmcurl/lib/ftplistparser.c b/Utilities/cmcurl/lib/ftplistparser.c index 17e0a66..abbf76e 100644 --- a/Utilities/cmcurl/lib/ftplistparser.c +++ b/Utilities/cmcurl/lib/ftplistparser.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -275,26 +275,6 @@ static void PL_ERROR(struct connectdata *conn, CURLcode err) parser->error = err; } -static bool ftp_pl_gettime(struct ftp_parselist_data *parser, char *string) -{ - (void)parser; - (void)string; - /* TODO - * There could be possible parse timestamp from server. Leaving unimplemented - * for now. - * If you want implement this, please add CURLFINFOFLAG_KNOWN_TIME flag to - * parser->file_data->flags - * - * Ftp servers are giving usually these formats: - * Apr 11 1998 (unknown time.. set it to 00:00:00?) - * Apr 11 12:21 (unknown year -> set it to NOW() time?) - * 08-05-09 02:49PM (ms-dos format) - * 20100421092538 -> for MLST/MLSD response - */ - - return FALSE; -} - static CURLcode ftp_pl_insert_finfo(struct connectdata *conn, struct curl_fileinfo *finfo) { @@ -715,9 +695,11 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, if(c == ' ') { finfo->b_data[parser->item_offset + parser->item_length -1] = 0; parser->offsets.time = parser->item_offset; - if(ftp_pl_gettime(parser, finfo->b_data + parser->item_offset)) { - parser->file_data->flags |= CURLFINFOFLAG_KNOWN_TIME; - } + /* + if(ftp_pl_gettime(parser, finfo->b_data + parser->item_offset)) { + parser->file_data->flags |= CURLFINFOFLAG_KNOWN_TIME; + } + */ if(finfo->filetype == CURLFILETYPE_SYMLINK) { parser->state.UNIX.main = PL_UNIX_SYMLINK; parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRESPACE; @@ -746,7 +728,6 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, case PL_UNIX_FILENAME_NAME: parser->item_length++; if(c == '\r') { - parser->item_length--; parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_WINDOWSEOL; } else if(c == '\n') { @@ -762,7 +743,7 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, break; case PL_UNIX_FILENAME_WINDOWSEOL: if(c == '\n') { - finfo->b_data[parser->item_offset + parser->item_length] = 0; + finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.filename = parser->item_offset; parser->state.UNIX.main = PL_UNIX_FILETYPE; result = ftp_pl_insert_finfo(conn, finfo); @@ -853,9 +834,8 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, } break; case PL_UNIX_SYMLINK_TARGET: - parser->item_length ++; + parser->item_length++; if(c == '\r') { - parser->item_length --; parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_WINDOWSEOL; } else if(c == '\n') { diff --git a/Utilities/cmcurl/lib/ftplistparser.h b/Utilities/cmcurl/lib/ftplistparser.h index 96764e2..8128887 100644 --- a/Utilities/cmcurl/lib/ftplistparser.h +++ b/Utilities/cmcurl/lib/ftplistparser.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/getenv.c b/Utilities/cmcurl/lib/getenv.c index 36215aa..50bb79f 100644 --- a/Utilities/cmcurl/lib/getenv.c +++ b/Utilities/cmcurl/lib/getenv.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/getinfo.c b/Utilities/cmcurl/lib/getinfo.c index 910f520..262cd93 100644 --- a/Utilities/cmcurl/lib/getinfo.c +++ b/Utilities/cmcurl/lib/getinfo.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -39,7 +39,7 @@ * This is supposed to be called in the beginning of a perform() session * and should reset all session-info variables */ -CURLcode Curl_initinfo(struct SessionHandle *data) +CURLcode Curl_initinfo(struct Curl_easy *data) { struct Progress *pro = &data->progress; struct PureInfo *info = &data->info; @@ -73,7 +73,7 @@ CURLcode Curl_initinfo(struct SessionHandle *data) return CURLE_OK; } -static CURLcode getinfo_char(struct SessionHandle *data, CURLINFO info, +static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info, char **param_charp) { switch(info) { @@ -113,13 +113,13 @@ static CURLcode getinfo_char(struct SessionHandle *data, CURLINFO info, break; default: - return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } -static CURLcode getinfo_long(struct SessionHandle *data, CURLINFO info, +static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info, long *param_longp) { curl_socket_t sockfd; @@ -198,15 +198,31 @@ static CURLcode getinfo_long(struct SessionHandle *data, CURLINFO info, case CURLINFO_RTSP_CSEQ_RECV: *param_longp = data->state.rtsp_CSeq_recv; break; + case CURLINFO_HTTP_VERSION: + switch (data->info.httpversion) { + case 10: + *param_longp = CURL_HTTP_VERSION_1_0; + break; + case 11: + *param_longp = CURL_HTTP_VERSION_1_1; + break; + case 20: + *param_longp = CURL_HTTP_VERSION_2_0; + break; + default: + *param_longp = CURL_HTTP_VERSION_NONE; + break; + } + break; default: - return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } -static CURLcode getinfo_double(struct SessionHandle *data, CURLINFO info, +static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info, double *param_doublep) { switch(info) { @@ -253,13 +269,13 @@ static CURLcode getinfo_double(struct SessionHandle *data, CURLINFO info, break; default: - return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } -static CURLcode getinfo_slist(struct SessionHandle *data, CURLINFO info, +static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info, struct curl_slist **param_slistp) { union { @@ -281,69 +297,84 @@ static CURLcode getinfo_slist(struct SessionHandle *data, CURLINFO info, *param_slistp = ptr.to_slist; break; case CURLINFO_TLS_SESSION: + case CURLINFO_TLS_SSL_PTR: { struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **) param_slistp; struct curl_tlssessioninfo *tsi = &data->tsi; struct connectdata *conn = data->easy_conn; - unsigned int sockindex = 0; - void *internals = NULL; *tsip = tsi; - tsi->backend = CURLSSLBACKEND_NONE; + tsi->backend = Curl_ssl_backend(); tsi->internals = NULL; - if(!conn) - break; - - /* Find the active ("in use") SSL connection, if any */ - while((sockindex < sizeof(conn->ssl) / sizeof(conn->ssl[0])) && - (!conn->ssl[sockindex].use)) - sockindex++; - - if(sockindex == sizeof(conn->ssl) / sizeof(conn->ssl[0])) - break; /* no SSL session found */ - - /* Return the TLS session information from the relevant backend */ -#ifdef USE_OPENSSL - internals = conn->ssl[sockindex].ctx; + if(conn && tsi->backend != CURLSSLBACKEND_NONE) { + unsigned int i; + for(i = 0; i < (sizeof(conn->ssl) / sizeof(conn->ssl[0])); ++i) { + if(conn->ssl[i].use) { +#if defined(USE_AXTLS) + tsi->internals = (void *)conn->ssl[i].ssl; +#elif defined(USE_CYASSL) + tsi->internals = (void *)conn->ssl[i].handle; +#elif defined(USE_DARWINSSL) + tsi->internals = (void *)conn->ssl[i].ssl_ctx; +#elif defined(USE_GNUTLS) + tsi->internals = (void *)conn->ssl[i].session; +#elif defined(USE_GSKIT) + tsi->internals = (void *)conn->ssl[i].handle; +#elif defined(USE_MBEDTLS) + tsi->internals = (void *)&conn->ssl[i].ssl; +#elif defined(USE_NSS) + tsi->internals = (void *)conn->ssl[i].handle; +#elif defined(USE_OPENSSL) + /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */ + tsi->internals = ((info == CURLINFO_TLS_SESSION) ? + (void *)conn->ssl[i].ctx : + (void *)conn->ssl[i].handle); +#elif defined(USE_POLARSSL) + tsi->internals = (void *)&conn->ssl[i].ssl; +#elif defined(USE_SCHANNEL) + tsi->internals = (void *)&conn->ssl[i].ctxt->ctxt_handle; +#elif defined(USE_SSL) +#error "SSL backend specific information missing for CURLINFO_TLS_SSL_PTR" #endif -#ifdef USE_GNUTLS - internals = conn->ssl[sockindex].session; -#endif -#ifdef USE_NSS - internals = conn->ssl[sockindex].handle; -#endif -#ifdef USE_GSKIT - internals = conn->ssl[sockindex].handle; -#endif - if(internals) { - tsi->backend = Curl_ssl_backend(); - tsi->internals = internals; + break; + } + } } - /* NOTE: For other SSL backends, it is not immediately clear what data - to return from 'struct ssl_connect_data'; thus, for now we keep the - backend as CURLSSLBACKEND_NONE in those cases, which should be - interpreted as "not supported" */ } break; default: - return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_UNKNOWN_OPTION; + } + + return CURLE_OK; +} + +static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info, + curl_socket_t *param_socketp) +{ + switch(info) { + case CURLINFO_ACTIVESOCKET: + *param_socketp = Curl_getconnectinfo(data, NULL); + break; + default: + return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } -CURLcode Curl_getinfo(struct SessionHandle *data, CURLINFO info, ...) +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; long *param_longp = NULL; double *param_doublep = NULL; char **param_charp = NULL; struct curl_slist **param_slistp = NULL; + curl_socket_t *param_socketp = NULL; int type; - /* default return code is to error out! */ - CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; + CURLcode result = CURLE_UNKNOWN_OPTION; if(!data) return result; @@ -372,6 +403,11 @@ CURLcode Curl_getinfo(struct SessionHandle *data, CURLINFO info, ...) if(param_slistp) result = getinfo_slist(data, info, param_slistp); break; + case CURLINFO_SOCKET: + param_socketp = va_arg(arg, curl_socket_t *); + if(param_socketp) + result = getinfo_socket(data, info, param_socketp); + break; default: break; } diff --git a/Utilities/cmcurl/lib/getinfo.h b/Utilities/cmcurl/lib/getinfo.h index 3879ff7..aecf717 100644 --- a/Utilities/cmcurl/lib/getinfo.h +++ b/Utilities/cmcurl/lib/getinfo.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -21,7 +21,7 @@ * KIND, either express or implied. * ***************************************************************************/ -CURLcode Curl_getinfo(struct SessionHandle *data, CURLINFO info, ...); -CURLcode Curl_initinfo(struct SessionHandle *data); +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...); +CURLcode Curl_initinfo(struct Curl_easy *data); #endif /* HEADER_CURL_GETINFO_H */ diff --git a/Utilities/cmcurl/lib/gopher.c b/Utilities/cmcurl/lib/gopher.c index 954cad8..f1efb60 100644 --- a/Utilities/cmcurl/lib/gopher.c +++ b/Utilities/cmcurl/lib/gopher.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -75,7 +75,7 @@ const struct Curl_handler Curl_handler_gopher = { static CURLcode gopher_do(struct connectdata *conn, bool *done) { CURLcode result=CURLE_OK; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; curl_off_t *bytecount = &data->req.bytecount; @@ -83,16 +83,18 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done) char *sel; char *sel_org = NULL; ssize_t amount, k; + int len; *done = TRUE; /* unconditionally */ /* Create selector. Degenerate cases: / and /1 => convert to "" */ - if(strlen(path) <= 2) + if(strlen(path) <= 2) { sel = (char *)""; + len = (int)strlen(sel); + } else { char *newp; size_t j, i; - int len; /* Otherwise, drop / and the first character (i.e., item type) ... */ newp = path; @@ -113,7 +115,7 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done) /* We use Curl_write instead of Curl_sendf to make sure the entire buffer is sent, which could be sizeable with long selectors. */ - k = curlx_uztosz(strlen(sel)); + k = curlx_uztosz(len); for(;;) { result = Curl_write(conn, sockfd, sel, k, &amount); diff --git a/Utilities/cmcurl/lib/gopher.h b/Utilities/cmcurl/lib/gopher.h index 38bbc4b..501c990 100644 --- a/Utilities/cmcurl/lib/gopher.h +++ b/Utilities/cmcurl/lib/gopher.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/hash.c b/Utilities/cmcurl/lib/hash.c index c46760a..937381b 100644 --- a/Utilities/cmcurl/lib/hash.c +++ b/Utilities/cmcurl/lib/hash.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,9 +22,12 @@ #include "curl_setup.h" +#include <curl/curl.h> + #include "hash.h" #include "llist.h" #include "curl_memory.h" + /* The last #include file should be: */ #include "memdebug.h" @@ -46,7 +49,12 @@ hash_element_dtor(void *user, void *element) free(e); } -/* return 1 on error, 0 is fine */ +/* Initializes a hash structure. + * Return 1 on error, 0 is fine. + * + * @unittest: 1602 + * @unittest: 1603 + */ int Curl_hash_init(struct curl_hash *h, int slots, @@ -119,6 +127,8 @@ mk_hash_element(const void *key, size_t key_len, const void *p) * that data is replaced. * * @unittest: 1305 + * @unittest: 1602 + * @unittest: 1603 */ void * Curl_hash_add(struct curl_hash *h, void *key, size_t key_len, void *p) @@ -155,7 +165,11 @@ Curl_hash_add(struct curl_hash *h, void *key, size_t key_len, void *p) return NULL; /* failure */ } -/* remove the identified hash entry, returns non-zero on failure */ +/* Remove the identified hash entry. + * Returns non-zero on failure. + * + * @unittest: 1603 + */ int Curl_hash_delete(struct curl_hash *h, void *key, size_t key_len) { struct curl_llist_element *le; @@ -173,6 +187,10 @@ int Curl_hash_delete(struct curl_hash *h, void *key, size_t key_len) return 1; } +/* Retrieves a hash element. + * + * @unittest: 1603 + */ void * Curl_hash_pick(struct curl_hash *h, void *key, size_t key_len) { @@ -214,6 +232,10 @@ Curl_hash_apply(curl_hash *h, void *user, /* Destroys all the entries in the given hash and resets its attributes, * prepping the given hash for [static|dynamic] deallocation. + * + * @unittest: 1305 + * @unittest: 1602 + * @unittest: 1603 */ void Curl_hash_destroy(struct curl_hash *h) diff --git a/Utilities/cmcurl/lib/hash.h b/Utilities/cmcurl/lib/hash.h index b13a236..57a17f0 100644 --- a/Utilities/cmcurl/lib/hash.h +++ b/Utilities/cmcurl/lib/hash.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/hmac.c b/Utilities/cmcurl/lib/hmac.c index 0d2d5f4..3df4715 100644 --- a/Utilities/cmcurl/lib/hmac.c +++ b/Utilities/cmcurl/lib/hmac.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,8 +26,11 @@ #ifndef CURL_DISABLE_CRYPTO_AUTH +#include <curl/curl.h> + #include "curl_hmac.h" #include "curl_memory.h" + /* The last #include file should be: */ #include "memdebug.h" diff --git a/Utilities/cmcurl/lib/hostasyn.c b/Utilities/cmcurl/lib/hostasyn.c index 17b8be0..28bdf7a 100644 --- a/Utilities/cmcurl/lib/hostasyn.c +++ b/Utilities/cmcurl/lib/hostasyn.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -77,7 +77,7 @@ CURLcode Curl_addrinfo_callback(struct connectdata *conn, if(CURL_ASYNC_SUCCESS == status) { if(ai) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); diff --git a/Utilities/cmcurl/lib/hostcheck.c b/Utilities/cmcurl/lib/hostcheck.c index 62a26e4..4db9e6b 100644 --- a/Utilities/cmcurl/lib/hostcheck.c +++ b/Utilities/cmcurl/lib/hostcheck.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -43,7 +43,7 @@ * "foo.host.com" matches "*.host.com". * * We use the matching rule described in RFC6125, section 6.4.3. - * http://tools.ietf.org/html/rfc6125#section-6.4.3 + * https://tools.ietf.org/html/rfc6125#section-6.4.3 * * In addition: ignore trailing dots in the host names and wildcards, so that * the names are used normalized. This is what the browsers do. diff --git a/Utilities/cmcurl/lib/hostcheck.h b/Utilities/cmcurl/lib/hostcheck.h index f4a517a..86e3b96 100644 --- a/Utilities/cmcurl/lib/hostcheck.h +++ b/Utilities/cmcurl/lib/hostcheck.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/hostip.c b/Utilities/cmcurl/lib/hostip.c index 82f3897..f2d9841 100644 --- a/Utilities/cmcurl/lib/hostip.c +++ b/Utilities/cmcurl/lib/hostip.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -56,9 +56,9 @@ #include "url.h" #include "inet_ntop.h" #include "warnless.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" #if defined(CURLRES_SYNCH) && \ @@ -254,7 +254,7 @@ hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now) * Library-wide function for pruning the DNS cache. This function takes and * returns the appropriate locks. */ -void Curl_hostcache_prune(struct SessionHandle *data) +void Curl_hostcache_prune(struct Curl_easy *data) { time_t now; @@ -293,7 +293,7 @@ fetch_addr(struct connectdata *conn, char *entry_id = NULL; struct Curl_dns_entry *dns = NULL; size_t entry_len; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Create an entry id, based upon the hostname and port */ entry_id = create_hostcache_id(hostname, port); @@ -345,7 +345,7 @@ Curl_fetch_addr(struct connectdata *conn, const char *hostname, int port) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct Curl_dns_entry *dns = NULL; if(data->share) @@ -353,7 +353,8 @@ Curl_fetch_addr(struct connectdata *conn, dns = fetch_addr(conn, hostname, port); - if(dns) dns->inuse++; /* we use it! */ + if(dns) + dns->inuse++; /* we use it! */ if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); @@ -371,7 +372,7 @@ Curl_fetch_addr(struct connectdata *conn, * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. */ struct Curl_dns_entry * -Curl_cache_addr(struct SessionHandle *data, +Curl_cache_addr(struct Curl_easy *data, Curl_addrinfo *addr, const char *hostname, int port) @@ -446,7 +447,7 @@ int Curl_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { struct Curl_dns_entry *dns = NULL; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result; int rc = CURLRESOLV_ERROR; /* default to failure */ @@ -581,7 +582,7 @@ int Curl_resolv_timeout(struct connectdata *conn, #endif /* HAVE_SIGACTION */ volatile long timeout; volatile unsigned int prev_alarm = 0; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; #endif /* USE_ALARM_TIMEOUT */ int rc; @@ -715,7 +716,7 @@ clean_up: * * May be called with 'data' == NULL for global cache. */ -void Curl_resolv_unlock(struct SessionHandle *data, struct Curl_dns_entry *dns) +void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns) { if(data && data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); @@ -757,7 +758,7 @@ int Curl_mk_dnscache(struct curl_hash *hash) * can be done! */ -void Curl_hostcache_clean(struct SessionHandle *data, +void Curl_hostcache_clean(struct Curl_easy *data, struct curl_hash *hash) { if(data && data->share) @@ -770,14 +771,14 @@ void Curl_hostcache_clean(struct SessionHandle *data, } -CURLcode Curl_loadhostpairs(struct SessionHandle *data) +CURLcode Curl_loadhostpairs(struct Curl_easy *data) { struct curl_slist *hostp; char hostname[256]; char address[256]; int port; - for(hostp = data->change.resolve; hostp; hostp = hostp->next ) { + for(hostp = data->change.resolve; hostp; hostp = hostp->next) { if(!hostp->data) continue; if(hostp->data[0] == '-') { diff --git a/Utilities/cmcurl/lib/hostip.h b/Utilities/cmcurl/lib/hostip.h index d5b44bc..9098ee3 100644 --- a/Utilities/cmcurl/lib/hostip.h +++ b/Utilities/cmcurl/lib/hostip.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -50,7 +50,7 @@ struct addrinfo; struct hostent; -struct SessionHandle; +struct Curl_easy; struct connectdata; /* @@ -118,7 +118,7 @@ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, /* unlock a previously resolved dns entry */ -void Curl_resolv_unlock(struct SessionHandle *data, +void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns); /* for debugging purposes only: */ @@ -128,7 +128,7 @@ void Curl_scan_cache_used(void *user, void *ptr); int Curl_mk_dnscache(struct curl_hash *hash); /* prune old entries from the DNS cache */ -void Curl_hostcache_prune(struct SessionHandle *data); +void Curl_hostcache_prune(struct Curl_easy *data); /* Return # of adresses in a Curl_addrinfo struct */ int Curl_num_addresses (const Curl_addrinfo *addr); @@ -188,7 +188,7 @@ Curl_fetch_addr(struct connectdata *conn, * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. */ struct Curl_dns_entry * -Curl_cache_addr(struct SessionHandle *data, Curl_addrinfo *addr, +Curl_cache_addr(struct Curl_easy *data, Curl_addrinfo *addr, const char *hostname, int port); #ifndef INADDR_NONE @@ -209,42 +209,42 @@ extern sigjmp_buf curl_jmpenv; /* * Function provided by the resolver backend to set DNS servers to use. */ -CURLcode Curl_set_dns_servers(struct SessionHandle *data, char *servers); +CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers); /* * Function provided by the resolver backend to set * outgoing interface to use for DNS requests */ -CURLcode Curl_set_dns_interface(struct SessionHandle *data, +CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf); /* * Function provided by the resolver backend to set * local IPv4 address to use as source address for DNS requests */ -CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4); /* * Function provided by the resolver backend to set * local IPv6 address to use as source address for DNS requests */ -CURLcode Curl_set_dns_local_ip6(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6); /* * Clean off entries from the cache */ -void Curl_hostcache_clean(struct SessionHandle *data, struct curl_hash *hash); +void Curl_hostcache_clean(struct Curl_easy *data, struct curl_hash *hash); /* * Destroy the hostcache of this handle. */ -void Curl_hostcache_destroy(struct SessionHandle *data); +void Curl_hostcache_destroy(struct Curl_easy *data); /* * Populate the cache with specified entries from CURLOPT_RESOLVE. */ -CURLcode Curl_loadhostpairs(struct SessionHandle *data); +CURLcode Curl_loadhostpairs(struct Curl_easy *data); #endif /* HEADER_CURL_HOSTIP_H */ diff --git a/Utilities/cmcurl/lib/hostip4.c b/Utilities/cmcurl/lib/hostip4.c index 37b0369..15895d7 100644 --- a/Utilities/cmcurl/lib/hostip4.c +++ b/Utilities/cmcurl/lib/hostip4.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -48,9 +48,9 @@ #include "strerror.h" #include "url.h" #include "inet_pton.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /*********************************************************************** diff --git a/Utilities/cmcurl/lib/hostip6.c b/Utilities/cmcurl/lib/hostip6.c index 6ab131a..4ebfc2d 100644 --- a/Utilities/cmcurl/lib/hostip6.c +++ b/Utilities/cmcurl/lib/hostip6.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -49,9 +49,9 @@ #include "url.h" #include "inet_pton.h" #include "connect.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /*********************************************************************** @@ -59,7 +59,6 @@ **********************************************************************/ #ifdef CURLRES_IPV6 - #if defined(CURLDEBUG) && defined(HAVE_GETNAMEINFO) /* These are strictly for memory tracing and are using the same style as the * family otherwise present in memdebug.c. I put these ones here since they @@ -124,6 +123,7 @@ bool Curl_ipvalid(struct connectdata *conn) { if(conn->ip_version == CURL_IPRESOLVE_V6) return Curl_ipv6works(); + return TRUE; } @@ -167,15 +167,17 @@ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, int error; char sbuf[12]; char *sbufptr = NULL; +#ifndef USE_RESOLVE_ON_IPS char addrbuf[128]; +#endif int pf; - struct SessionHandle *data = conn->data; +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + struct Curl_easy *data = conn->data; +#endif *waitp = 0; /* synchronous response only */ - /* - * Check if a limited name resolve has been requested. - */ + /* Check if a limited name resolve has been requested */ switch(conn->ip_version) { case CURL_IPRESOLVE_V4: pf = PF_INET; @@ -196,26 +198,37 @@ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, hints.ai_family = pf; hints.ai_socktype = conn->socktype; +#ifndef USE_RESOLVE_ON_IPS + /* + * The AI_NUMERICHOST must not be set to get synthesized IPv6 address from + * an IPv4 address on iOS and Mac OS X. + */ if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) || (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) { /* the given address is numerical only, prevent a reverse lookup */ hints.ai_flags = AI_NUMERICHOST; } +#endif if(port) { snprintf(sbuf, sizeof(sbuf), "%d", port); sbufptr=sbuf; } + error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res); if(error) { infof(data, "getaddrinfo(3) failed for %s:%d\n", hostname, port); return NULL; } + if(port) { + Curl_addrinfo_set_port(res, port); + } + dump_addrinfo(conn, res); return res; } #endif /* CURLRES_SYNCH */ -#endif /* CURLRES_IPV6 */ +#endif /* CURLRES_IPV6 */ diff --git a/Utilities/cmcurl/lib/hostsyn.c b/Utilities/cmcurl/lib/hostsyn.c index fb1de35..1a95263 100644 --- a/Utilities/cmcurl/lib/hostsyn.c +++ b/Utilities/cmcurl/lib/hostsyn.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -59,7 +59,7 @@ /* * Function provided by the resolver backend to set DNS servers to use. */ -CURLcode Curl_set_dns_servers(struct SessionHandle *data, +CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers) { (void)data; @@ -72,7 +72,7 @@ CURLcode Curl_set_dns_servers(struct SessionHandle *data, * Function provided by the resolver backend to set * outgoing interface to use for DNS requests */ -CURLcode Curl_set_dns_interface(struct SessionHandle *data, +CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf) { (void)data; @@ -84,7 +84,7 @@ CURLcode Curl_set_dns_interface(struct SessionHandle *data, * Function provided by the resolver backend to set * local IPv4 address to use as source address for DNS requests */ -CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4) { (void)data; @@ -96,7 +96,7 @@ CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, * Function provided by the resolver backend to set * local IPv6 address to use as source address for DNS requests */ -CURLcode Curl_set_dns_local_ip6(struct SessionHandle *data, +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6) { (void)data; diff --git a/Utilities/cmcurl/lib/http.c b/Utilities/cmcurl/lib/http.c index 9817d72..378d8f7 100644 --- a/Utilities/cmcurl/lib/http.c +++ b/Utilities/cmcurl/lib/http.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -54,9 +54,10 @@ #include "curl_base64.h" #include "cookie.h" #include "strequal.h" +#include "vauth/vauth.h" #include "vtls/vtls.h" #include "http_digest.h" -#include "curl_ntlm.h" +#include "http_ntlm.h" #include "curl_ntlm_wb.h" #include "http_negotiate.h" #include "url.h" @@ -76,9 +77,9 @@ #include "pipeline.h" #include "http2.h" #include "connect.h" -#include "curl_printf.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -144,14 +145,13 @@ const struct Curl_handler Curl_handler_https = { ZERO_NULL, /* readwrite */ PORT_HTTPS, /* defport */ CURLPROTO_HTTPS, /* protocol */ - PROTOPT_SSL | PROTOPT_CREDSPERREQUEST /* flags */ + PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN_NPN /* flags */ }; #endif - CURLcode Curl_http_setup_conn(struct connectdata *conn) { - /* allocate the HTTP-specific struct for the SessionHandle, only to survive + /* allocate the HTTP-specific struct for the Curl_easy, only to survive during this request */ struct HTTP *http; DEBUGASSERT(conn->data->req.protop == NULL); @@ -179,12 +179,13 @@ char *Curl_checkheaders(const struct connectdata *conn, { struct curl_slist *head; size_t thislen = strlen(thisheader); - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; for(head = data->set.headers;head; head=head->next) { if(Curl_raw_nequal(head->data, thisheader, thislen)) return head->data; } + return NULL; } @@ -193,24 +194,24 @@ char *Curl_checkheaders(const struct connectdata *conn, * if proxy headers are not available, then it will lookup into http header * link list * - * It takes a connectdata struct as input instead of the SessionHandle simply + * It takes a connectdata struct as input instead of the Curl_easy simply * to know if this is a proxy request or not, as it then might check a * different header list. - * */ char *Curl_checkProxyheaders(const struct connectdata *conn, const char *thisheader) { struct curl_slist *head; size_t thislen = strlen(thisheader); - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; - for(head = (conn->bits.proxy && data->set.sep_headers)? - data->set.proxyheaders:data->set.headers; + for(head = (conn->bits.proxy && data->set.sep_headers) ? + data->set.proxyheaders : data->set.headers; head; head=head->next) { if(Curl_raw_nequal(head->data, thisheader, thislen)) return head->data; } + return NULL; } @@ -279,7 +280,7 @@ static CURLcode http_output_basic(struct connectdata *conn, bool proxy) { size_t size = 0; char *authorization = NULL; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char **userp; const char *user; const char *pwd; @@ -309,7 +310,7 @@ static CURLcode http_output_basic(struct connectdata *conn, bool proxy) free(*userp); *userp = aprintf("%sAuthorization: Basic %s\r\n", - proxy?"Proxy-":"", + proxy ? "Proxy-" : "", authorization); free(authorization); if(!*userp) @@ -376,7 +377,7 @@ static bool pickoneauth(struct auth *pick) */ static CURLcode http_perhapsrewind(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct HTTP *http = data->req.protop; curl_off_t bytessent; curl_off_t expectsend = -1; /* default is unknown */ @@ -484,7 +485,7 @@ static CURLcode http_perhapsrewind(struct connectdata *conn) CURLcode Curl_http_auth_act(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; bool pickhost = FALSE; bool pickproxy = FALSE; CURLcode result = CURLE_OK; @@ -528,7 +529,6 @@ CURLcode Curl_http_auth_act(struct connectdata *conn) return result; } } - else if((data->req.httpcode < 300) && (!data->state.authhost.done) && conn->bits.authneg) { @@ -553,7 +553,6 @@ CURLcode Curl_http_auth_act(struct connectdata *conn) return result; } - /* * Output the correct authentication header depending on the auth type * and whether or not it is to a proxy. @@ -567,12 +566,12 @@ output_auth_headers(struct connectdata *conn, { const char *auth = NULL; CURLcode result = CURLE_OK; -#if defined(USE_SPNEGO) || !defined(CURL_DISABLE_VERBOSE_STRINGS) - struct SessionHandle *data = conn->data; +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) || defined(USE_SPNEGO) + struct Curl_easy *data = conn->data; #endif #ifdef USE_SPNEGO - struct negotiatedata *negdata = proxy? - &data->state.proxyneg:&data->state.negotiate; + struct negotiatedata *negdata = proxy ? + &data->state.proxyneg : &data->state.negotiate; #endif #ifdef CURL_DISABLE_CRYPTO_AUTH @@ -584,7 +583,7 @@ output_auth_headers(struct connectdata *conn, negdata->state = GSS_AUTHNONE; if((authstatus->picked == CURLAUTH_NEGOTIATE) && negdata->context && !GSS_ERROR(negdata->status)) { - auth="Negotiate"; + auth = "Negotiate"; result = Curl_output_negotiate(conn, proxy); if(result) return result; @@ -595,7 +594,7 @@ output_auth_headers(struct connectdata *conn, #endif #ifdef USE_NTLM if(authstatus->picked == CURLAUTH_NTLM) { - auth="NTLM"; + auth = "NTLM"; result = Curl_output_ntlm(conn, proxy); if(result) return result; @@ -613,7 +612,7 @@ output_auth_headers(struct connectdata *conn, #endif #ifndef CURL_DISABLE_CRYPTO_AUTH if(authstatus->picked == CURLAUTH_DIGEST) { - auth="Digest"; + auth = "Digest"; result = Curl_output_digest(conn, proxy, (const unsigned char *)request, @@ -629,11 +628,12 @@ output_auth_headers(struct connectdata *conn, !Curl_checkProxyheaders(conn, "Proxy-authorization:")) || (!proxy && conn->bits.user_passwd && !Curl_checkheaders(conn, "Authorization:"))) { - auth="Basic"; + auth = "Basic"; result = http_output_basic(conn, proxy); if(result) return result; } + /* NOTE: this function should set 'done' TRUE, as the other auth functions work that way */ authstatus->done = TRUE; @@ -641,9 +641,9 @@ output_auth_headers(struct connectdata *conn, if(auth) { infof(data, "%s auth using %s with user '%s'\n", - proxy?"Proxy":"Server", auth, - proxy?(conn->proxyuser?conn->proxyuser:""): - (conn->user?conn->user:"")); + proxy ? "Proxy" : "Server", auth, + proxy ? (conn->proxyuser ? conn->proxyuser : "") : + (conn->user ? conn->user : "")); authstatus->multi = (!authstatus->done) ? TRUE : FALSE; } else @@ -674,7 +674,7 @@ Curl_http_output_auth(struct connectdata *conn, up the proxy tunnel */ { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct auth *authhost; struct auth *authproxy; @@ -735,7 +735,6 @@ Curl_http_output_auth(struct connectdata *conn, return result; } - /* * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate: * headers. They are dealt with both in the transfer.c main loop and in the @@ -748,7 +747,7 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, /* * This resource requires authentication */ - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; #ifdef USE_SPNEGO struct negotiatedata *negdata = proxy? @@ -780,7 +779,6 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, * request is sent, and then it is again set _after_ all response 401/407 * headers have been received but then only to a single preferred method * (bit). - * */ while(*auth) { @@ -893,6 +891,7 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, while(*auth && ISSPACE(*auth)) auth++; } + return CURLE_OK; } @@ -908,7 +907,7 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, */ static int http_should_fail(struct connectdata *conn) { - struct SessionHandle *data; + struct Curl_easy *data; int httpcode; DEBUGASSERT(conn); @@ -934,8 +933,7 @@ static int http_should_fail(struct connectdata *conn) ** Any code >= 400 that's not 401 or 407 is always ** a terminal error */ - if((httpcode != 401) && - (httpcode != 407)) + if((httpcode != 401) && (httpcode != 407)) return 1; /* @@ -986,7 +984,7 @@ static size_t readmoredata(char *buffer, struct HTTP *http = conn->data->req.protop; size_t fullsize = size * nitems; - if(0 == http->postsize) + if(!http->postsize) /* nothing to return */ return 0; @@ -1001,8 +999,8 @@ static size_t readmoredata(char *buffer, /* move backup data into focus and continue on that */ http->postdata = http->backup.postdata; http->postsize = http->backup.postsize; - conn->data->set.fread_func = http->backup.fread_func; - conn->data->set.in = http->backup.fread_in; + conn->data->state.fread_func = http->backup.fread_func; + conn->data->state.in = http->backup.fread_in; http->sending++; /* move one step up */ @@ -1092,15 +1090,14 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in, return result; } - - if(conn->handler->flags & PROTOPT_SSL) { + if((conn->handler->flags & PROTOPT_SSL) && conn->httpversion != 20) { /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk when we speak HTTPS, as if only a fraction of it is sent now, this data needs to fit into the normal read-callback buffer later on and that buffer is using this size. */ - sendsize= (size > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:size; + sendsize = (size > CURL_MAX_WRITE_SIZE) ? CURL_MAX_WRITE_SIZE : size; /* OpenSSL is very picky and we must send the SAME buffer pointer to the library when we attempt to re-send this buffer. Sending the same data @@ -1123,7 +1120,7 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in, * only send away a part). */ /* how much of the header that was sent */ - size_t headlen = (size_t)amount>headersize?headersize:(size_t)amount; + size_t headlen = (size_t)amount>headersize ? headersize : (size_t)amount; size_t bodylen = amount - headlen; if(conn->data->set.verbose) { @@ -1136,10 +1133,6 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in, ptr+headlen, bodylen, conn); } } - if(bodylen) - /* since we sent a piece of the body here, up the byte counter for it - accordingly */ - http->writebytecount += bodylen; /* 'amount' can never be a very large value here so typecasting it so a signed 31 bit value should not cause problems even if ssize_t is @@ -1147,6 +1140,10 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in, *bytes_written += (long)amount; if(http) { + /* if we sent a piece of the body here, up the byte counter for it + accordingly */ + http->writebytecount += bodylen; + if((size_t)amount != size) { /* The whole request could not be sent in one system call. We must queue it up and send it later when we get the chance. We must not @@ -1157,14 +1154,14 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in, ptr = in->buffer + amount; /* backup the currently set pointers */ - http->backup.fread_func = conn->data->set.fread_func; - http->backup.fread_in = conn->data->set.in; + http->backup.fread_func = conn->data->state.fread_func; + http->backup.fread_in = conn->data->state.in; http->backup.postdata = http->postdata; http->backup.postsize = http->postsize; /* set the new pointers for the request-sending */ - conn->data->set.fread_func = (curl_read_callback)readmoredata; - conn->data->set.in = (void *)conn; + conn->data->state.fread_func = (curl_read_callback)readmoredata; + conn->data->state.in = (void *)conn; http->postdata = ptr; http->postsize = (curl_off_t)size; @@ -1242,11 +1239,11 @@ CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size) buffer size that doubles the required size. If this new size would wrap size_t, then just use the largest possible one */ - if((size > (size_t)-1/2) || (in->size_used > (size_t)-1/2) || - (~(size*2) < (in->size_used*2))) + if((size > (size_t)-1 / 2) || (in->size_used > (size_t)-1 / 2) || + (~(size * 2) < (in->size_used * 2))) new_size = (size_t)-1; else - new_size = (in->size_used+size)*2; + new_size = (in->size_used+size) * 2; if(in->buffer) /* we have a buffer, enlarge the existing one */ @@ -1394,7 +1391,8 @@ static CURLcode https_connecting(struct connectdata *conn, bool *done) #endif #if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \ - defined(USE_DARWINSSL) || defined(USE_POLARSSL) || defined(USE_NSS) + defined(USE_DARWINSSL) || defined(USE_POLARSSL) || defined(USE_NSS) || \ + defined(USE_MBEDTLS) /* This function is for OpenSSL, GnuTLS, darwinssl, schannel and polarssl only. It should be made to query the generic SSL layer instead. */ static int https_getsock(struct connectdata *conn, @@ -1418,6 +1416,7 @@ static int https_getsock(struct connectdata *conn, return GETSOCK_READSOCK(0); } } + return CURLE_OK; } #else @@ -1435,14 +1434,14 @@ static int https_getsock(struct connectdata *conn, #endif /* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL */ /* - * Curl_http_done() gets called from Curl_done() after a single HTTP request - * has been performed. + * Curl_http_done() gets called after a single HTTP request has been + * performed. */ CURLcode Curl_http_done(struct connectdata *conn, CURLcode status, bool premature) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct HTTP *http = data->req.protop; #ifdef USE_NGHTTP2 struct http_conn *httpc = &conn->proto.httpc; @@ -1455,8 +1454,10 @@ CURLcode Curl_http_done(struct connectdata *conn, data->state.negotiate.state == GSS_AUTHSENT) { /* add forbid re-use if http-code != 401/407 as a WA only needed for * 401/407 that signal auth failure (empty) otherwise state will be RECV - * with current code */ - if((data->req.httpcode != 401) && (data->req.httpcode != 407)) + * with current code. + * Do not close CONNECT_ONLY connections. */ + if((data->req.httpcode != 401) && (data->req.httpcode != 407) && + !data->set.connect_only) connclose(conn, "Negotiate transfer completed"); Curl_cleanup_negotiate(data); } @@ -1466,7 +1467,7 @@ CURLcode Curl_http_done(struct connectdata *conn, conn->seek_func = data->set.seek_func; /* restore */ conn->seek_client = data->set.seek_client; /* restore */ - if(http == NULL) + if(!http) return CURLE_OK; if(http->send_buffer) { @@ -1479,11 +1480,16 @@ CURLcode Curl_http_done(struct connectdata *conn, DEBUGF(infof(data, "free header_recvbuf!!\n")); Curl_add_buffer_free(http->header_recvbuf); http->header_recvbuf = NULL; /* clear the pointer */ - for(; http->push_headers_used > 0; --http->push_headers_used) { - free(http->push_headers[http->push_headers_used - 1]); + Curl_add_buffer_free(http->trailer_recvbuf); + http->trailer_recvbuf = NULL; /* clear the pointer */ + if(http->push_headers) { + /* if they weren't used and then freed before */ + for(; http->push_headers_used > 0; --http->push_headers_used) { + free(http->push_headers[http->push_headers_used - 1]); + } + free(http->push_headers); + http->push_headers = NULL; } - free(http->push_headers); - http->push_headers = NULL; } if(http->stream_id) { nghttp2_session_set_stream_user_data(httpc->h2, http->stream_id, 0); @@ -1511,9 +1517,9 @@ CURLcode Curl_http_done(struct connectdata *conn, entire operation is complete */ !conn->bits.retry && !data->set.connect_only && - ((http->readbytecount + - data->req.headerbytecount - - data->req.deductheadercount)) <= 0) { + (http->readbytecount + + data->req.headerbytecount - + data->req.deductheadercount) <= 0) { /* If this connection isn't simply closed to be retried, AND nothing was read from the HTTP server (that counts), this can't be right so we return an error here */ @@ -1524,7 +1530,6 @@ CURLcode Curl_http_done(struct connectdata *conn, return CURLE_OK; } - /* * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons * to avoid it include: @@ -1534,18 +1539,20 @@ CURLcode Curl_http_done(struct connectdata *conn, * - if any server previously contacted to handle this request only supports * 1.0. */ -static bool use_http_1_1plus(const struct SessionHandle *data, +static bool use_http_1_1plus(const struct Curl_easy *data, const struct connectdata *conn) { - return ((data->set.httpversion >= CURL_HTTP_VERSION_1_1) || - ((data->set.httpversion != CURL_HTTP_VERSION_1_0) && - ((conn->httpversion == 11) || - ((conn->httpversion != 10) && - (data->state.httpversion != 10))))) ? TRUE : FALSE; + if((data->state.httpversion == 10) || (conn->httpversion == 10)) + return FALSE; + if((data->set.httpversion == CURL_HTTP_VERSION_1_0) && + (conn->httpversion <= 10)) + return FALSE; + return ((data->set.httpversion == CURL_HTTP_VERSION_NONE) || + (data->set.httpversion >= CURL_HTTP_VERSION_1_1)); } /* check and possibly add an Expect: header */ -static CURLcode expect100(struct SessionHandle *data, +static CURLcode expect100(struct Curl_easy *data, struct connectdata *conn, Curl_send_buffer *req_buffer) { @@ -1570,6 +1577,7 @@ static CURLcode expect100(struct SessionHandle *data, data->state.expect100header = TRUE; } } + return result; } @@ -1587,7 +1595,7 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn, struct curl_slist *h[2]; struct curl_slist *headers; int numlists=1; /* by default */ - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int i; enum proxy_use proxy; @@ -1688,16 +1696,23 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn, headers = headers->next; } } + return CURLE_OK; } -CURLcode Curl_add_timecondition(struct SessionHandle *data, +CURLcode Curl_add_timecondition(struct Curl_easy *data, Curl_send_buffer *req_buffer) { const struct tm *tm; char *buf = data->state.buffer; struct tm keeptime; - CURLcode result = Curl_gmtime(data->set.timevalue, &keeptime); + CURLcode result; + + if(data->set.timecondition == CURL_TIMECOND_NONE) + /* no condition was asked for */ + return CURLE_OK; + + result = Curl_gmtime(data->set.timevalue, &keeptime); if(result) { failf(data, "Invalid TIMEVALUE"); return result; @@ -1723,8 +1738,9 @@ CURLcode Curl_add_timecondition(struct SessionHandle *data, tm->tm_sec); switch(data->set.timecondition) { - case CURL_TIMECOND_IFMODSINCE: default: + break; + case CURL_TIMECOND_IFMODSINCE: result = Curl_add_bufferf(req_buffer, "If-Modified-Since: %s\r\n", buf); break; @@ -1742,13 +1758,13 @@ CURLcode Curl_add_timecondition(struct SessionHandle *data, } /* - * Curl_http() gets called from the generic Curl_do() function when a HTTP + * Curl_http() gets called from the generic multi_do() function when a HTTP * request is to be performed. This creates and sends a properly constructed * HTTP request. */ CURLcode Curl_http(struct connectdata *conn, bool *done) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; struct HTTP *http; const char *ppath = data->state.path; @@ -1776,15 +1792,8 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) if(conn->httpversion < 20) { /* unless the connection is re-used and already http2 */ switch(conn->negnpn) { - case CURL_HTTP_VERSION_2_0: + case CURL_HTTP_VERSION_2: conn->httpversion = 20; /* we know we're on HTTP/2 now */ - result = Curl_http2_init(conn); - if(result) - return result; - - result = Curl_http2_setup(conn); - if(result) - return result; result = Curl_http2_switched(conn, NULL, 0); if(result) @@ -1794,7 +1803,18 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) /* continue with HTTP/1.1 when explicitly requested */ break; default: - /* and as fallback */ + /* Check if user wants to use HTTP/2 with clear TCP*/ +#ifdef USE_NGHTTP2 + if(conn->data->set.httpversion == + CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) { + DEBUGF(infof(data, "HTTP/2 over clean TCP\n")); + conn->httpversion = 20; + + result = Curl_http2_switched(conn, NULL, 0); + if(result) + return result; + } +#endif break; } } @@ -1814,6 +1834,8 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) data->state.first_host = strdup(conn->host.name); if(!data->state.first_host) return CURLE_OUT_OF_MEMORY; + + data->state.first_remote_port = conn->remote_port; } http->writebytecount = http->readbytecount = 0; @@ -1895,6 +1917,10 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) if(!conn->allocptr.accept_encoding) return CURLE_OUT_OF_MEMORY; } + else { + Curl_safefree(conn->allocptr.accept_encoding); + conn->allocptr.accept_encoding = NULL; + } #ifdef HAVE_LIBZ /* we only consider transfer-encoding magic if libz support is built-in */ @@ -2130,7 +2156,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) * file size before we continue this venture in the dark lands of HTTP. *********************************************************************/ - if(data->state.resume_from < 0 ) { + if(data->state.resume_from < 0) { /* * This is meant to get the size of the present remote-file by itself. * We don't support this now. Bail out! @@ -2162,8 +2188,8 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) BUFSIZE : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = - data->set.fread_func(data->state.buffer, 1, readthisamountnow, - data->set.in); + data->state.fread_func(data->state.buffer, 1, readthisamountnow, + data->state.in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { @@ -2279,7 +2305,6 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) "%s" /* TE: */ "%s" /* accept-encoding */ "%s" /* referer */ - "%s" /* Proxy-Connection */ "%s",/* transfer-encoding */ ftp_typecode, @@ -2302,10 +2327,6 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) conn->allocptr.accept_encoding:"", (data->change.referer && conn->allocptr.ref)? conn->allocptr.ref:"" /* Referer: <data> */, - (conn->bits.httpproxy && - !conn->bits.tunnel_proxy && - !Curl_checkProxyheaders(conn, "Proxy-Connection:"))? - "Proxy-Connection: Keep-Alive\r\n":"", te ); @@ -2329,7 +2350,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) if(!(conn->handler->flags&PROTOPT_SSL) && conn->httpversion != 20 && - (data->set.httpversion == CURL_HTTP_VERSION_2_0)) { + (data->set.httpversion == CURL_HTTP_VERSION_2)) { /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done over SSL */ result = Curl_http2_request_upgrade(req_buffer, conn); @@ -2390,11 +2411,9 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) } #endif - if(data->set.timecondition) { - result = Curl_add_timecondition(data, req_buffer); - if(result) - return result; - } + result = Curl_add_timecondition(data, req_buffer); + if(result) + return result; result = Curl_add_custom_headers(conn, FALSE, req_buffer); if(result) @@ -2437,11 +2456,11 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) on. The data->set.fread_func pointer itself will be changed for the multipart case to the function that returns a multipart formatted stream. */ - http->form.fread_func = data->set.fread_func; + http->form.fread_func = data->state.fread_func; /* Set the read function to read from the generated form data */ - data->set.fread_func = (curl_read_callback)Curl_FormReader; - data->set.in = &http->form; + data->state.fread_func = (curl_read_callback)Curl_FormReader; + data->state.in = &http->form; http->sending = HTTPSEND_BODY; @@ -2659,8 +2678,8 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) http->sending = HTTPSEND_BODY; - data->set.fread_func = (curl_read_callback)readmoredata; - data->set.in = (void *)conn; + data->state.fread_func = (curl_read_callback)readmoredata; + data->state.in = (void *)conn; /* set the upload size to the progress meter */ Curl_pgrsSetUploadSize(data, http->postsize); @@ -2758,7 +2777,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done) * Returns TRUE if member of the list matches prefix of string */ static bool -checkhttpprefix(struct SessionHandle *data, +checkhttpprefix(struct Curl_easy *data, const char *s) { struct curl_slist *head = data->set.http200aliases; @@ -2797,7 +2816,7 @@ checkhttpprefix(struct SessionHandle *data, #ifndef CURL_DISABLE_RTSP static bool -checkrtspprefix(struct SessionHandle *data, +checkrtspprefix(struct Curl_easy *data, const char *s) { @@ -2825,7 +2844,7 @@ checkrtspprefix(struct SessionHandle *data, #endif /* CURL_DISABLE_RTSP */ static bool -checkprotoprefix(struct SessionHandle *data, struct connectdata *conn, +checkprotoprefix(struct Curl_easy *data, struct connectdata *conn, const char *s) { #ifndef CURL_DISABLE_RTSP @@ -2843,7 +2862,7 @@ checkprotoprefix(struct SessionHandle *data, struct connectdata *conn, * header. We make sure that the full string fit in the allocated header * buffer, or else we enlarge it. */ -static CURLcode header_append(struct SessionHandle *data, +static CURLcode header_append(struct Curl_easy *data, struct SingleRequest *k, size_t length) { @@ -2881,7 +2900,7 @@ static CURLcode header_append(struct SessionHandle *data, return CURLE_OK; } -static void print_http_error(struct SessionHandle *data) +static void print_http_error(struct Curl_easy *data) { struct SingleRequest *k = &data->req; char *beg = k->p; @@ -2921,7 +2940,7 @@ static void print_http_error(struct SessionHandle *data) /* * Read any HTTP header lines from the server and pass them to the client app. */ -CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, +CURLcode Curl_http_readwrite_headers(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *stop_reading) @@ -3035,7 +3054,7 @@ CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, switch(k->httpcode) { case 100: /* if we did wait for this do enable write now! */ - if(k->exp100) { + if(k->exp100 > EXP100_SEND_DATA) { k->exp100 = EXP100_SEND_DATA; k->keepon |= KEEP_SEND; } @@ -3119,52 +3138,50 @@ CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, data->req.deductheadercount = (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0; - if(!*stop_reading) { - /* Curl_http_auth_act() checks what authentication methods - * that are available and decides which one (if any) to - * use. It will set 'newurl' if an auth method was picked. */ - result = Curl_http_auth_act(conn); + /* Curl_http_auth_act() checks what authentication methods + * that are available and decides which one (if any) to + * use. It will set 'newurl' if an auth method was picked. */ + result = Curl_http_auth_act(conn); - if(result) - return result; + if(result) + return result; - if(k->httpcode >= 300) { - if((!conn->bits.authneg) && !conn->bits.close && - !conn->bits.rewindaftersend) { - /* - * General treatment of errors when about to send data. Including : - * "417 Expectation Failed", while waiting for 100-continue. - * - * The check for close above is done simply because of something - * else has already deemed the connection to get closed then - * something else should've considered the big picture and we - * avoid this check. - * - * rewindaftersend indicates that something has told libcurl to - * continue sending even if it gets discarded + if(k->httpcode >= 300) { + if((!conn->bits.authneg) && !conn->bits.close && + !conn->bits.rewindaftersend) { + /* + * General treatment of errors when about to send data. Including : + * "417 Expectation Failed", while waiting for 100-continue. + * + * The check for close above is done simply because of something + * else has already deemed the connection to get closed then + * something else should've considered the big picture and we + * avoid this check. + * + * rewindaftersend indicates that something has told libcurl to + * continue sending even if it gets discarded + */ + + switch(data->set.httpreq) { + case HTTPREQ_PUT: + case HTTPREQ_POST: + case HTTPREQ_POST_FORM: + /* We got an error response. If this happened before the whole + * request body has been sent we stop sending and mark the + * connection for closure after we've read the entire response. */ - - switch(data->set.httpreq) { - case HTTPREQ_PUT: - case HTTPREQ_POST: - case HTTPREQ_POST_FORM: - /* We got an error response. If this happened before the whole - * request body has been sent we stop sending and mark the - * connection for closure after we've read the entire response. - */ - if(!k->upload_done) { - infof(data, "HTTP error before end of send, stop sending\n"); - connclose(conn, "Stop sending data before everything sent"); - k->upload_done = TRUE; - k->keepon &= ~KEEP_SEND; /* don't send */ - if(data->state.expect100header) - k->exp100 = EXP100_FAILED; - } - break; - - default: /* default label present to avoid compiler warnings */ - break; + if(!k->upload_done) { + infof(data, "HTTP error before end of send, stop sending\n"); + connclose(conn, "Stop sending data before everything sent"); + k->upload_done = TRUE; + k->keepon &= ~KEEP_SEND; /* don't send */ + if(data->state.expect100header) + k->exp100 = EXP100_FAILED; } + break; + + default: /* default label present to avoid compiler warnings */ + break; } } @@ -3185,6 +3202,16 @@ CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, */ if(data->set.opt_no_body) *stop_reading = TRUE; +#ifndef CURL_DISABLE_RTSP + else if((conn->handler->protocol & CURLPROTO_RTSP) && + (data->set.rtspreq == RTSPREQ_DESCRIBE) && + (k->size <= -1)) + /* Respect section 4.4 of rfc2326: If the Content-Length header is + absent, a length 0 must be assumed. It will prevent libcurl from + hanging on DESCRIBE request that got refused for whatever + reason */ + *stop_reading = TRUE; +#endif else { /* If we know the expected size of this document, we set the maximum download size to the size of the expected @@ -3279,6 +3306,13 @@ CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, &httpversion_major, &conn->httpversion, &k->httpcode); + + if(nc == 1 && httpversion_major == 2 && + 1 == sscanf(HEADER1, " HTTP/2 %d", &k->httpcode)) { + conn->httpversion = 0; + nc = 3; + } + if(nc==3) { conn->httpversion += 10 * httpversion_major; @@ -3576,8 +3610,7 @@ CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, } else if(checkprefix("Content-Encoding:", k->p) && - (data->set.str[STRING_ENCODING] || - conn->httpversion == 20)) { + data->set.str[STRING_ENCODING]) { /* * Process Content-Encoding. Look for the values: identity, * gzip, deflate, compress, x-gzip and x-compress. x-gzip and @@ -3726,7 +3759,7 @@ CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, k->hbufp = data->state.headerbuff; k->hbuflen = 0; } - while(!*stop_reading && *k->str); /* header line within buffer */ + while(*k->str); /* header line within buffer */ /* We might have reached the end of the header part here, but there might be a non-header part left in the end of the read diff --git a/Utilities/cmcurl/lib/http.h b/Utilities/cmcurl/lib/http.h index fe4f39b..6529005 100644 --- a/Utilities/cmcurl/lib/http.h +++ b/Utilities/cmcurl/lib/http.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -69,7 +69,7 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in, size_t included_body_bytes, int socketindex); -CURLcode Curl_add_timecondition(struct SessionHandle *data, +CURLcode Curl_add_timecondition(struct Curl_easy *data, Curl_send_buffer *buf); CURLcode Curl_add_custom_headers(struct connectdata *conn, bool is_connect, @@ -87,7 +87,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn, char *datap, ssize_t length, ssize_t *wrote); /* These functions are in http.c */ -void Curl_http_auth_stage(struct SessionHandle *data, int stage); +void Curl_http_auth_stage(struct Curl_easy *data, int stage); CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, const char *auth); CURLcode Curl_http_auth_act(struct connectdata *conn); @@ -163,6 +163,7 @@ struct HTTP { Curl_send_buffer *header_recvbuf; size_t nread_header_recvbuf; /* number of bytes in header_recvbuf fed into upper layer */ + Curl_send_buffer *trailer_recvbuf; int status_code; /* HTTP status code */ const uint8_t *pausedata; /* pointer to data received in on_data_chunk */ size_t pauselen; /* the number of bytes left in data */ @@ -213,15 +214,16 @@ struct http_conn { them for both cases. */ int32_t pause_stream_id; /* stream ID which paused nghttp2_session_mem_recv */ + size_t drain_total; /* sum of all stream's UrlState.drain */ - /* this is a hash of all individual streams (SessionHandle structs) */ + /* this is a hash of all individual streams (Curl_easy structs) */ struct h2settings settings; #else int unused; /* prevent a compiler warning */ #endif }; -CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, +CURLcode Curl_http_readwrite_headers(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *stop_reading); diff --git a/Utilities/cmcurl/lib/http2.c b/Utilities/cmcurl/lib/http2.c index 0024add..efc082d 100644 --- a/Utilities/cmcurl/lib/http2.c +++ b/Utilities/cmcurl/lib/http2.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -23,7 +23,6 @@ #include "curl_setup.h" #ifdef USE_NGHTTP2 -#include "curl_printf.h" #include <nghttp2/nghttp2.h> #include "urldata.h" #include "http2.h" @@ -34,17 +33,50 @@ #include "multiif.h" #include "conncache.h" #include "url.h" +#include "connect.h" +#include "strtoofft.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define MIN(x,y) ((x)<(y)?(x):(y)) -#if (NGHTTP2_VERSION_NUM < 0x000600) +#if (NGHTTP2_VERSION_NUM < 0x010000) #error too old nghttp2 version, upgrade! #endif +#if (NGHTTP2_VERSION_NUM > 0x010800) +#define NGHTTP2_HAS_HTTP2_STRERROR 1 +#endif + +#if (NGHTTP2_VERSION_NUM >= 0x010900) +/* nghttp2_session_callbacks_set_error_callback is present in nghttp2 1.9.0 or + later */ +#define NGHTTP2_HAS_ERROR_CALLBACK 1 +#else +#define nghttp2_session_callbacks_set_error_callback(x,y) +#endif + +/* + * Curl_http2_init_state() is called when the easy handle is created and + * allows for HTTP/2 specific init of state. + */ +void Curl_http2_init_state(struct UrlState *state) +{ + state->stream_weight = NGHTTP2_DEFAULT_WEIGHT; +} + +/* + * Curl_http2_init_userset() is called when the easy handle is created and + * allows for HTTP/2 specific user-set fields. + */ +void Curl_http2_init_userset(struct UserDefined *set) +{ + set->stream_weight = NGHTTP2_DEFAULT_WEIGHT; +} + static int http2_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks @@ -92,6 +124,8 @@ static CURLcode http2_disconnect(struct connectdata *conn, if(http) { Curl_add_buffer_free(http->header_recvbuf); http->header_recvbuf = NULL; /* clear the pointer */ + Curl_add_buffer_free(http->trailer_recvbuf); + http->trailer_recvbuf = NULL; /* clear the pointer */ for(; http->push_headers_used > 0; --http->push_headers_used) { free(http->push_headers[http->push_headers_used - 1]); } @@ -105,7 +139,7 @@ static CURLcode http2_disconnect(struct connectdata *conn, } /* called from Curl_http_setup_conn */ -void Curl_http2_setup_req(struct SessionHandle *data) +void Curl_http2_setup_req(struct Curl_easy *data) { struct HTTP *http = data->req.protop; @@ -134,7 +168,7 @@ void Curl_http2_setup_conn(struct connectdata *conn) * HTTP to HTTP2. */ const struct Curl_handler Curl_handler_http2 = { - "HTTP2", /* scheme */ + "HTTP", /* scheme */ ZERO_NULL, /* setup_connection */ Curl_http, /* do_it */ Curl_http_done, /* done */ @@ -154,7 +188,7 @@ const struct Curl_handler Curl_handler_http2 = { }; const struct Curl_handler Curl_handler_http2_ssl = { - "HTTP2", /* scheme */ + "HTTPS", /* scheme */ ZERO_NULL, /* setup_connection */ Curl_http, /* do_it */ Curl_http_done, /* done */ @@ -183,6 +217,34 @@ int Curl_http2_ver(char *p, size_t len) return snprintf(p, len, " nghttp2/%s", h2->version_str); } +/* HTTP/2 error code to name based on the Error Code Registry. +https://tools.ietf.org/html/rfc7540#page-77 +nghttp2_error_code enums are identical. +*/ +const char *Curl_http2_strerror(uint32_t err) { +#ifndef NGHTTP2_HAS_HTTP2_STRERROR + const char *str[] = { + "NO_ERROR", /* 0x0 */ + "PROTOCOL_ERROR", /* 0x1 */ + "INTERNAL_ERROR", /* 0x2 */ + "FLOW_CONTROL_ERROR", /* 0x3 */ + "SETTINGS_TIMEOUT", /* 0x4 */ + "STREAM_CLOSED", /* 0x5 */ + "FRAME_SIZE_ERROR", /* 0x6 */ + "REFUSED_STREAM", /* 0x7 */ + "CANCEL", /* 0x8 */ + "COMPRESSION_ERROR", /* 0x9 */ + "CONNECT_ERROR", /* 0xA */ + "ENHANCE_YOUR_CALM", /* 0xB */ + "INADEQUATE_SECURITY", /* 0xC */ + "HTTP_1_1_REQUIRED" /* 0xD */ + }; + return (err < sizeof str / sizeof str[0]) ? str[err] : "unknown"; +#else + return nghttp2_http2_strerror(err); +#endif +} + /* * The implementation of nghttp2_send_callback type. Here we write |data| with * size |length| to the network and return the number of bytes actually @@ -222,7 +284,7 @@ static ssize_t send_callback(nghttp2_session *h2, /* We pass a pointer to this struct in the push callback, but the contents of the struct are hidden from the user. */ struct curl_pushheaders { - struct SessionHandle *data; + struct Curl_easy *data; const nghttp2_push_promise *frame; }; @@ -263,7 +325,7 @@ char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header) size_t i; for(i=0; i<stream->push_headers_used; i++) { if(!strncmp(header, stream->push_headers[i], len)) { - /* sub-match, make sure that it us followed by a colon */ + /* sub-match, make sure that it is followed by a colon */ if(stream->push_headers[i][len] != ':') continue; return &stream->push_headers[i][len+1]; @@ -273,9 +335,9 @@ char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header) return NULL; } -static CURL *duphandle(struct SessionHandle *data) +static struct Curl_easy *duphandle(struct Curl_easy *data) { - struct SessionHandle *second = curl_easy_duphandle(data); + struct Curl_easy *second = curl_easy_duphandle(data); if(second) { /* setup the request struct */ struct HTTP *http = calloc(1, sizeof(struct HTTP)); @@ -291,15 +353,17 @@ static CURL *duphandle(struct SessionHandle *data) (void)Curl_close(second); second = NULL; } - else + else { Curl_http2_setup_req(second); + second->state.stream_weight = data->state.stream_weight; + } } } return second; } -static int push_promise(struct SessionHandle *data, +static int push_promise(struct Curl_easy *data, struct connectdata *conn, const nghttp2_push_promise *frame) { @@ -308,12 +372,13 @@ static int push_promise(struct SessionHandle *data, frame->promised_stream_id)); if(data->multi->push_cb) { struct HTTP *stream; + struct HTTP *newstream; struct curl_pushheaders heads; CURLMcode rc; struct http_conn *httpc; size_t i; /* clone the parent */ - CURL *newhandle = duphandle(data); + struct Curl_easy *newhandle = duphandle(data); if(!newhandle) { infof(data, "failed to duplicate handle\n"); rv = 1; /* FAIL HARD */ @@ -348,6 +413,11 @@ static int push_promise(struct SessionHandle *data, goto fail; } + newstream = newhandle->req.protop; + newstream->stream_id = frame->promised_stream_id; + newhandle->req.maxdownload = -1; + newhandle->req.size = -1; + /* approved, add to the multi handle and immediately switch to PERFORM state with the given connection !*/ rc = Curl_multi_add_perform(data->multi, newhandle, conn); @@ -373,29 +443,46 @@ static int push_promise(struct SessionHandle *data, static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { - struct connectdata *conn = NULL; - struct http_conn *httpc = NULL; - struct SessionHandle *data_s = NULL; + struct connectdata *conn = (struct connectdata *)userp; + struct http_conn *httpc = &conn->proto.httpc; + struct Curl_easy *data_s = NULL; struct HTTP *stream = NULL; static int lastStream = -1; int rv; size_t left, ncopy; int32_t stream_id = frame->hd.stream_id; - (void)userp; - if(!stream_id) { /* stream ID zero is for connection-oriented stuff */ + if(frame->hd.type == NGHTTP2_SETTINGS) { + uint32_t max_conn = httpc->settings.max_concurrent_streams; + DEBUGF(infof(conn->data, "Got SETTINGS\n")); + httpc->settings.max_concurrent_streams = + nghttp2_session_get_remote_settings( + session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); + httpc->settings.enable_push = + nghttp2_session_get_remote_settings( + session, NGHTTP2_SETTINGS_ENABLE_PUSH); + DEBUGF(infof(conn->data, "MAX_CONCURRENT_STREAMS == %d\n", + httpc->settings.max_concurrent_streams)); + DEBUGF(infof(conn->data, "ENABLE_PUSH == %s\n", + httpc->settings.enable_push?"TRUE":"false")); + if(max_conn != httpc->settings.max_concurrent_streams) { + /* only signal change if the value actually changed */ + infof(conn->data, + "Connection state changed (MAX_CONCURRENT_STREAMS updated)!\n"); + Curl_multi_connchanged(conn->data->multi); + } + } return 0; } - data_s = nghttp2_session_get_stream_user_data(session, - frame->hd.stream_id); - if(lastStream != frame->hd.stream_id) { - lastStream = frame->hd.stream_id; + data_s = nghttp2_session_get_stream_user_data(session, stream_id); + if(lastStream != stream_id) { + lastStream = stream_id; } if(!data_s) { DEBUGF(infof(conn->data, - "No SessionHandle associated with stream: %x\n", + "No Curl_easy associated with stream: %x\n", stream_id)); return 0; } @@ -407,10 +494,6 @@ static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, DEBUGF(infof(data_s, "on_frame_recv() header %x stream %x\n", frame->hd.type, stream_id)); - conn = data_s->easy_conn; - assert(conn); - assert(conn->data == data_s); - httpc = &conn->proto.httpc; switch(frame->hd.type) { case NGHTTP2_DATA: /* If body started on this stream, then receiving DATA is illegal. */ @@ -424,13 +507,9 @@ static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, } break; case NGHTTP2_HEADERS: - if(frame->headers.cat == NGHTTP2_HCAT_REQUEST) - break; - if(stream->bodystarted) { /* Only valid HEADERS after body started is trailer HEADERS. We - ignores trailer HEADERS for now. nghttp2 guarantees that it - has END_STREAM flag set. */ + buffer them in on_header callback. */ break; } @@ -461,7 +540,15 @@ static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, stream->memlen += ncopy; data_s->state.drain++; - Curl_expire(data_s, 1); + httpc->drain_total++; + { + /* get the pointer from userp again since it was re-assigned above */ + struct connectdata *conn_s = (struct connectdata *)userp; + + /* if we receive data for another handle, wake that up */ + if(conn_s->data != data_s) + Curl_expire(data_s, 1); + } break; case NGHTTP2_PUSH_PROMISE: rv = push_promise(data_s, conn, &frame->push_promise); @@ -474,28 +561,6 @@ static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, } } break; - case NGHTTP2_SETTINGS: - { - uint32_t max_conn = httpc->settings.max_concurrent_streams; - DEBUGF(infof(conn->data, "Got SETTINGS for stream %u!\n", stream_id)); - httpc->settings.max_concurrent_streams = - nghttp2_session_get_remote_settings( - session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); - httpc->settings.enable_push = - nghttp2_session_get_remote_settings( - session, NGHTTP2_SETTINGS_ENABLE_PUSH); - DEBUGF(infof(conn->data, "MAX_CONCURRENT_STREAMS == %d\n", - httpc->settings.max_concurrent_streams)); - DEBUGF(infof(conn->data, "ENABLE_PUSH == %s\n", - httpc->settings.enable_push?"TRUE":"false")); - if(max_conn != httpc->settings.max_concurrent_streams) { - /* only signal change if the value actually changed */ - infof(conn->data, - "Connection state changed (MAX_CONCURRENT_STREAMS updated)!\n"); - Curl_multi_connchanged(conn->data->multi); - } - } - break; default: DEBUGF(infof(conn->data, "Got frame type %x for stream %u!\n", frame->hd.type, stream_id)); @@ -508,7 +573,7 @@ static int on_invalid_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, int lib_error_code, void *userp) { - struct SessionHandle *data_s = NULL; + struct Curl_easy *data_s = NULL; (void)userp; data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); @@ -525,12 +590,12 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, const uint8_t *data, size_t len, void *userp) { struct HTTP *stream; - struct SessionHandle *data_s; + struct Curl_easy *data_s; size_t nread; + struct connectdata *conn = (struct connectdata *)userp; (void)session; (void)flags; (void)data; - (void)userp; DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ @@ -552,8 +617,12 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, stream->memlen += nread; data_s->state.drain++; - Curl_expire(data_s, 1); /* TODO: fix so that this can be set to 0 for - immediately? */ + conn->proto.httpc.drain_total++; + + /* if we receive data for another handle, wake that up */ + if(conn->data != data_s) + Curl_expire(data_s, 1); /* TODO: fix so that this can be set to 0 for + immediately? */ DEBUGF(infof(data_s, "%zu data received for stream %u " "(%zu left in buffer %p, total %zu)\n", @@ -568,8 +637,18 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, ", stream %u\n", len - nread, stream_id)); data_s->easy_conn->proto.httpc.pause_stream_id = stream_id; + return NGHTTP2_ERR_PAUSE; } + + /* pause execution of nghttp2 if we received data for another handle + in order to process them first. */ + if(conn->data != data_s) { + data_s->easy_conn->proto.httpc.pause_stream_id = stream_id; + + return NGHTTP2_ERR_PAUSE; + } + return 0; } @@ -577,7 +656,7 @@ static int before_frame_send(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { - struct SessionHandle *data_s; + struct Curl_easy *data_s; (void)userp; data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); @@ -591,7 +670,7 @@ static int on_frame_send(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { - struct SessionHandle *data_s; + struct Curl_easy *data_s; (void)userp; data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); @@ -605,7 +684,7 @@ static int on_frame_not_send(nghttp2_session *session, const nghttp2_frame *frame, int lib_error_code, void *userp) { - struct SessionHandle *data_s; + struct Curl_easy *data_s; (void)userp; data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); @@ -619,11 +698,11 @@ static int on_frame_not_send(nghttp2_session *session, static int on_stream_close(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *userp) { - struct SessionHandle *data_s; + struct Curl_easy *data_s; struct HTTP *stream; + struct connectdata *conn = (struct connectdata *)userp; (void)session; (void)stream_id; - (void)userp; if(stream_id) { /* get the stream from the hash based on Stream ID, stream ID zero is for @@ -634,14 +713,16 @@ static int on_stream_close(nghttp2_session *session, int32_t stream_id, decided to reject stream (e.g., PUSH_PROMISE). */ return 0; } - DEBUGF(infof(data_s, "on_stream_close(), error_code = %d, stream %u\n", - error_code, stream_id)); + DEBUGF(infof(data_s, "on_stream_close(), %s (err %d), stream %u\n", + Curl_http2_strerror(error_code), error_code, stream_id)); stream = data_s->req.protop; if(!stream) return NGHTTP2_ERR_CALLBACK_FAILURE; stream->error_code = error_code; stream->closed = TRUE; + data_s->state.drain++; + conn->proto.httpc.drain_total++; /* remove the entry from the hash as the stream is now gone */ nghttp2_session_set_stream_user_data(session, stream_id, 0); @@ -653,13 +734,36 @@ static int on_stream_close(nghttp2_session *session, int32_t stream_id, static int on_begin_headers(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { - struct SessionHandle *data_s = NULL; + struct HTTP *stream; + struct Curl_easy *data_s = NULL; (void)userp; data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); - if(data_s) { - DEBUGF(infof(data_s, "on_begin_headers() was called\n")); + if(!data_s) { + return 0; + } + + DEBUGF(infof(data_s, "on_begin_headers() was called\n")); + + if(frame->hd.type != NGHTTP2_HEADERS) { + return 0; + } + + stream = data_s->req.protop; + if(!stream || !stream->bodystarted) { + return 0; } + + /* This is trailer HEADERS started. Allocate buffer for them. */ + DEBUGF(infof(data_s, "trailer field started\n")); + + assert(stream->trailer_recvbuf == NULL); + + stream->trailer_recvbuf = Curl_add_buffer_init(); + if(!stream->trailer_recvbuf) { + return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; + } + return 0; } @@ -698,11 +802,10 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { struct HTTP *stream; - struct SessionHandle *data_s; + struct Curl_easy *data_s; int32_t stream_id = frame->hd.stream_id; - + struct connectdata *conn = (struct connectdata *)userp; (void)flags; - (void)userp; DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ @@ -719,11 +822,6 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame, return NGHTTP2_ERR_CALLBACK_FAILURE; } - if(stream->bodystarted) - /* Ignore trailer or HEADERS not mapped to HTTP semantics. The - consequence is handled in on_frame_recv(). */ - return 0; - /* Store received PUSH_PROMISE headers to be used when the subsequent PUSH_PROMISE callback comes */ if(frame->hd.type == NGHTTP2_PUSH_PROMISE) { @@ -754,6 +852,23 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame, return 0; } + if(stream->bodystarted) { + /* This is trailer fields. */ + /* 3 is for ":" and "\r\n". */ + uint32_t n = (uint32_t)(namelen + valuelen + 3); + + DEBUGF(infof(data_s, "h2 trailer: %.*s: %.*s\n", namelen, name, valuelen, + value)); + + Curl_add_buffer(stream->trailer_recvbuf, &n, sizeof(n)); + Curl_add_buffer(stream->trailer_recvbuf, name, namelen); + Curl_add_buffer(stream->trailer_recvbuf, ": ", 2); + Curl_add_buffer(stream->trailer_recvbuf, value, valuelen); + Curl_add_buffer(stream->trailer_recvbuf, "\r\n\0", 3); + + return 0; + } + if(namelen == sizeof(":status") - 1 && memcmp(":status", name, namelen) == 0) { /* nghttp2 guarantees :status is received first and only once, and @@ -762,14 +877,16 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame, stream->status_code = decode_status_code(value, valuelen); DEBUGASSERT(stream->status_code != -1); - Curl_add_buffer(stream->header_recvbuf, "HTTP/2.0 ", 9); + Curl_add_buffer(stream->header_recvbuf, "HTTP/2 ", 7); Curl_add_buffer(stream->header_recvbuf, value, valuelen); - Curl_add_buffer(stream->header_recvbuf, "\r\n", 2); - data_s->state.drain++; - Curl_expire(data_s, 1); - - DEBUGF(infof(data_s, "h2 status: HTTP/2 %03d\n", - stream->status_code)); + /* the space character after the status code is mandatory */ + Curl_add_buffer(stream->header_recvbuf, " \r\n", 3); + /* if we receive data for another handle, wake that up */ + if(conn->data != data_s) + Curl_expire(data_s, 1); + + DEBUGF(infof(data_s, "h2 status: HTTP/2 %03d (easy %p)\n", + stream->status_code, data_s)); return 0; } @@ -777,11 +894,12 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame, received, and this is not pseudo-header field . */ /* convert to a HTTP1-style header */ Curl_add_buffer(stream->header_recvbuf, name, namelen); - Curl_add_buffer(stream->header_recvbuf, ":", 1); + Curl_add_buffer(stream->header_recvbuf, ": ", 2); Curl_add_buffer(stream->header_recvbuf, value, valuelen); Curl_add_buffer(stream->header_recvbuf, "\r\n", 2); - data_s->state.drain++; - Curl_expire(data_s, 1); + /* if we receive data for another handle, wake that up */ + if(conn->data != data_s) + Curl_expire(data_s, 1); DEBUGF(infof(data_s, "h2 header: %.*s: %.*s\n", namelen, name, valuelen, value)); @@ -796,7 +914,7 @@ static ssize_t data_source_read_callback(nghttp2_session *session, nghttp2_data_source *source, void *userp) { - struct SessionHandle *data_s; + struct Curl_easy *data_s; struct HTTP *stream = NULL; size_t nread; (void)source; @@ -848,6 +966,19 @@ static nghttp2_settings_entry settings[] = { #define H2_BUFSIZE 32768 +#ifdef NGHTTP2_HAS_ERROR_CALLBACK +static int error_callback(nghttp2_session *session, + const char *msg, + size_t len, + void *userp) +{ + struct connectdata *conn = (struct connectdata *)userp; + (void)session; + infof(conn->data, "http2 error: %.*s\n", len, msg); + return 0; +} +#endif + /* * Initialize nghttp2 for a Curl connection */ @@ -897,6 +1028,8 @@ CURLcode Curl_http2_init(struct connectdata *conn) /* nghttp2_on_header_callback */ nghttp2_session_callbacks_set_on_header_callback(callbacks, on_header); + nghttp2_session_callbacks_set_error_callback(callbacks, error_callback); + /* The nghttp2 session is not yet setup, do it */ rc = nghttp2_session_client_new(&conn->proto.httpc.h2, callbacks, conn); @@ -906,25 +1039,11 @@ CURLcode Curl_http2_init(struct connectdata *conn) failf(conn->data, "Couldn't initialize nghttp2!"); return CURLE_OUT_OF_MEMORY; /* most likely at least */ } - - if(rc) { - failf(conn->data, "Couldn't init stream hash!"); - return CURLE_OUT_OF_MEMORY; /* most likely at least */ - } } return CURLE_OK; } /* - * Send a request using http2 - */ -CURLcode Curl_http2_send_request(struct connectdata *conn) -{ - (void)conn; - return CURLE_OK; -} - -/* * Append headers to ask for a HTTP1.1 to HTTP2 upgrade. */ CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req, @@ -969,26 +1088,187 @@ CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req, return result; } -static ssize_t http2_handle_stream_close(struct http_conn *httpc, - struct SessionHandle *data, +/* + * Returns nonzero if current HTTP/2 session should be closed. + */ +static int should_close_session(struct http_conn *httpc) { + return httpc->drain_total == 0 && !nghttp2_session_want_read(httpc->h2) && + !nghttp2_session_want_write(httpc->h2); +} + +static int h2_session_send(struct Curl_easy *data, + nghttp2_session *h2); + +/* + * h2_process_pending_input() processes pending input left in + * httpc->inbuf. Then, call h2_session_send() to send pending data. + * This function returns 0 if it succeeds, or -1 and error code will + * be assigned to *err. + */ +static int h2_process_pending_input(struct Curl_easy *data, + struct http_conn *httpc, + CURLcode *err) { + ssize_t nread; + char *inbuf; + ssize_t rv; + + nread = httpc->inbuflen - httpc->nread_inbuf; + inbuf = httpc->inbuf + httpc->nread_inbuf; + + rv = nghttp2_session_mem_recv(httpc->h2, (const uint8_t *)inbuf, nread); + if(rv < 0) { + failf(data, + "h2_process_pending_input: nghttp2_session_mem_recv() returned " + "%d:%s\n", rv, nghttp2_strerror((int)rv)); + *err = CURLE_RECV_ERROR; + return -1; + } + + if(nread == rv) { + DEBUGF(infof(data, + "h2_process_pending_input: All data in connection buffer " + "processed\n")); + httpc->inbuflen = 0; + httpc->nread_inbuf = 0; + } + else { + httpc->nread_inbuf += rv; + DEBUGF(infof(data, + "h2_process_pending_input: %zu bytes left in connection " + "buffer\n", + httpc->inbuflen - httpc->nread_inbuf)); + } + + rv = h2_session_send(data, httpc->h2); + if(rv != 0) { + *err = CURLE_SEND_ERROR; + return -1; + } + + if(should_close_session(httpc)) { + DEBUGF(infof(data, + "h2_process_pending_input: nothing to do in this session\n")); + *err = CURLE_HTTP2; + return -1; + } + + return 0; +} + +static ssize_t http2_handle_stream_close(struct connectdata *conn, + struct Curl_easy *data, struct HTTP *stream, CURLcode *err) { + char *trailer_pos, *trailer_end; + CURLcode result; + struct http_conn *httpc = &conn->proto.httpc; + if(httpc->pause_stream_id == stream->stream_id) { httpc->pause_stream_id = 0; } + + DEBUGASSERT(httpc->drain_total >= data->state.drain); + httpc->drain_total -= data->state.drain; + data->state.drain = 0; + + if(httpc->pause_stream_id == 0) { + if(h2_process_pending_input(data, httpc, err) != 0) { + return -1; + } + } + + DEBUGASSERT(data->state.drain == 0); + /* Reset to FALSE to prevent infinite loop in readwrite_data function. */ stream->closed = FALSE; if(stream->error_code != NGHTTP2_NO_ERROR) { - failf(data, "HTTP/2 stream %u was not closed cleanly: error_code = %d", - stream->stream_id, stream->error_code); - *err = CURLE_HTTP2; + failf(data, "HTTP/2 stream %u was not closed cleanly: %s (err %d)", + stream->stream_id, Curl_http2_strerror(stream->error_code), + stream->error_code); + *err = CURLE_HTTP2_STREAM; + return -1; + } + + if(!stream->bodystarted) { + failf(data, "HTTP/2 stream %u was closed cleanly, but before getting " + " all response header fields, teated as error", + stream->stream_id); + *err = CURLE_HTTP2_STREAM; return -1; } + + if(stream->trailer_recvbuf && stream->trailer_recvbuf->buffer) { + trailer_pos = stream->trailer_recvbuf->buffer; + trailer_end = trailer_pos + stream->trailer_recvbuf->size_used; + + for(; trailer_pos < trailer_end;) { + uint32_t n; + memcpy(&n, trailer_pos, sizeof(n)); + trailer_pos += sizeof(n); + + result = Curl_client_write(conn, CLIENTWRITE_HEADER, trailer_pos, n); + if(result) { + *err = result; + return -1; + } + + trailer_pos += n + 1; + } + } + DEBUGF(infof(data, "http2_recv returns 0, http2_handle_stream_close\n")); return 0; } /* + * h2_pri_spec() fills in the pri_spec struct, used by nghttp2 to send weight + * and dependency to the peer. It also stores the updated values in the state + * struct. + */ + +static void h2_pri_spec(struct Curl_easy *data, + nghttp2_priority_spec *pri_spec) +{ + struct HTTP *depstream = (data->set.stream_depends_on? + data->set.stream_depends_on->req.protop:NULL); + int32_t depstream_id = depstream? depstream->stream_id:0; + nghttp2_priority_spec_init(pri_spec, depstream_id, data->set.stream_weight, + data->set.stream_depends_e); + data->state.stream_weight = data->set.stream_weight; + data->state.stream_depends_e = data->set.stream_depends_e; + data->state.stream_depends_on = data->set.stream_depends_on; +} + +/* + * h2_session_send() checks if there's been an update in the priority / + * dependency settings and if so it submits a PRIORITY frame with the updated + * info. + */ +static int h2_session_send(struct Curl_easy *data, + nghttp2_session *h2) +{ + struct HTTP *stream = data->req.protop; + if((data->set.stream_weight != data->state.stream_weight) || + (data->set.stream_depends_e != data->state.stream_depends_e) || + (data->set.stream_depends_on != data->state.stream_depends_on) ) { + /* send new weight and/or dependency */ + nghttp2_priority_spec pri_spec; + int rv; + + h2_pri_spec(data, &pri_spec); + + DEBUGF(infof(data, "Queuing PRIORITY on stream %u (easy %p)\n", + stream->stream_id, data)); + rv = nghttp2_submit_priority(h2, NGHTTP2_FLAG_NONE, stream->stream_id, + &pri_spec); + if(rv) + return rv; + } + + return nghttp2_session_send(h2); +} + +/* * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return * a regular CURLcode value. */ @@ -999,17 +1279,16 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, ssize_t rv; ssize_t nread; struct http_conn *httpc = &conn->proto.httpc; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct HTTP *stream = data->req.protop; (void)sockindex; /* we always do HTTP2 on sockindex 0 */ - /* If stream is closed, return 0 to signal the http routine to close - the connection. We need to handle stream closure here, - otherwise, we may be going to read from underlying connection, - and gets EAGAIN, and we will get stuck there. */ - if(stream->memlen == 0 && stream->closed) { - return http2_handle_stream_close(httpc, data, stream, err); + if(should_close_session(httpc)) { + DEBUGF(infof(data, + "http2_recv: nothing to do in this session\n")); + *err = CURLE_HTTP2; + return -1; } /* Nullify here because we call nghttp2_session_send() and they @@ -1018,7 +1297,7 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, stream->upload_len = 0; /* - * At this point 'stream' is just in the SessionHandle the connection + * At this point 'stream' is just in the Curl_easy the connection * identifies as its owner at this time. */ @@ -1032,13 +1311,13 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, ncopy); stream->nread_header_recvbuf += ncopy; - infof(data, "http2_recv: Got %d bytes from header_recvbuf\n", - (int)ncopy); + DEBUGF(infof(data, "http2_recv: Got %d bytes from header_recvbuf\n", + (int)ncopy)); return ncopy; } - infof(data, "http2_recv: %d bytes buffer at %p (stream %u)\n", - len, mem, stream->stream_id); + DEBUGF(infof(data, "http2_recv: easy %p (stream %u)\n", + data, stream->stream_id)); if((data->state.drain) && stream->memlen) { DEBUGF(infof(data, "http2_recv: DRAIN %zu bytes stream %u!! (%p => %p)\n", @@ -1051,8 +1330,18 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, stream->len = len - stream->memlen; stream->mem = mem; } + if(httpc->pause_stream_id == stream->stream_id && !stream->pausedata) { + /* We have paused nghttp2, but we have no pause data (see + on_data_chunk_recv). */ + httpc->pause_stream_id = 0; + if(h2_process_pending_input(data, httpc, &result) != 0) { + *err = result; + return -1; + } + } } else if(stream->pausedata) { + DEBUGASSERT(httpc->pause_stream_id == stream->stream_id); nread = MIN(len, stream->pauselen); memcpy(mem, stream->pausedata, nread); @@ -1067,9 +1356,21 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, stream->pausedata = NULL; stream->pauselen = 0; + + /* When NGHTTP2_ERR_PAUSE is returned from + data_source_read_callback, we might not process DATA frame + fully. Calling nghttp2_session_mem_recv() again will + continue to process DATA frame, but if there is no incoming + frames, then we have to call it again with 0-length data. + Without this, on_stream_close callback will not be called, + and stream could be hanged. */ + if(h2_process_pending_input(data, httpc, &result) != 0) { + *err = result; + return -1; + } } - infof(data, "http2_recv: returns unpaused %zd bytes on stream %u\n", - nread, stream->stream_id); + DEBUGF(infof(data, "http2_recv: returns unpaused %zd bytes on stream %u\n", + nread, stream->stream_id)); return nread; } else if(httpc->pause_stream_id) { @@ -1096,15 +1397,15 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, nread = ((Curl_recv *)httpc->recv_underlying)( conn, FIRSTSOCKET, httpc->inbuf, H2_BUFSIZE, &result); - if(result == CURLE_AGAIN) { - *err = result; - return -1; - } - if(nread == -1) { - failf(data, "Failed receiving HTTP2 data"); + if(result != CURLE_AGAIN) + failf(data, "Failed receiving HTTP2 data"); + else if(stream->closed) + /* received when the stream was already closed! */ + return http2_handle_stream_close(conn, data, stream, err); + *err = result; - return 0; + return -1; } if(nread == 0) { @@ -1146,16 +1447,22 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, } /* Always send pending frames in nghttp2 session, because nghttp2_session_mem_recv() may queue new frame */ - rv = nghttp2_session_send(httpc->h2); + rv = h2_session_send(data, httpc->h2); if(rv != 0) { *err = CURLE_SEND_ERROR; return 0; } + + if(should_close_session(httpc)) { + DEBUGF(infof(data, "http2_recv: nothing to do in this session\n")); + *err = CURLE_HTTP2; + return -1; + } } if(stream->memlen) { ssize_t retlen = stream->memlen; - infof(data, "http2_recv: returns %zd for stream %u\n", - retlen, stream->stream_id); + DEBUGF(infof(data, "http2_recv: returns %zd for stream %u\n", + retlen, stream->stream_id)); stream->memlen = 0; if(httpc->pause_stream_id == stream->stream_id) { @@ -1164,15 +1471,18 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, DEBUGF(infof(data, "Data returned for PAUSED stream %u\n", stream->stream_id)); } - else + else if(!stream->closed) { + DEBUGASSERT(httpc->drain_total >= data->state.drain); + httpc->drain_total -= data->state.drain; data->state.drain = 0; /* this stream is hereby drained */ + } return retlen; } /* If stream is closed, return 0 to signal the http routine to close the connection */ if(stream->closed) { - return http2_handle_stream_close(httpc, data, stream, err); + return http2_handle_stream_close(conn, data, stream, err); } *err = CURLE_AGAIN; DEBUGF(infof(data, "http2_recv returns AGAIN for stream %u\n", @@ -1184,6 +1494,9 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex, field list. */ #define AUTHORITY_DST_IDX 3 +#define HEADER_OVERFLOW(x) \ + (x.namelen > (uint16_t)-1 || x.valuelen > (uint16_t)-1 - x.namelen) + /* return number of received (decrypted) bytes */ static ssize_t http2_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) @@ -1196,15 +1509,16 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, int rv; struct http_conn *httpc = &conn->proto.httpc; struct HTTP *stream = conn->data->req.protop; - nghttp2_nv *nva; + nghttp2_nv *nva = NULL; size_t nheader; size_t i; size_t authority_idx; char *hdbuf = (char*)mem; - char *end; + char *end, *line_end; nghttp2_data_provider data_prd; int32_t stream_id; nghttp2_session *h2 = httpc->h2; + nghttp2_priority_spec pri_spec; (void)sockindex; @@ -1216,7 +1530,7 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, stream->upload_mem = mem; stream->upload_len = len; nghttp2_session_resume_data(h2, stream->stream_id); - rv = nghttp2_session_send(h2); + rv = h2_session_send(conn->data, h2); if(nghttp2_is_fatal(rv)) { *err = CURLE_SEND_ERROR; return -1; @@ -1228,6 +1542,12 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, stream->upload_mem = NULL; stream->upload_len = 0; + if(should_close_session(httpc)) { + DEBUGF(infof(conn->data, "http2_send: nothing to do in this session\n")); + *err = CURLE_HTTP2; + return -1; + } + if(stream->upload_left) { /* we are sure that we have more data to send here. Calling the following API will make nghttp2_session_want_write() return @@ -1245,12 +1565,16 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, /* Here, we assume the curl http code generate *correct* HTTP header field block */ nheader = 0; - for(i = 0; i < len; ++i) { - if(hdbuf[i] == 0x0a) { + for(i = 1; i < len; ++i) { + if(hdbuf[i] == '\n' && hdbuf[i - 1] == '\r') { ++nheader; + ++i; } } - /* We counted additional 2 \n in the first and last line. We need 3 + if(nheader < 2) + goto fail; + + /* We counted additional 2 \r\n in the first and last line. We need 3 new headers: :method, :path and :scheme. Therefore we need one more space. */ nheader += 1; @@ -1259,81 +1583,133 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, *err = CURLE_OUT_OF_MEMORY; return -1; } + /* Extract :method, :path from request line */ - end = strchr(hdbuf, ' '); - if(!end) + line_end = strstr(hdbuf, "\r\n"); + + /* Method does not contain spaces */ + end = memchr(hdbuf, ' ', line_end - hdbuf); + if(!end || end == hdbuf) goto fail; nva[0].name = (unsigned char *)":method"; - nva[0].namelen = (uint16_t)strlen((char *)nva[0].name); + nva[0].namelen = strlen((char *)nva[0].name); nva[0].value = (unsigned char *)hdbuf; - nva[0].valuelen = (uint16_t)(end - hdbuf); + nva[0].valuelen = (size_t)(end - hdbuf); nva[0].flags = NGHTTP2_NV_FLAG_NONE; + if(HEADER_OVERFLOW(nva[0])) { + failf(conn->data, "Failed sending HTTP request: Header overflow"); + goto fail; + } hdbuf = end + 1; - end = strchr(hdbuf, ' '); - if(!end) + /* Path may contain spaces so scan backwards */ + end = NULL; + for(i = (size_t)(line_end - hdbuf); i; --i) { + if(hdbuf[i - 1] == ' ') { + end = &hdbuf[i - 1]; + break; + } + } + if(!end || end == hdbuf) goto fail; nva[1].name = (unsigned char *)":path"; - nva[1].namelen = (uint16_t)strlen((char *)nva[1].name); + nva[1].namelen = strlen((char *)nva[1].name); nva[1].value = (unsigned char *)hdbuf; - nva[1].valuelen = (uint16_t)(end - hdbuf); + nva[1].valuelen = (size_t)(end - hdbuf); nva[1].flags = NGHTTP2_NV_FLAG_NONE; + if(HEADER_OVERFLOW(nva[1])) { + failf(conn->data, "Failed sending HTTP request: Header overflow"); + goto fail; + } + + hdbuf = end + 1; + end = line_end; nva[2].name = (unsigned char *)":scheme"; - nva[2].namelen = (uint16_t)strlen((char *)nva[2].name); + nva[2].namelen = strlen((char *)nva[2].name); if(conn->handler->flags & PROTOPT_SSL) nva[2].value = (unsigned char *)"https"; else nva[2].value = (unsigned char *)"http"; - nva[2].valuelen = (uint16_t)strlen((char *)nva[2].value); + nva[2].valuelen = strlen((char *)nva[2].value); nva[2].flags = NGHTTP2_NV_FLAG_NONE; - - hdbuf = strchr(hdbuf, 0x0a); - if(!hdbuf) + if(HEADER_OVERFLOW(nva[2])) { + failf(conn->data, "Failed sending HTTP request: Header overflow"); goto fail; - ++hdbuf; + } authority_idx = 0; + i = 3; + while(i < nheader) { + size_t hlen; + int skip = 0; + + hdbuf = line_end + 2; + + line_end = strstr(hdbuf, "\r\n"); + if(line_end == hdbuf) + goto fail; + + /* header continuation lines are not supported */ + if(*hdbuf == ' ' || *hdbuf == '\t') + goto fail; - for(i = 3; i < nheader; ++i) { - end = strchr(hdbuf, ':'); - if(!end) + for(end = hdbuf; end < line_end && *end != ':'; ++end) + ; + if(end == hdbuf || end == line_end) goto fail; - if(end - hdbuf == 4 && Curl_raw_nequal("host", hdbuf, 4)) { + hlen = end - hdbuf; + + if(hlen == 10 && Curl_raw_nequal("connection", hdbuf, 10)) { + /* skip Connection: headers! */ + skip = 1; + --nheader; + } + else if(hlen == 4 && Curl_raw_nequal("host", hdbuf, 4)) { authority_idx = i; nva[i].name = (unsigned char *)":authority"; - nva[i].namelen = (uint16_t)strlen((char *)nva[i].name); + nva[i].namelen = strlen((char *)nva[i].name); } else { nva[i].name = (unsigned char *)hdbuf; - nva[i].namelen = (uint16_t)(end - hdbuf); + nva[i].namelen = (size_t)(end - hdbuf); } hdbuf = end + 1; - for(; *hdbuf == ' '; ++hdbuf); - end = strchr(hdbuf, 0x0d); - if(!end) - goto fail; - nva[i].value = (unsigned char *)hdbuf; - nva[i].valuelen = (uint16_t)(end - hdbuf); - nva[i].flags = NGHTTP2_NV_FLAG_NONE; - - hdbuf = end + 2; - /* Inspect Content-Length header field and retrieve the request - entity length so that we can set END_STREAM to the last DATA - frame. */ - if(nva[i].namelen == 14 && - Curl_raw_nequal("content-length", (char*)nva[i].name, 14)) { - size_t j; - stream->upload_left = 0; - for(j = 0; j < nva[i].valuelen; ++j) { - stream->upload_left *= 10; - stream->upload_left += nva[i].value[j] - '0'; + while(*hdbuf == ' ' || *hdbuf == '\t') + ++hdbuf; + end = line_end; + if(!skip) { + nva[i].value = (unsigned char *)hdbuf; + nva[i].valuelen = (size_t)(end - hdbuf); + nva[i].flags = NGHTTP2_NV_FLAG_NONE; + if(HEADER_OVERFLOW(nva[i])) { + failf(conn->data, "Failed sending HTTP request: Header overflow"); + goto fail; } - DEBUGF(infof(conn->data, - "request content-length=%" - CURL_FORMAT_CURL_OFF_T - "\n", stream->upload_left)); + /* Inspect Content-Length header field and retrieve the request + entity length so that we can set END_STREAM to the last DATA + frame. */ + if(nva[i].namelen == 14 && + Curl_raw_nequal("content-length", (char*)nva[i].name, 14)) { + size_t j; + stream->upload_left = 0; + if(!nva[i].valuelen) + goto fail; + for(j = 0; j < nva[i].valuelen; ++j) { + if(nva[i].value[j] < '0' || nva[i].value[j] > '9') + goto fail; + if(stream->upload_left >= CURL_OFF_T_MAX / 10) + goto fail; + stream->upload_left *= 10; + stream->upload_left += nva[i].value[j] - '0'; + } + DEBUGF(infof(conn->data, + "request content-length=%" + CURL_FORMAT_CURL_OFF_T + "\n", stream->upload_left)); + } + ++i; } } @@ -1346,17 +1722,42 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, nva[i] = authority; } + /* Warn stream may be rejected if cumulative length of headers is too large. + It appears nghttp2 will not send a header frame larger than 64KB. */ + { + size_t acc = 0; + const size_t max_acc = 60000; /* <64KB to account for some overhead */ + + for(i = 0; i < nheader; ++i) { + if(nva[i].namelen > max_acc - acc) + break; + acc += nva[i].namelen; + + if(nva[i].valuelen > max_acc - acc) + break; + acc += nva[i].valuelen; + } + + if(i != nheader) { + infof(conn->data, "http2_send: Warning: The cumulative length of all " + "headers exceeds %zu bytes and that could cause the " + "stream to be rejected.\n", max_acc); + } + } + + h2_pri_spec(conn->data, &pri_spec); + switch(conn->data->set.httpreq) { case HTTPREQ_POST: case HTTPREQ_POST_FORM: case HTTPREQ_PUT: data_prd.read_callback = data_source_read_callback; data_prd.source.ptr = NULL; - stream_id = nghttp2_submit_request(h2, NULL, nva, nheader, + stream_id = nghttp2_submit_request(h2, &pri_spec, nva, nheader, &data_prd, conn->data); break; default: - stream_id = nghttp2_submit_request(h2, NULL, nva, nheader, + stream_id = nghttp2_submit_request(h2, &pri_spec, nva, nheader, NULL, conn->data); } @@ -1372,6 +1773,8 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, stream_id, conn->data); stream->stream_id = stream_id; + /* this does not call h2_session_send() since there can not have been any + * priority upodate since the nghttp2_submit_request() call above */ rv = nghttp2_session_send(h2); if(rv != 0) { @@ -1379,6 +1782,12 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, return -1; } + if(should_close_session(httpc)) { + DEBUGF(infof(conn->data, "http2_send: nothing to do in this session\n")); + *err = CURLE_HTTP2; + return -1; + } + if(stream->stream_id != -1) { /* If whole HEADERS frame was sent off to the underlying socket, the nghttp2 library calls data_source_read_callback. But only @@ -1393,7 +1802,7 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex, return len; - fail: +fail: free(nva); *err = CURLE_SEND_ERROR; return -1; @@ -1432,6 +1841,7 @@ CURLcode Curl_http2_setup(struct connectdata *conn) httpc->nread_inbuf = 0; httpc->pause_stream_id = 0; + httpc->drain_total = 0; conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ conn->httpversion = 20; @@ -1440,6 +1850,10 @@ CURLcode Curl_http2_setup(struct connectdata *conn) infof(conn->data, "Connection state changed (HTTP/2 confirmed)\n"); Curl_multi_connchanged(conn->data->multi); + /* switch on TCP_NODELAY as we need to send off packets without delay for + maximum throughput */ + Curl_tcpnodelay(conn, conn->sock[FIRSTSOCKET]); + return CURLE_OK; } @@ -1450,7 +1864,7 @@ CURLcode Curl_http2_switched(struct connectdata *conn, struct http_conn *httpc = &conn->proto.httpc; int rv; ssize_t nproc; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct HTTP *stream = conn->data->req.protop; result = Curl_http2_setup(conn); @@ -1527,7 +1941,7 @@ CURLcode Curl_http2_switched(struct connectdata *conn, } /* Try to send some frames since we may read SETTINGS already. */ - rv = nghttp2_session_send(httpc->h2); + rv = h2_session_send(data, httpc->h2); if(rv != 0) { failf(data, "nghttp2_session_send() failed: %s(%d)", @@ -1535,6 +1949,12 @@ CURLcode Curl_http2_switched(struct connectdata *conn, return CURLE_HTTP2; } + if(should_close_session(httpc)) { + DEBUGF(infof(data, + "nghttp2_session_send(): nothing to do in this session\n")); + return CURLE_HTTP2; + } + return CURLE_OK; } diff --git a/Utilities/cmcurl/lib/http2.h b/Utilities/cmcurl/lib/http2.h index bb7ad9c..bedbebf 100644 --- a/Utilities/cmcurl/lib/http2.h +++ b/Utilities/cmcurl/lib/http2.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -37,7 +37,11 @@ */ int Curl_http2_ver(char *p, size_t len); +const char *Curl_http2_strerror(uint32_t err); + CURLcode Curl_http2_init(struct connectdata *conn); +void Curl_http2_init_state(struct UrlState *state); +void Curl_http2_init_userset(struct UserDefined *set); CURLcode Curl_http2_send_request(struct connectdata *conn); CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req, struct connectdata *conn); @@ -46,7 +50,7 @@ CURLcode Curl_http2_switched(struct connectdata *conn, const char *data, size_t nread); /* called from Curl_http_setup_conn */ void Curl_http2_setup_conn(struct connectdata *conn); -void Curl_http2_setup_req(struct SessionHandle *data); +void Curl_http2_setup_req(struct Curl_easy *data); #else /* USE_NGHTTP2 */ #define Curl_http2_init(x) CURLE_UNSUPPORTED_PROTOCOL #define Curl_http2_send_request(x) CURLE_UNSUPPORTED_PROTOCOL @@ -55,6 +59,8 @@ void Curl_http2_setup_req(struct SessionHandle *data); #define Curl_http2_switched(x,y,z) CURLE_UNSUPPORTED_PROTOCOL #define Curl_http2_setup_conn(x) #define Curl_http2_setup_req(x) +#define Curl_http2_init_state(x) +#define Curl_http2_init_userset(x) #endif #endif /* HEADER_CURL_HTTP2_H */ diff --git a/Utilities/cmcurl/lib/http_chunks.c b/Utilities/cmcurl/lib/http_chunks.c index 7e91b37..ea17109 100644 --- a/Utilities/cmcurl/lib/http_chunks.c +++ b/Utilities/cmcurl/lib/http_chunks.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -80,7 +80,7 @@ static bool Curl_isxdigit(char digit) { return ( (digit >= 0x30 && digit <= 0x39) /* 0-9 */ || (digit >= 0x41 && digit <= 0x46) /* A-F */ - || (digit >= 0x61 && digit <= 0x66) /* a-f */ ) ? TRUE : FALSE; + || (digit >= 0x61 && digit <= 0x66) /* a-f */) ? TRUE : FALSE; } void Curl_httpchunk_init(struct connectdata *conn) @@ -108,7 +108,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn, ssize_t *wrotep) { CURLcode result=CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct Curl_chunker *ch = &conn->chunk; struct SingleRequest *k = &data->req; size_t piece; diff --git a/Utilities/cmcurl/lib/http_chunks.h b/Utilities/cmcurl/lib/http_chunks.h index 0489eb8..3a8b4dd 100644 --- a/Utilities/cmcurl/lib/http_chunks.h +++ b/Utilities/cmcurl/lib/http_chunks.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/http_digest.c b/Utilities/cmcurl/lib/http_digest.c index 929e2c6..97230e7 100644 --- a/Utilities/cmcurl/lib/http_digest.c +++ b/Utilities/cmcurl/lib/http_digest.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,11 +26,10 @@ #include "urldata.h" #include "rawstr.h" -#include "curl_sasl.h" +#include "vauth/vauth.h" #include "http_digest.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -46,7 +45,7 @@ CURLcode Curl_input_digest(struct connectdata *conn, const char *header) /* rest of the *-authenticate: header */ { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Point to the correct struct with this */ struct digestdata *digest; @@ -65,7 +64,7 @@ CURLcode Curl_input_digest(struct connectdata *conn, while(*header && ISSPACE(*header)) header++; - return Curl_sasl_decode_digest_http_message(header, digest); + return Curl_auth_decode_digest_http_message(header, digest); } CURLcode Curl_output_digest(struct connectdata *conn, @@ -74,7 +73,7 @@ CURLcode Curl_output_digest(struct connectdata *conn, const unsigned char *uripath) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; unsigned char *path; char *tmp; char *response; @@ -135,7 +134,7 @@ CURLcode Curl_output_digest(struct connectdata *conn, Apache servers can be set to do the Digest IE-style automatically using the BrowserMatch feature: - http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie + https://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie Further details on Digest implementation differences: http://www.fngtps.com/2006/09/http-authentication @@ -152,7 +151,7 @@ CURLcode Curl_output_digest(struct connectdata *conn, if(!path) return CURLE_OUT_OF_MEMORY; - result = Curl_sasl_create_digest_http_message(data, userp, passwdp, request, + result = Curl_auth_create_digest_http_message(data, userp, passwdp, request, path, digest, &response, &len); free(path); if(result) @@ -170,10 +169,10 @@ CURLcode Curl_output_digest(struct connectdata *conn, return CURLE_OK; } -void Curl_digest_cleanup(struct SessionHandle *data) +void Curl_digest_cleanup(struct Curl_easy *data) { - Curl_sasl_digest_cleanup(&data->state.digest); - Curl_sasl_digest_cleanup(&data->state.proxydigest); + Curl_auth_digest_cleanup(&data->state.digest); + Curl_auth_digest_cleanup(&data->state.proxydigest); } #endif diff --git a/Utilities/cmcurl/lib/http_digest.h b/Utilities/cmcurl/lib/http_digest.h index d13d563..fd225c7 100644 --- a/Utilities/cmcurl/lib/http_digest.h +++ b/Utilities/cmcurl/lib/http_digest.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -34,7 +34,7 @@ CURLcode Curl_output_digest(struct connectdata *conn, const unsigned char *uripath); #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) -void Curl_digest_cleanup(struct SessionHandle *data); +void Curl_digest_cleanup(struct Curl_easy *data); #else #define Curl_digest_cleanup(x) Curl_nop_stmt #endif diff --git a/Utilities/cmcurl/lib/http_negotiate.c b/Utilities/cmcurl/lib/http_negotiate.c index a1baf29..c39d6f3 100644 --- a/Utilities/cmcurl/lib/http_negotiate.c +++ b/Utilities/cmcurl/lib/http_negotiate.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,156 +22,94 @@ #include "curl_setup.h" -#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) #include "urldata.h" #include "sendf.h" -#include "curl_gssapi.h" #include "rawstr.h" -#include "curl_base64.h" #include "http_negotiate.h" -#include "curl_sasl.h" -#include "url.h" -#include "curl_printf.h" +#include "vauth/vauth.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy, const char *header) { - struct SessionHandle *data = conn->data; - struct negotiatedata *neg_ctx = proxy?&data->state.proxyneg: - &data->state.negotiate; - OM_uint32 major_status, minor_status, discard_st; - gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + struct Curl_easy *data = conn->data; size_t len; - size_t rawlen = 0; - CURLcode result; - if(neg_ctx->context && neg_ctx->status == GSS_S_COMPLETE) { - /* We finished successfully our part of authentication, but server - * rejected it (since we're again here). Exit with an error since we - * can't invent anything better */ - Curl_cleanup_negotiate(data); - return CURLE_LOGIN_DENIED; - } + /* Point to the username, password, service and host */ + const char *userp; + const char *passwdp; + const char *service; + const char *host; - if(!neg_ctx->server_name) { - /* Generate our SPN */ - char *spn = Curl_sasl_build_gssapi_spn( - proxy ? data->set.str[STRING_PROXY_SERVICE_NAME] : - data->set.str[STRING_SERVICE_NAME], - proxy ? conn->proxy.name : conn->host.name); - if(!spn) - return CURLE_OUT_OF_MEMORY; - - /* Populate the SPN structure */ - spn_token.value = spn; - spn_token.length = strlen(spn); - - /* Import the SPN */ - major_status = gss_import_name(&minor_status, &spn_token, - GSS_C_NT_HOSTBASED_SERVICE, - &neg_ctx->server_name); - if(GSS_ERROR(major_status)) { - Curl_gss_log_error(data, minor_status, "gss_import_name() failed: "); - - free(spn); - - return CURLE_OUT_OF_MEMORY; - } + /* Point to the correct struct with this */ + struct negotiatedata *neg_ctx; - free(spn); + if(proxy) { + userp = conn->proxyuser; + passwdp = conn->proxypasswd; + service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; + host = conn->proxy.name; + neg_ctx = &data->state.proxyneg; + } + else { + userp = conn->user; + passwdp = conn->passwd; + service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : "HTTP"; + host = conn->host.name; + neg_ctx = &data->state.negotiate; } + /* Not set means empty */ + if(!userp) + userp = ""; + + if(!passwdp) + passwdp = ""; + + /* Obtain the input token, if any */ header += strlen("Negotiate"); while(*header && ISSPACE(*header)) header++; len = strlen(header); - if(len > 0) { - result = Curl_base64_decode(header, (unsigned char **)&input_token.value, - &rawlen); - if(result) - return result; - - if(!rawlen) { - infof(data, "Negotiate handshake failure (empty challenge message)\n"); - - return CURLE_BAD_CONTENT_ENCODING; + if(!len) { + /* Is this the first call in a new negotiation? */ + if(neg_ctx->context) { + /* The server rejected our authentication and hasn't suppled any more + negotiation mechanisms */ + return CURLE_LOGIN_DENIED; } - - input_token.length = rawlen; - - DEBUGASSERT(input_token.value != NULL); - } - - major_status = Curl_gss_init_sec_context(data, - &minor_status, - &neg_ctx->context, - neg_ctx->server_name, - &Curl_spnego_mech_oid, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - &output_token, - TRUE, - NULL); - Curl_safefree(input_token.value); - - neg_ctx->status = major_status; - if(GSS_ERROR(major_status)) { - if(output_token.value) - gss_release_buffer(&discard_st, &output_token); - Curl_gss_log_error(conn->data, minor_status, - "gss_init_sec_context() failed: "); - return CURLE_OUT_OF_MEMORY; - } - - if(!output_token.value || !output_token.length) { - if(output_token.value) - gss_release_buffer(&discard_st, &output_token); - return CURLE_OUT_OF_MEMORY; } - neg_ctx->output_token = output_token; - - return CURLE_OK; + /* Initilise the security context and decode our challenge */ + return Curl_auth_decode_spnego_message(data, userp, passwdp, service, host, + header, neg_ctx); } CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy) { - struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg: + struct negotiatedata *neg_ctx = proxy ? &conn->data->state.proxyneg : &conn->data->state.negotiate; - char *encoded = NULL; + char *base64 = NULL; size_t len = 0; char *userp; CURLcode result; - OM_uint32 discard_st; - - result = Curl_base64_encode(conn->data, - neg_ctx->output_token.value, - neg_ctx->output_token.length, - &encoded, &len); - if(result) { - gss_release_buffer(&discard_st, &neg_ctx->output_token); - neg_ctx->output_token.value = NULL; - neg_ctx->output_token.length = 0; - return result; - } - if(!encoded || !len) { - gss_release_buffer(&discard_st, &neg_ctx->output_token); - neg_ctx->output_token.value = NULL; - neg_ctx->output_token.length = 0; - return CURLE_REMOTE_ACCESS_DENIED; - } + result = Curl_auth_create_spnego_message(conn->data, neg_ctx, &base64, &len); + if(result) + return result; userp = aprintf("%sAuthorization: Negotiate %s\r\n", proxy ? "Proxy-" : "", - encoded); + base64); + if(proxy) { Curl_safefree(conn->allocptr.proxyuserpwd); conn->allocptr.proxyuserpwd = userp; @@ -181,30 +119,15 @@ CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy) conn->allocptr.userpwd = userp; } - free(encoded); + free(base64); return (userp == NULL) ? CURLE_OUT_OF_MEMORY : CURLE_OK; } -static void cleanup(struct negotiatedata *neg_ctx) -{ - OM_uint32 minor_status; - if(neg_ctx->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&minor_status, &neg_ctx->context, GSS_C_NO_BUFFER); - - if(neg_ctx->output_token.value) - gss_release_buffer(&minor_status, &neg_ctx->output_token); - - if(neg_ctx->server_name != GSS_C_NO_NAME) - gss_release_name(&minor_status, &neg_ctx->server_name); - - memset(neg_ctx, 0, sizeof(*neg_ctx)); -} - -void Curl_cleanup_negotiate(struct SessionHandle *data) +void Curl_cleanup_negotiate(struct Curl_easy *data) { - cleanup(&data->state.negotiate); - cleanup(&data->state.proxyneg); + Curl_auth_spnego_cleanup(&data->state.negotiate); + Curl_auth_spnego_cleanup(&data->state.proxyneg); } -#endif /* HAVE_GSSAPI && !CURL_DISABLE_HTTP && USE_SPNEGO */ +#endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */ diff --git a/Utilities/cmcurl/lib/http_negotiate.h b/Utilities/cmcurl/lib/http_negotiate.h index a8eb980..c64e548 100644 --- a/Utilities/cmcurl/lib/http_negotiate.h +++ b/Utilities/cmcurl/lib/http_negotiate.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -31,11 +31,7 @@ CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy, /* this is for creating Negotiate header output */ CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy); -void Curl_cleanup_negotiate(struct SessionHandle *data); - -#ifdef USE_WINDOWS_SSPI -#define GSS_ERROR(status) (status & 0x80000000) -#endif +void Curl_cleanup_negotiate(struct Curl_easy *data); #endif /* USE_SPNEGO */ diff --git a/Utilities/cmcurl/lib/http_negotiate_sspi.c b/Utilities/cmcurl/lib/http_negotiate_sspi.c deleted file mode 100644 index a50ea96..0000000 --- a/Utilities/cmcurl/lib/http_negotiate_sspi.c +++ /dev/null @@ -1,300 +0,0 @@ -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include "curl_setup.h" - -#ifdef USE_WINDOWS_SSPI - -#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) - -#include "urldata.h" -#include "sendf.h" -#include "rawstr.h" -#include "warnless.h" -#include "curl_base64.h" -#include "curl_sasl.h" -#include "http_negotiate.h" -#include "curl_multibyte.h" -#include "curl_printf.h" - -/* The last #include files should be: */ -#include "curl_memory.h" -#include "memdebug.h" - -CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy, - const char *header) -{ - struct SessionHandle *data = conn->data; - BYTE *input_token = NULL; - SecBufferDesc out_buff_desc; - SecBuffer out_sec_buff; - SecBufferDesc in_buff_desc; - SecBuffer in_sec_buff; - SECURITY_STATUS status; - unsigned long attrs; - TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ - size_t len = 0, input_token_len = 0; - CURLcode result; - - /* Point to the username and password */ - const char *userp; - const char *passwdp; - - /* Point to the correct struct with this */ - struct negotiatedata *neg_ctx; - - if(proxy) { - userp = conn->proxyuser; - passwdp = conn->proxypasswd; - neg_ctx = &data->state.proxyneg; - } - else { - userp = conn->user; - passwdp = conn->passwd; - neg_ctx = &data->state.negotiate; - } - - /* Not set means empty */ - if(!userp) - userp = ""; - - if(!passwdp) - passwdp = ""; - - if(neg_ctx->context && neg_ctx->status == SEC_E_OK) { - /* We finished successfully our part of authentication, but server - * rejected it (since we're again here). Exit with an error since we - * can't invent anything better */ - Curl_cleanup_negotiate(data); - return CURLE_LOGIN_DENIED; - } - - if(!neg_ctx->server_name) { - /* Check proxy auth requested but no given proxy name */ - if(proxy && !conn->proxy.name) - return CURLE_BAD_FUNCTION_ARGUMENT; - - /* Generate our SPN */ - neg_ctx->server_name = Curl_sasl_build_spn( - proxy ? data->set.str[STRING_PROXY_SERVICE_NAME] : - data->set.str[STRING_SERVICE_NAME], - proxy ? conn->proxy.name : conn->host.name); - if(!neg_ctx->server_name) - return CURLE_OUT_OF_MEMORY; - } - - if(!neg_ctx->output_token) { - PSecPkgInfo SecurityPackage; - status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) - TEXT(SP_NAME_NEGOTIATE), - &SecurityPackage); - if(status != SEC_E_OK) - return CURLE_NOT_BUILT_IN; - - /* Allocate input and output buffers according to the max token size - as indicated by the security package */ - neg_ctx->token_max = SecurityPackage->cbMaxToken; - neg_ctx->output_token = malloc(neg_ctx->token_max); - s_pSecFn->FreeContextBuffer(SecurityPackage); - } - - /* Obtain the input token, if any */ - header += strlen("Negotiate"); - while(*header && ISSPACE(*header)) - header++; - - len = strlen(header); - if(!len) { - /* Is this the first call in a new negotiation? */ - if(neg_ctx->context) { - /* The server rejected our authentication and hasn't suppled any more - negotiation mechanisms */ - return CURLE_LOGIN_DENIED; - } - - /* We have to acquire credentials and allocate memory for the context */ - neg_ctx->credentials = malloc(sizeof(CredHandle)); - neg_ctx->context = malloc(sizeof(CtxtHandle)); - - if(!neg_ctx->credentials || !neg_ctx->context) - return CURLE_OUT_OF_MEMORY; - - if(userp && *userp) { - /* Populate our identity structure */ - result = Curl_create_sspi_identity(userp, passwdp, &neg_ctx->identity); - if(result) - return result; - - /* Allow proper cleanup of the identity structure */ - neg_ctx->p_identity = &neg_ctx->identity; - } - else - /* Use the current Windows user */ - neg_ctx->p_identity = NULL; - - /* Acquire our credientials handle */ - neg_ctx->status = - s_pSecFn->AcquireCredentialsHandle(NULL, - (TCHAR *) TEXT(SP_NAME_NEGOTIATE), - SECPKG_CRED_OUTBOUND, NULL, - neg_ctx->p_identity, NULL, NULL, - neg_ctx->credentials, &expiry); - if(neg_ctx->status != SEC_E_OK) - return CURLE_LOGIN_DENIED; - } - else { - result = Curl_base64_decode(header, - (unsigned char **)&input_token, - &input_token_len); - if(result) - return result; - - if(!input_token_len) { - infof(data, - "Negotiate handshake failure (empty challenge message)\n"); - - return CURLE_BAD_CONTENT_ENCODING; - } - } - - /* Setup the "output" security buffer */ - out_buff_desc.ulVersion = SECBUFFER_VERSION; - out_buff_desc.cBuffers = 1; - out_buff_desc.pBuffers = &out_sec_buff; - out_sec_buff.BufferType = SECBUFFER_TOKEN; - out_sec_buff.pvBuffer = neg_ctx->output_token; - out_sec_buff.cbBuffer = curlx_uztoul(neg_ctx->token_max); - - /* Setup the "input" security buffer if present */ - if(input_token) { - in_buff_desc.ulVersion = SECBUFFER_VERSION; - in_buff_desc.cBuffers = 1; - in_buff_desc.pBuffers = &in_sec_buff; - in_sec_buff.BufferType = SECBUFFER_TOKEN; - in_sec_buff.pvBuffer = input_token; - in_sec_buff.cbBuffer = curlx_uztoul(input_token_len); - } - - /* Generate our message */ - neg_ctx->status = s_pSecFn->InitializeSecurityContext( - neg_ctx->credentials, - input_token ? neg_ctx->context : NULL, - neg_ctx->server_name, - ISC_REQ_CONFIDENTIALITY, - 0, - SECURITY_NATIVE_DREP, - input_token ? &in_buff_desc : NULL, - 0, - neg_ctx->context, - &out_buff_desc, - &attrs, - &expiry); - - free(input_token); - - if(GSS_ERROR(neg_ctx->status)) - return CURLE_OUT_OF_MEMORY; - - if(neg_ctx->status == SEC_I_COMPLETE_NEEDED || - neg_ctx->status == SEC_I_COMPLETE_AND_CONTINUE) { - neg_ctx->status = s_pSecFn->CompleteAuthToken(neg_ctx->context, - &out_buff_desc); - if(GSS_ERROR(neg_ctx->status)) - return CURLE_RECV_ERROR; - } - - neg_ctx->output_token_length = out_sec_buff.cbBuffer; - - return CURLE_OK; -} - -CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy) -{ - struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg: - &conn->data->state.negotiate; - char *encoded = NULL; - size_t len = 0; - char *userp; - CURLcode error; - - error = Curl_base64_encode(conn->data, - (const char*)neg_ctx->output_token, - neg_ctx->output_token_length, - &encoded, &len); - if(error) - return error; - - if(!len) - return CURLE_REMOTE_ACCESS_DENIED; - - userp = aprintf("%sAuthorization: Negotiate %s\r\n", proxy ? "Proxy-" : "", - encoded); - - if(proxy) { - Curl_safefree(conn->allocptr.proxyuserpwd); - conn->allocptr.proxyuserpwd = userp; - } - else { - Curl_safefree(conn->allocptr.userpwd); - conn->allocptr.userpwd = userp; - } - free(encoded); - return (userp == NULL) ? CURLE_OUT_OF_MEMORY : CURLE_OK; -} - -static void cleanup(struct negotiatedata *neg_ctx) -{ - /* Free our security context */ - if(neg_ctx->context) { - s_pSecFn->DeleteSecurityContext(neg_ctx->context); - free(neg_ctx->context); - neg_ctx->context = NULL; - } - - /* Free our credentials handle */ - if(neg_ctx->credentials) { - s_pSecFn->FreeCredentialsHandle(neg_ctx->credentials); - free(neg_ctx->credentials); - neg_ctx->credentials = NULL; - } - - /* Free our identity */ - Curl_sspi_free_identity(neg_ctx->p_identity); - neg_ctx->p_identity = NULL; - - /* Free the SPN and output token */ - Curl_safefree(neg_ctx->server_name); - Curl_safefree(neg_ctx->output_token); - - /* Reset any variables */ - neg_ctx->token_max = 0; -} - -void Curl_cleanup_negotiate(struct SessionHandle *data) -{ - cleanup(&data->state.negotiate); - cleanup(&data->state.proxyneg); -} - -#endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */ - -#endif /* USE_WINDOWS_SSPI */ diff --git a/Utilities/cmcurl/lib/curl_ntlm.c b/Utilities/cmcurl/lib/http_ntlm.c index f9ddf50..935df25 100644 --- a/Utilities/cmcurl/lib/curl_ntlm.c +++ b/Utilities/cmcurl/lib/http_ntlm.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,7 +28,7 @@ * NTLM details: * * http://davenport.sourceforge.net/ntlm.html - * http://www.innovation.ch/java/ntlm.html + * https://www.innovation.ch/java/ntlm.html */ #define DEBUG_ME 0 @@ -36,12 +36,10 @@ #include "urldata.h" #include "sendf.h" #include "rawstr.h" -#include "curl_ntlm.h" -#include "curl_ntlm_msgs.h" +#include "http_ntlm.h" #include "curl_ntlm_wb.h" -#include "curl_sasl.h" +#include "vauth/vauth.h" #include "url.h" -#include "curl_printf.h" #if defined(USE_NSS) #include "vtls/nssg.h" @@ -49,7 +47,8 @@ #include "curl_sspi.h" #endif -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -77,7 +76,7 @@ CURLcode Curl_input_ntlm(struct connectdata *conn, header++; if(*header) { - result = Curl_sasl_decode_ntlm_type2_message(conn->data, header, ntlm); + result = Curl_auth_decode_ntlm_type2_message(conn->data, header, ntlm); if(result) return result; @@ -171,7 +170,7 @@ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy) case NTLMSTATE_TYPE1: default: /* for the weird cases we (re)start here */ /* Create a type-1 message */ - result = Curl_sasl_create_ntlm_type1_message(userp, passwdp, ntlm, &base64, + result = Curl_auth_create_ntlm_type1_message(userp, passwdp, ntlm, &base64, &len); if(result) return result; @@ -191,7 +190,7 @@ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy) case NTLMSTATE_TYPE2: /* We already received the type-2 message, create a type-3 message */ - result = Curl_sasl_create_ntlm_type3_message(conn->data, userp, passwdp, + result = Curl_auth_create_ntlm_type3_message(conn->data, userp, passwdp, ntlm, &base64, &len); if(result) return result; @@ -216,7 +215,7 @@ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy) /* connection is already authenticated, * don't send a header in future requests */ ntlm->state = NTLMSTATE_LAST; - + /* fall-through */ case NTLMSTATE_LAST: Curl_safefree(*allocuserpwd); authp->done = TRUE; @@ -228,8 +227,8 @@ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy) void Curl_http_ntlm_cleanup(struct connectdata *conn) { - Curl_sasl_ntlm_cleanup(&conn->ntlm); - Curl_sasl_ntlm_cleanup(&conn->proxyntlm); + Curl_auth_ntlm_cleanup(&conn->ntlm); + Curl_auth_ntlm_cleanup(&conn->proxyntlm); #if defined(NTLM_WB_ENABLED) Curl_ntlm_wb_cleanup(conn); diff --git a/Utilities/cmcurl/lib/curl_ntlm.h b/Utilities/cmcurl/lib/http_ntlm.h index 947eac2..d186bbe 100644 --- a/Utilities/cmcurl/lib/curl_ntlm.h +++ b/Utilities/cmcurl/lib/http_ntlm.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/http_proxy.c b/Utilities/cmcurl/lib/http_proxy.c index 4373d62..c6b05e3 100644 --- a/Utilities/cmcurl/lib/http_proxy.c +++ b/Utilities/cmcurl/lib/http_proxy.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -35,11 +35,11 @@ #include "progress.h" #include "non-ascii.h" #include "connect.h" -#include "curl_printf.h" #include "curlx.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" CURLcode Curl_proxy_connect(struct connectdata *conn) @@ -49,6 +49,8 @@ CURLcode Curl_proxy_connect(struct connectdata *conn) /* for [protocol] tunneled through HTTP proxy */ struct HTTP http_proxy; void *prot_save; + const char *hostname; + int remote_port; CURLcode result; /* BLOCKING */ @@ -67,8 +69,16 @@ CURLcode Curl_proxy_connect(struct connectdata *conn) memset(&http_proxy, 0, sizeof(http_proxy)); conn->data->req.protop = &http_proxy; connkeep(conn, "HTTP proxy CONNECT"); - result = Curl_proxyCONNECT(conn, FIRSTSOCKET, - conn->host.name, conn->remote_port, FALSE); + if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; + if(conn->bits.conn_to_port) + remote_port = conn->conn_to_port; + else + remote_port = conn->remote_port; + result = Curl_proxyCONNECT(conn, FIRSTSOCKET, hostname, + remote_port, FALSE); conn->data->req.protop = prot_save; if(CURLE_OK != result) return result; @@ -97,7 +107,7 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn, bool blocking) { int subversion=0; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; struct SingleRequest *k = &data->req; CURLcode result; curl_socket_t tunnelsocket = conn->sock[sockindex]; @@ -150,13 +160,17 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn, if(!result) { char *host=(char *)""; - const char *proxyconn=""; const char *useragent=""; const char *http = (conn->proxytype == CURLPROXY_HTTP_1_0) ? "1.0" : "1.1"; - char *hostheader= /* host:port with IPv6 support */ - aprintf("%s%s%s:%hu", conn->bits.ipv6_ip?"[":"", - hostname, conn->bits.ipv6_ip?"]":"", + bool ipv6_ip = conn->bits.ipv6_ip; + char *hostheader; + + /* the hostname may be different */ + if(hostname != conn->host.name) + ipv6_ip = (strchr(hostname, ':') != NULL); + hostheader= /* host:port with IPv6 support */ + aprintf("%s%s%s:%hu", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"", remote_port); if(!hostheader) { Curl_add_buffer_free(req_buffer); @@ -171,9 +185,6 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn, return CURLE_OUT_OF_MEMORY; } } - if(!Curl_checkProxyheaders(conn, "Proxy-Connection:")) - proxyconn = "Proxy-Connection: Keep-Alive\r\n"; - if(!Curl_checkProxyheaders(conn, "User-Agent:") && data->set.str[STRING_USERAGENT]) useragent = conn->allocptr.uagent; @@ -183,15 +194,13 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn, "CONNECT %s HTTP/%s\r\n" "%s" /* Host: */ "%s" /* Proxy-Authorization */ - "%s" /* User-Agent */ - "%s", /* Proxy-Connection */ + "%s", /* User-Agent */ hostheader, http, host, conn->allocptr.proxyuserpwd? conn->allocptr.proxyuserpwd:"", - useragent, - proxyconn); + useragent); if(host && *host) free(host); diff --git a/Utilities/cmcurl/lib/http_proxy.h b/Utilities/cmcurl/lib/http_proxy.h index 9c4f020..fd04330 100644 --- a/Utilities/cmcurl/lib/http_proxy.h +++ b/Utilities/cmcurl/lib/http_proxy.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/idn_win32.c b/Utilities/cmcurl/lib/idn_win32.c index b369723..8dc300b 100644 --- a/Utilities/cmcurl/lib/idn_win32.c +++ b/Utilities/cmcurl/lib/idn_win32.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -29,9 +29,10 @@ #ifdef USE_WIN32_IDN #include "curl_multibyte.h" - #include "curl_memory.h" -/* The last #include file should be: */ +#include "warnless.h" + + /* The last #include file should be: */ #include "memdebug.h" #ifdef WANT_IDN_PROTOTYPES @@ -64,45 +65,47 @@ WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags, #define IDN_MAX_LENGTH 255 -int curl_win32_idn_to_ascii(const char *in, char **out); -int curl_win32_ascii_to_idn(const char *in, size_t in_len, char **out_utf8); +bool curl_win32_idn_to_ascii(const char *in, char **out); +bool curl_win32_ascii_to_idn(const char *in, char **out); -int curl_win32_idn_to_ascii(const char *in, char **out) +bool curl_win32_idn_to_ascii(const char *in, char **out) { + bool success = FALSE; + wchar_t *in_w = Curl_convert_UTF8_to_wchar(in); if(in_w) { wchar_t punycode[IDN_MAX_LENGTH]; - if(IdnToAscii(0, in_w, -1, punycode, IDN_MAX_LENGTH) == 0) { - wprintf(L"ERROR %d converting to Punycode\n", GetLastError()); - free(in_w); - return 0; - } + int chars = IdnToAscii(0, in_w, -1, punycode, IDN_MAX_LENGTH); free(in_w); - - *out = Curl_convert_wchar_to_UTF8(punycode); - if(!*out) - return 0; + if(chars) { + *out = Curl_convert_wchar_to_UTF8(punycode); + if(*out) + success = TRUE; + } } - return 1; + + return success; } -int curl_win32_ascii_to_idn(const char *in, size_t in_len, char **out_utf8) +bool curl_win32_ascii_to_idn(const char *in, char **out) { - (void)in_len; /* unused */ - if(in) { - WCHAR unicode[IDN_MAX_LENGTH]; + bool success = FALSE; - if(IdnToUnicode(0, (wchar_t *)in, -1, unicode, IDN_MAX_LENGTH) == 0) { - wprintf(L"ERROR %d converting to Punycode\n", GetLastError()); - return 0; - } - else { - *out_utf8 = Curl_convert_wchar_to_UTF8(unicode); - if(!*out_utf8) - return 0; + wchar_t *in_w = Curl_convert_UTF8_to_wchar(in); + if(in_w) { + size_t in_len = wcslen(in_w) + 1; + wchar_t unicode[IDN_MAX_LENGTH]; + int chars = IdnToUnicode(0, in_w, curlx_uztosi(in_len), + unicode, IDN_MAX_LENGTH); + free(in_w); + if(chars) { + *out = Curl_convert_wchar_to_UTF8(unicode); + if(*out) + success = TRUE; } } - return 1; + + return success; } #endif /* USE_WIN32_IDN */ diff --git a/Utilities/cmcurl/lib/if2ip.c b/Utilities/cmcurl/lib/if2ip.c index 6e6f969..2f92b2d 100644 --- a/Utilities/cmcurl/lib/if2ip.c +++ b/Utilities/cmcurl/lib/if2ip.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -53,10 +53,9 @@ #include "inet_ntop.h" #include "strequal.h" #include "if2ip.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* ------------------------------------------------------------------ */ @@ -68,7 +67,7 @@ unsigned int Curl_ipv6_scope(const struct sockaddr *sa) (void) sa; #else if(sa->sa_family == AF_INET6) { - const struct sockaddr_in6 * sa6 = (const struct sockaddr_in6 *) sa; + const struct sockaddr_in6 * sa6 = (const struct sockaddr_in6 *)(void *) sa; const unsigned char * b = sa6->sin6_addr.s6_addr; unsigned short w = (unsigned short) ((b[0] << 8) | b[1]); @@ -152,11 +151,12 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, continue; } - addr = &((struct sockaddr_in6 *)iface->ifa_addr)->sin6_addr; + addr = + &((struct sockaddr_in6 *)(void *)iface->ifa_addr)->sin6_addr; #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID /* Include the scope of this interface as part of the address */ - scopeid = - ((struct sockaddr_in6 *)iface->ifa_addr)->sin6_scope_id; + scopeid = ((struct sockaddr_in6 *)(void *)iface->ifa_addr) + ->sin6_scope_id; /* If given, scope id should match. */ if(remote_scope_id && scopeid != remote_scope_id) { @@ -171,7 +171,8 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, } else #endif - addr = &((struct sockaddr_in *)iface->ifa_addr)->sin_addr; + addr = + &((struct sockaddr_in *)(void *)iface->ifa_addr)->sin_addr; res = IF2IP_FOUND; ip = (char *) Curl_inet_ntop(af, addr, ipstr, sizeof(ipstr)); snprintf(buf, buf_size, "%s%s", ip, scope); diff --git a/Utilities/cmcurl/lib/if2ip.h b/Utilities/cmcurl/lib/if2ip.h index 78bb0bd..f3a7ff0 100644 --- a/Utilities/cmcurl/lib/if2ip.h +++ b/Utilities/cmcurl/lib/if2ip.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/imap.c b/Utilities/cmcurl/lib/imap.c index e6d83f2..123ea3b 100644 --- a/Utilities/cmcurl/lib/imap.c +++ b/Utilities/cmcurl/lib/imap.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -80,10 +80,10 @@ #include "rawstr.h" #include "curl_sasl.h" #include "warnless.h" -#include "curl_printf.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* Local API functions */ @@ -98,7 +98,7 @@ static int imap_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done); static CURLcode imap_setup_connection(struct connectdata *conn); -static char *imap_atom(const char *str); +static char *imap_atom(const char *str, bool escape_only); static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...); static CURLcode imap_parse_url_options(struct connectdata *conn); static CURLcode imap_parse_url_path(struct connectdata *conn); @@ -227,7 +227,11 @@ static const struct SASLproto saslimap = { #ifdef USE_SSL static void imap_to_imaps(struct connectdata *conn) { + /* Change the connection handler */ conn->handler = &Curl_handler_imaps; + + /* Set the connection's upgraded to TLS flag */ + conn->tls_upgraded = TRUE; } #else #define imap_to_imaps(x) Curl_nop_stmt @@ -360,8 +364,8 @@ static bool imap_endofresp(struct connectdata *conn, char *line, size_t len, a space and optionally some text as per RFC-3501 for the AUTHENTICATE and APPEND commands and as outlined in Section 4. Examples of RFC-4959 but some e-mail servers ignore this and only send a single + instead. */ - if((len == 3 && !memcmp("+", line, 1)) || - (len >= 2 && !memcmp("+ ", line, 2))) { + if(imap && !imap->custom && ((len == 3 && !memcmp("+", line, 1)) || + (len >= 2 && !memcmp("+ ", line, 2)))) { switch(imapc->state) { /* States which are interested in continuation responses */ case IMAP_AUTHENTICATE: @@ -540,8 +544,8 @@ static CURLcode imap_perform_login(struct connectdata *conn) } /* Make sure the username and password are in the correct atom format */ - user = imap_atom(conn->user); - passwd = imap_atom(conn->passwd); + user = imap_atom(conn->user, false); + passwd = imap_atom(conn->passwd, false); /* Send the LOGIN command */ result = imap_sendf(conn, "LOGIN %s %s", user ? user : "", @@ -644,7 +648,7 @@ static CURLcode imap_perform_authentication(struct connectdata *conn) static CURLcode imap_perform_list(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; char *mailbox; @@ -653,8 +657,8 @@ static CURLcode imap_perform_list(struct connectdata *conn) result = imap_sendf(conn, "%s%s", imap->custom, imap->custom_params ? imap->custom_params : ""); else { - /* Make sure the mailbox is in the correct atom format */ - mailbox = imap_atom(imap->mailbox ? imap->mailbox : ""); + /* Make sure the mailbox is in the correct atom format if necessary */ + mailbox = imap->mailbox ? imap_atom(imap->mailbox, true) : strdup(""); if(!mailbox) return CURLE_OUT_OF_MEMORY; @@ -679,7 +683,7 @@ static CURLcode imap_perform_list(struct connectdata *conn) static CURLcode imap_perform_select(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; char *mailbox; @@ -695,7 +699,7 @@ static CURLcode imap_perform_select(struct connectdata *conn) } /* Make sure the mailbox is in the correct atom format */ - mailbox = imap_atom(imap->mailbox); + mailbox = imap_atom(imap->mailbox, false); if(!mailbox) return CURLE_OUT_OF_MEMORY; @@ -769,7 +773,7 @@ static CURLcode imap_perform_append(struct connectdata *conn) } /* Make sure the mailbox is in the correct atom format */ - mailbox = imap_atom(imap->mailbox); + mailbox = imap_atom(imap->mailbox, false); if(!mailbox) return CURLE_OUT_OF_MEMORY; @@ -836,7 +840,7 @@ static CURLcode imap_state_servergreet_resp(struct connectdata *conn, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -856,7 +860,7 @@ static CURLcode imap_state_capability_resp(struct connectdata *conn, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct imap_conn *imapc = &conn->proto.imapc; const char *line = data->state.buffer; size_t wordlen; @@ -906,8 +910,8 @@ static CURLcode imap_state_capability_resp(struct connectdata *conn, wordlen -= 5; /* Test the word for a matching authentication mechanism */ - if((mechbit = Curl_sasl_decode_mech(line, wordlen, &llen)) && - llen == wordlen) + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) imapc->sasl.authmechs |= mechbit; } @@ -943,7 +947,7 @@ static CURLcode imap_state_starttls_resp(struct connectdata *conn, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -967,7 +971,7 @@ static CURLcode imap_state_auth_resp(struct connectdata *conn, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct imap_conn *imapc = &conn->proto.imapc; saslprogress progress; @@ -1001,7 +1005,7 @@ static CURLcode imap_state_login_resp(struct connectdata *conn, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -1016,9 +1020,10 @@ static CURLcode imap_state_login_resp(struct connectdata *conn, return result; } -/* For LIST responses */ -static CURLcode imap_state_list_resp(struct connectdata *conn, int imapcode, - imapstate instate) +/* For LIST and SEARCH responses */ +static CURLcode imap_state_listsearch_resp(struct connectdata *conn, + int imapcode, + imapstate instate) { CURLcode result = CURLE_OK; char *line = conn->data->state.buffer; @@ -1046,7 +1051,7 @@ static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = conn->data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; const char *line = data->state.buffer; @@ -1093,12 +1098,12 @@ static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; const char *ptr = data->state.buffer; bool parsed = FALSE; - curl_off_t size; + curl_off_t size = 0; (void)instate; /* no use for this yet */ @@ -1206,7 +1211,7 @@ static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* No use for this yet */ @@ -1245,31 +1250,6 @@ static CURLcode imap_state_append_final_resp(struct connectdata *conn, return result; } -/* For SEARCH responses */ -static CURLcode imap_state_search_resp(struct connectdata *conn, int imapcode, - imapstate instate) -{ - CURLcode result = CURLE_OK; - char *line = conn->data->state.buffer; - size_t len = strlen(line); - - (void)instate; /* No use for this yet */ - - if(imapcode == '*') { - /* Temporarily add the LF character back and send as body to the client */ - line[len] = '\n'; - result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1); - line[len] = '\0'; - } - else if(imapcode != 'O') - result = CURLE_QUOTE_ERROR; /* TODO: Fix error code */ - else - /* End of DO phase */ - state(conn, IMAP_STOP); - - return result; -} - static CURLcode imap_statemach_act(struct connectdata *conn) { CURLcode result = CURLE_OK; @@ -1323,7 +1303,7 @@ static CURLcode imap_statemach_act(struct connectdata *conn) break; case IMAP_LIST: - result = imap_state_list_resp(conn, imapcode, imapc->state); + result = imap_state_listsearch_resp(conn, imapcode, imapc->state); break; case IMAP_SELECT: @@ -1347,7 +1327,7 @@ static CURLcode imap_statemach_act(struct connectdata *conn) break; case IMAP_SEARCH: - result = imap_state_search_resp(conn, imapcode, imapc->state); + result = imap_state_listsearch_resp(conn, imapcode, imapc->state); break; case IMAP_LOGOUT: @@ -1391,12 +1371,12 @@ static CURLcode imap_block_statemach(struct connectdata *conn) return result; } -/* Allocate and initialize the struct IMAP for the current SessionHandle if +/* Allocate and initialize the struct IMAP for the current Curl_easy if required */ static CURLcode imap_init(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap; imap = data->req.protop = calloc(sizeof(struct IMAP), 1); @@ -1476,16 +1456,12 @@ static CURLcode imap_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; (void)premature; if(!imap) - /* When the easy handle is removed from the multi interface while libcurl - is still trying to resolve the host name, the IMAP struct is not yet - initialized. However, the removal action calls Curl_done() which in - turn calls this function, so we simply return success. */ return CURLE_OK; if(status) { @@ -1508,8 +1484,7 @@ static CURLcode imap_done(struct connectdata *conn, CURLcode status, TODO: when the multi interface is used, this _really_ should be using the imap_multi_statemach function but we have no general support for - non-blocking DONE operations, not in the multi state machine and with - Curl_done() invokes on several places in the code! + non-blocking DONE operations! */ if(!result) result = imap_block_statemach(conn); @@ -1543,7 +1518,7 @@ static CURLcode imap_perform(struct connectdata *conn, bool *connected, { /* This is IMAP and no proxy */ CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; bool selected = FALSE; @@ -1708,7 +1683,7 @@ static CURLcode imap_regular_transfer(struct connectdata *conn, { CURLcode result = CURLE_OK; bool connected = FALSE; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Make sure size is unknown at this point */ data->req.size = -1; @@ -1731,13 +1706,17 @@ static CURLcode imap_regular_transfer(struct connectdata *conn, static CURLcode imap_setup_connection(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Initialise the IMAP layer */ CURLcode result = imap_init(conn); if(result) return result; + /* Clear the TLS upgraded flag */ + conn->tls_upgraded = FALSE; + + /* Set up the proxy if necessary */ if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) { /* Unless we have asked to tunnel IMAP operations through the proxy, we switch and use HTTP operations only */ @@ -1815,38 +1794,49 @@ static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...) * The returned string needs to be freed. * */ -static char *imap_atom(const char *str) +static char *imap_atom(const char *str, bool escape_only) { + /* !checksrc! disable PARENBRACE 1 */ + const char atom_specials[] = "(){ %*]"; const char *p1; char *p2; size_t backsp_count = 0; size_t quote_count = 0; - bool space_exists = FALSE; + bool others_exists = FALSE; size_t newlen = 0; char *newstr = NULL; if(!str) return NULL; - /* Count any unescaped characters */ + /* Look for "atom-specials", counting the backslash and quote characters as + these will need escapping */ p1 = str; while(*p1) { if(*p1 == '\\') backsp_count++; else if(*p1 == '"') quote_count++; - else if(*p1 == ' ') - space_exists = TRUE; + else if(!escape_only) { + const char *p3 = atom_specials; + + while(*p3 && !others_exists) { + if(*p1 == *p3) + others_exists = TRUE; + + p3++; + } + } p1++; } - /* Does the input contain any unescaped characters? */ - if(!backsp_count && !quote_count && !space_exists) + /* Does the input contain any "atom-special" characters? */ + if(!backsp_count && !quote_count && !others_exists) return strdup(str); /* Calculate the new string length */ - newlen = strlen(str) + backsp_count + quote_count + (space_exists ? 2 : 0); + newlen = strlen(str) + backsp_count + quote_count + (others_exists ? 2 : 0); /* Allocate the new string */ newstr = (char *) malloc((newlen + 1) * sizeof(char)); @@ -1855,7 +1845,7 @@ static char *imap_atom(const char *str) /* Surround the string in quotes if necessary */ p2 = newstr; - if(space_exists) { + if(others_exists) { newstr[0] = '"'; newstr[newlen - 1] = '"'; p2++; @@ -1981,7 +1971,7 @@ static CURLcode imap_parse_url_path(struct connectdata *conn) { /* The imap struct is already initialised in imap_connect() */ CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; const char *begin = data->state.path; const char *ptr = begin; @@ -2111,7 +2101,7 @@ static CURLcode imap_parse_url_path(struct connectdata *conn) static CURLcode imap_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; diff --git a/Utilities/cmcurl/lib/imap.h b/Utilities/cmcurl/lib/imap.h index 3189daa..5e0e228 100644 --- a/Utilities/cmcurl/lib/imap.h +++ b/Utilities/cmcurl/lib/imap.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -49,9 +49,9 @@ typedef enum { IMAP_LAST /* never used */ } imapstate; -/* This IMAP struct is used in the SessionHandle. All IMAP data that is +/* This IMAP struct is used in the Curl_easy. All IMAP data that is connection-oriented must be in imap_conn to properly deal with the fact that - perhaps the SessionHandle is changed between the times the connection is + perhaps the Curl_easy is changed between the times the connection is used. */ struct IMAP { curl_pp_transfer transfer; diff --git a/Utilities/cmcurl/lib/inet_ntop.c b/Utilities/cmcurl/lib/inet_ntop.c index da9a3ab..416005c 100644 --- a/Utilities/cmcurl/lib/inet_ntop.c +++ b/Utilities/cmcurl/lib/inet_ntop.c @@ -32,9 +32,8 @@ #include <arpa/inet.h> #endif -#include "curl_printf.h" - #include "inet_ntop.h" +#include "curl_printf.h" #define IN6ADDRSZ 16 #define INADDRSZ 4 @@ -57,10 +56,10 @@ static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size) tmp[0] = '\0'; (void)snprintf(tmp, sizeof(tmp), "%d.%d.%d.%d", - ((int)((unsigned char)src[0])) & 0xff, - ((int)((unsigned char)src[1])) & 0xff, - ((int)((unsigned char)src[2])) & 0xff, - ((int)((unsigned char)src[3])) & 0xff); + ((int)((unsigned char)src[0])) & 0xff, + ((int)((unsigned char)src[1])) & 0xff, + ((int)((unsigned char)src[2])) & 0xff, + ((int)((unsigned char)src[3])) & 0xff); len = strlen(tmp); if(len == 0 || len >= size) { diff --git a/Utilities/cmcurl/lib/inet_ntop.h b/Utilities/cmcurl/lib/inet_ntop.h index cc4bdbb..9f44612 100644 --- a/Utilities/cmcurl/lib/inet_ntop.h +++ b/Utilities/cmcurl/lib/inet_ntop.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/inet_pton.c b/Utilities/cmcurl/lib/inet_pton.c index f50b365..cf8b88a 100644 --- a/Utilities/cmcurl/lib/inet_pton.c +++ b/Utilities/cmcurl/lib/inet_pton.c @@ -188,8 +188,8 @@ inet_pton6(const char *src, unsigned char *dst) } if(tp + INT16SZ > endp) return (0); - *tp++ = (unsigned char) (val >> 8) & 0xff; - *tp++ = (unsigned char) val & 0xff; + *tp++ = (unsigned char) ((val >> 8) & 0xff); + *tp++ = (unsigned char) (val & 0xff); saw_xdigit = 0; val = 0; continue; @@ -205,8 +205,8 @@ inet_pton6(const char *src, unsigned char *dst) if(saw_xdigit) { if(tp + INT16SZ > endp) return (0); - *tp++ = (unsigned char) (val >> 8) & 0xff; - *tp++ = (unsigned char) val & 0xff; + *tp++ = (unsigned char) ((val >> 8) & 0xff); + *tp++ = (unsigned char) (val & 0xff); } if(colonp != NULL) { /* diff --git a/Utilities/cmcurl/lib/inet_pton.h b/Utilities/cmcurl/lib/inet_pton.h index 43c5491..9188d95 100644 --- a/Utilities/cmcurl/lib/inet_pton.h +++ b/Utilities/cmcurl/lib/inet_pton.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/krb5.c b/Utilities/cmcurl/lib/krb5.c index ad7dd67..87ce8ee 100644 --- a/Utilities/cmcurl/lib/krb5.c +++ b/Utilities/cmcurl/lib/krb5.c @@ -2,7 +2,7 @@ * * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). - * Copyright (c) 2004 - 2015 Daniel Stenberg + * Copyright (c) 2004 - 2016 Daniel Stenberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -47,15 +47,12 @@ #include "sendf.h" #include "curl_sec.h" #include "warnless.h" -#include "curl_printf.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" -#define LOCAL_ADDR (&conn->local_addr) -#define REMOTE_ADDR conn->ip_addr->ai_addr - static int krb5_init(void *app_data) { @@ -153,28 +150,31 @@ krb5_auth(void *app_data, struct connectdata *conn) const char *host = conn->host.name; ssize_t nread; curl_socklen_t l = sizeof(conn->local_addr); - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result; - const char *service = "ftp", *srv_host = "host"; + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + "ftp"; + const char *srv_host = "host"; gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp; OM_uint32 maj, min; gss_name_t gssname; gss_ctx_id_t *context = app_data; struct gss_channel_bindings_struct chan; size_t base64_sz = 0; + struct sockaddr_in **remote_addr = + (struct sockaddr_in **)&conn->ip_addr->ai_addr; if(getsockname(conn->sock[FIRSTSOCKET], - (struct sockaddr *)LOCAL_ADDR, &l) < 0) + (struct sockaddr *)&conn->local_addr, &l) < 0) perror("getsockname()"); chan.initiator_addrtype = GSS_C_AF_INET; chan.initiator_address.length = l - 4; - chan.initiator_address.value = - &((struct sockaddr_in *)LOCAL_ADDR)->sin_addr.s_addr; + chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr; chan.acceptor_addrtype = GSS_C_AF_INET; chan.acceptor_address.length = l - 4; - chan.acceptor_address.value = - &((struct sockaddr_in *)REMOTE_ADDR)->sin_addr.s_addr; + chan.acceptor_address.value = &(*remote_addr)->sin_addr.s_addr; chan.application_data.length = 0; chan.application_data.value = NULL; @@ -183,9 +183,9 @@ krb5_auth(void *app_data, struct connectdata *conn) /* this really shouldn't be repeated here, but can't help it */ if(service == srv_host) { result = Curl_ftpsendf(conn, "AUTH GSSAPI"); - if(result) return -2; + if(Curl_GetFTPResponse(&nread, conn, NULL)) return -1; diff --git a/Utilities/cmcurl/lib/ldap.c b/Utilities/cmcurl/lib/ldap.c index 4d91282..a164627 100644 --- a/Utilities/cmcurl/lib/ldap.c +++ b/Utilities/cmcurl/lib/ldap.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -76,9 +76,8 @@ #include "curl_base64.h" #include "rawstr.h" #include "connect.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -193,7 +192,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done) LDAPMessage *ldapmsg = NULL; LDAPMessage *entryIterator; int num = 0; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; int ldap_proto = LDAP_VERSION3; int ldap_ssl = 0; char *val_b64 = NULL; @@ -228,7 +227,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done) goto quit; } - /* Get the URL scheme ( either ldap or ldaps ) */ + /* Get the URL scheme (either ldap or ldaps) */ if(conn->given->flags & PROTOPT_SSL) ldap_ssl = 1; infof(data, "LDAP local: trying to establish %s connection\n", @@ -717,7 +716,7 @@ static int str2scope (const char *p) return LDAP_SCOPE_BASE; if(strequal(p, "sub")) return LDAP_SCOPE_SUBTREE; - if(strequal( p, "subtree")) + if(strequal(p, "subtree")) return LDAP_SCOPE_SUBTREE; return (-1); } diff --git a/Utilities/cmcurl/lib/libcurl.rc b/Utilities/cmcurl/lib/libcurl.rc index 47b944a..50b365d 100644 --- a/Utilities/cmcurl/lib/libcurl.rc +++ b/Utilities/cmcurl/lib/libcurl.rc @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -44,7 +44,7 @@ BEGIN BEGIN BLOCK "040904b0" BEGIN - VALUE "CompanyName", "The cURL library, http://curl.haxx.se/\0" + VALUE "CompanyName", "The cURL library, https://curl.haxx.se/\0" VALUE "FileDescription", "libcurl Shared Library\0" VALUE "FileVersion", LIBCURL_VERSION "\0" VALUE "InternalName", "libcurl\0" @@ -52,7 +52,7 @@ BEGIN VALUE "ProductName", "The cURL library\0" VALUE "ProductVersion", LIBCURL_VERSION "\0" VALUE "LegalCopyright", "© " LIBCURL_COPYRIGHT "\0" - VALUE "License", "http://curl.haxx.se/docs/copyright.html\0" + VALUE "License", "https://curl.haxx.se/docs/copyright.html\0" END END diff --git a/Utilities/cmcurl/lib/llist.c b/Utilities/cmcurl/lib/llist.c index 40bb628..482aaa0 100644 --- a/Utilities/cmcurl/lib/llist.c +++ b/Utilities/cmcurl/lib/llist.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,6 +22,8 @@ #include "curl_setup.h" +#include <curl/curl.h> + #include "llist.h" #include "curl_memory.h" diff --git a/Utilities/cmcurl/lib/llist.h b/Utilities/cmcurl/lib/llist.h index 27ddb71..39ff408 100644 --- a/Utilities/cmcurl/lib/llist.h +++ b/Utilities/cmcurl/lib/llist.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/md5.c b/Utilities/cmcurl/lib/md5.c index b604c10..84adb99 100644 --- a/Utilities/cmcurl/lib/md5.c +++ b/Utilities/cmcurl/lib/md5.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,6 +24,8 @@ #ifndef CURL_DISABLE_CRYPTO_AUTH +#include <curl/curl.h> + #include "curl_md5.h" #include "curl_hmac.h" #include "warnless.h" diff --git a/Utilities/cmcurl/lib/memdebug.c b/Utilities/cmcurl/lib/memdebug.c index dd8889b..ccbf461 100644 --- a/Utilities/cmcurl/lib/memdebug.c +++ b/Utilities/cmcurl/lib/memdebug.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,10 +26,12 @@ #include <curl/curl.h> -#include "curl_printf.h" #include "urldata.h" #define MEMDEBUG_NODEFINES /* don't redefine the standard functions */ + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -117,7 +119,7 @@ void curl_memdebug(const char *logname) logfile = stderr; #ifdef MEMDEBUG_LOG_SYNC /* Flush the log file after every line so the log isn't lost in a crash */ - setvbuf(logfile, (char *)NULL, _IOLBF, 0); + setbuf(logfile, (char *)NULL); #endif } } @@ -146,6 +148,7 @@ static bool countcheck(const char *func, int line, const char *source) /* log to stderr also */ fprintf(stderr, "LIMIT %s:%d %s reached memlimit\n", source, line, func); + fflush(logfile); /* because it might crash now */ } SET_ERRNO(ENOMEM); return TRUE; /* RETURN ERROR! */ @@ -153,10 +156,6 @@ static bool countcheck(const char *func, int line, const char *source) else memsize--; /* countdown */ - /* log the countdown */ - if(source) - curl_memlog("LIMIT %s:%d %ld ALLOCS left\n", - source, line, memsize); } diff --git a/Utilities/cmcurl/lib/memdebug.h b/Utilities/cmcurl/lib/memdebug.h index cfac1e0..835dab3 100644 --- a/Utilities/cmcurl/lib/memdebug.h +++ b/Utilities/cmcurl/lib/memdebug.h @@ -8,11 +8,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,10 +28,6 @@ * as well as the library. Do not mix with library internals! */ -#include "curl_setup.h" - -#include <curl/curl.h> - #define CURL_MT_LOGFNAME_BUFSIZE 512 #define logfile curl_debuglogfile @@ -57,17 +53,17 @@ CURL_EXTERN void curl_memlog(const char *format, ...); /* file descriptor manipulators */ CURL_EXTERN curl_socket_t curl_socket(int domain, int type, int protocol, - int line , const char *source); + int line, const char *source); CURL_EXTERN void curl_mark_sclose(curl_socket_t sockfd, - int line , const char *source); + int line, const char *source); CURL_EXTERN int curl_sclose(curl_socket_t sockfd, - int line , const char *source); + int line, const char *source); CURL_EXTERN curl_socket_t curl_accept(curl_socket_t s, void *a, void *alen, int line, const char *source); #ifdef HAVE_SOCKETPAIR CURL_EXTERN int curl_socketpair(int domain, int type, int protocol, curl_socket_t socket_vector[2], - int line , const char *source); + int line, const char *source); #endif /* FILE functions */ @@ -103,6 +99,7 @@ CURL_EXTERN int curl_fclose(FILE *file, int line, const char *source); # endif #endif +#undef socket #define socket(domain,type,protocol)\ curl_socket(domain, type, protocol, __LINE__, __FILE__) #undef accept /* for those with accept as a macro */ diff --git a/Utilities/cmcurl/lib/mprintf.c b/Utilities/cmcurl/lib/mprintf.c index 7412dc3..380c3d6 100644 --- a/Utilities/cmcurl/lib/mprintf.c +++ b/Utilities/cmcurl/lib/mprintf.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1999 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1999 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -32,15 +32,10 @@ * * If you ever want truly portable and good *printf() clones, the project that * took on from here is named 'Trio' and you find more details on the trio web - * page at http://daniel.haxx.se/trio/ + * page at https://daniel.haxx.se/projects/trio/ */ #include "curl_setup.h" - -#if defined(DJGPP) && (DJGPP_MINOR < 4) -#undef _MPRINTF_REPLACE /* don't use x_was_used() here */ -#endif - #include <curl/mprintf.h> #include "curl_memory.h" @@ -461,22 +456,24 @@ static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos, if(flags & FLAGS_WIDTHPARAM) { /* we have the width specified from a parameter, so we make that parameter's info setup properly */ - vto[i].width = width - 1; - i = width - 1; - vto[i].type = FORMAT_WIDTH; - vto[i].flags = FLAGS_NEW; - vto[i].precision = vto[i].width = 0; /* can't use width or precision - of width! */ + long k = width - 1; + vto[i].width = k; + vto[k].type = FORMAT_WIDTH; + vto[k].flags = FLAGS_NEW; + /* can't use width or precision of width! */ + vto[k].width = 0; + vto[k].precision = 0; } if(flags & FLAGS_PRECPARAM) { /* we have the precision specified from a parameter, so we make that parameter's info setup properly */ - vto[i].precision = precision - 1; - i = precision - 1; - vto[i].type = FORMAT_WIDTH; - vto[i].flags = FLAGS_NEW; - vto[i].precision = vto[i].width = 0; /* can't use width or precision - of width! */ + long k = precision - 1; + vto[i].precision = k; + vto[k].type = FORMAT_WIDTH; + vto[k].flags = FLAGS_NEW; + /* can't use width or precision of width! */ + vto[k].width = 0; + vto[k].precision = 0; } *endpos++ = fmt + 1; /* end of this sequence */ } @@ -484,11 +481,15 @@ static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos, /* Read the arg list parameters into our data list */ for(i=0; i<max_param; i++) { - if((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH)) { - /* Width/precision arguments must be read before the main argument - * they are attached to - */ - vto[i + 1].data.num.as_signed = (mp_intmax_t)va_arg(arglist, int); + /* Width/precision arguments must be read before the main argument + they are attached to */ + if(vto[i].flags & FLAGS_WIDTHPARAM) { + vto[vto[i].width].data.num.as_signed = + (mp_intmax_t)va_arg(arglist, int); + } + if(vto[i].flags & FLAGS_PRECPARAM) { + vto[vto[i].precision].data.num.as_signed = + (mp_intmax_t)va_arg(arglist, int); } switch (vto[i].type) { @@ -576,6 +577,11 @@ static int dprintf_formatf( va_stack_t *p; + /* 'workend' points to the final buffer byte position, but with an extra + byte as margin to avoid the (false?) warning Coverity gives us + otherwise */ + char *workend = &work[sizeof(work) - 2]; + /* Do the actual %-code parsing */ dprintf_Pass1(format, vto, endpos, ap_save); @@ -605,6 +611,8 @@ static int dprintf_formatf( /* Used to convert negative in positive. */ mp_intmax_t signed_num; + char *w; + if(*f != '%') { /* This isn't a format spec, so write everything out until the next one OR end of string is reached. */ @@ -641,16 +649,30 @@ static int dprintf_formatf( p = &vto[param]; /* pick up the specified width */ - if(p->flags & FLAGS_WIDTHPARAM) + if(p->flags & FLAGS_WIDTHPARAM) { width = (long)vto[p->width].data.num.as_signed; + param_num++; /* since the width is extracted from a parameter, we + must skip that to get to the next one properly */ + if(width < 0) { + /* "A negative field width is taken as a '-' flag followed by a + positive field width." */ + width = -width; + p->flags |= FLAGS_LEFT; + p->flags &= ~FLAGS_PAD_NIL; + } + } else width = p->width; /* pick up the specified precision */ if(p->flags & FLAGS_PRECPARAM) { prec = (long)vto[p->precision].data.num.as_signed; - param_num++; /* since the precision is extraced from a parameter, we + param_num++; /* since the precision is extracted from a parameter, we must skip that to get to the next one properly */ + if(prec < 0) + /* "A negative precision is taken as if the precision were + omitted." */ + prec = -1; } else if(p->flags & FLAGS_PREC) prec = p->precision; @@ -711,72 +733,68 @@ static int dprintf_formatf( number: /* Number of base BASE. */ - { - char *workend = &work[sizeof(work) - 1]; - char *w; - - /* Supply a default precision if none was given. */ - if(prec == -1) - prec = 1; - - /* Put the number in WORK. */ - w = workend; - while(num > 0) { - *w-- = digits[num % base]; - num /= base; - } - width -= (long)(workend - w); - prec -= (long)(workend - w); - if(is_alt && base == 8 && prec <= 0) { - *w-- = '0'; - --width; - } + /* Supply a default precision if none was given. */ + if(prec == -1) + prec = 1; - if(prec > 0) { - width -= prec; - while(prec-- > 0) - *w-- = '0'; - } + /* Put the number in WORK. */ + w = workend; + while(num > 0) { + *w-- = digits[num % base]; + num /= base; + } + width -= (long)(workend - w); + prec -= (long)(workend - w); - if(is_alt && base == 16) - width -= 2; + if(is_alt && base == 8 && prec <= 0) { + *w-- = '0'; + --width; + } - if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE)) - --width; + if(prec > 0) { + width -= prec; + while(prec-- > 0) + *w-- = '0'; + } - if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL)) - while(width-- > 0) - OUTCHAR(' '); + if(is_alt && base == 16) + width -= 2; - if(is_neg) - OUTCHAR('-'); - else if(p->flags & FLAGS_SHOWSIGN) - OUTCHAR('+'); - else if(p->flags & FLAGS_SPACE) - OUTCHAR(' '); + if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE)) + --width; - if(is_alt && base == 16) { - OUTCHAR('0'); - if(p->flags & FLAGS_UPPER) - OUTCHAR('X'); - else - OUTCHAR('x'); - } + if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR(' '); - if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL)) - while(width-- > 0) - OUTCHAR('0'); + if(is_neg) + OUTCHAR('-'); + else if(p->flags & FLAGS_SHOWSIGN) + OUTCHAR('+'); + else if(p->flags & FLAGS_SPACE) + OUTCHAR(' '); + + if(is_alt && base == 16) { + OUTCHAR('0'); + if(p->flags & FLAGS_UPPER) + OUTCHAR('X'); + else + OUTCHAR('x'); + } - /* Write the number. */ - while(++w <= workend) { - OUTCHAR(*w); - } + if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR('0'); - if(p->flags & FLAGS_LEFT) - while(width-- > 0) - OUTCHAR(' '); + /* Write the number. */ + while(++w <= workend) { + OUTCHAR(*w); } + + if(p->flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); break; case FORMAT_STRING: @@ -805,7 +823,7 @@ static int dprintf_formatf( else len = strlen(str); - width -= (long)len; + width -= (len > LONG_MAX) ? LONG_MAX : (long)len; if(p->flags & FLAGS_ALT) OUTCHAR('"'); diff --git a/Utilities/cmcurl/lib/multi.c b/Utilities/cmcurl/lib/multi.c index 0052087..8bb9366 100644 --- a/Utilities/cmcurl/lib/multi.c +++ b/Utilities/cmcurl/lib/multi.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -42,9 +42,9 @@ #include "multihandle.h" #include "pipeline.h" #include "sigpipe.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* @@ -61,15 +61,15 @@ #define CURL_MULTI_HANDLE 0x000bab1e #define GOOD_MULTI_HANDLE(x) \ - ((x) && (((struct Curl_multi *)(x))->type == CURL_MULTI_HANDLE)) + ((x) && (x)->type == CURL_MULTI_HANDLE) static void singlesocket(struct Curl_multi *multi, - struct SessionHandle *data); + struct Curl_easy *data); static int update_timer(struct Curl_multi *multi); static CURLMcode add_next_timeout(struct timeval now, struct Curl_multi *multi, - struct SessionHandle *d); + struct Curl_easy *d); static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms); @@ -99,14 +99,23 @@ static const char * const statename[]={ static void multi_freetimeout(void *a, void *b); +/* function pointer called once when switching TO a state */ +typedef void (*init_multistate_func)(struct Curl_easy *data); + /* always use this function to change state, to make debugging easier */ -static void mstate(struct SessionHandle *data, CURLMstate state +static void mstate(struct Curl_easy *data, CURLMstate state #ifdef DEBUGBUILD , int lineno #endif ) { CURLMstate oldstate = data->mstate; + static const init_multistate_func finit[CURLM_STATE_LAST] = { + NULL, + NULL, + Curl_init_CONNECT, /* CONNECT */ + /* the rest is NULL too */ + }; #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS) (void) lineno; @@ -127,7 +136,7 @@ static void mstate(struct SessionHandle *data, CURLMstate state connection_id = data->easy_conn->connection_id; infof(data, - "STATE: %s => %s handle %p; line %d (connection #%ld) \n", + "STATE: %s => %s handle %p; line %d (connection #%ld)\n", statename[oldstate], statename[data->mstate], (void *)data, lineno, connection_id); } @@ -136,6 +145,10 @@ static void mstate(struct SessionHandle *data, CURLMstate state if(state == CURLM_STATE_COMPLETED) /* changing to COMPLETED means there's one less easy handle 'alive' */ data->multi->num_alive--; + + /* if this state has an init-function, run it */ + if(finit[state]) + finit[state](data); } #ifndef DEBUGBUILD @@ -149,7 +162,7 @@ static void mstate(struct SessionHandle *data, CURLMstate state */ struct Curl_sh_entry { - struct SessionHandle *easy; + struct Curl_easy *easy; int action; /* what action READ/WRITE this socket waits for */ curl_socket_t socket; /* mainly to ease debugging */ void *socketp; /* settable by users with curl_multi_assign() */ @@ -159,13 +172,22 @@ struct Curl_sh_entry { #define SH_READ 1 #define SH_WRITE 2 +/* look up a given socket in the socket hash, skip invalid sockets */ +static struct Curl_sh_entry *sh_getentry(struct curl_hash *sh, + curl_socket_t s) +{ + if(s != CURL_SOCKET_BAD) + /* only look for proper sockets */ + return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); + return NULL; +} + /* make sure this socket is present in the hash for this handle */ static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh, curl_socket_t s, - struct SessionHandle *data) + struct Curl_easy *data) { - struct Curl_sh_entry *there = - Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); + struct Curl_sh_entry *there = sh_getentry(sh, s); struct Curl_sh_entry *check; if(there) @@ -193,15 +215,9 @@ static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh, /* delete the given socket + handle from the hash */ static void sh_delentry(struct curl_hash *sh, curl_socket_t s) { - struct Curl_sh_entry *there = - Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); - - if(there) { - /* this socket is in the hash */ - /* We remove the hash entry. (This'll end up in a call to - sh_freeentry().) */ - Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); - } + /* We remove the hash entry. This will end up in a call to + sh_freeentry(). */ + Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); } /* @@ -218,15 +234,15 @@ static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void) k1_len; (void) k2_len; - return (*((int *) k1)) == (*((int *) k2)); + return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2)); } static size_t hash_fd(void *key, size_t key_length, size_t slots_num) { - int fd = *((int *) key); + curl_socket_t fd = *((curl_socket_t *) key); (void) key_length; - return (fd % (int)slots_num); + return (fd % slots_num); } /* @@ -318,7 +334,7 @@ struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */ /* -1 means it not set by user, use the default value */ multi->maxconnects = -1; - return (CURLM *) multi; + return multi; error: @@ -334,25 +350,23 @@ struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */ return NULL; } -CURLM *curl_multi_init(void) +struct Curl_multi *curl_multi_init(void) { return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE, CURL_CONNECTION_HASH_SIZE); } -CURLMcode curl_multi_add_handle(CURLM *multi_handle, - CURL *easy_handle) +CURLMcode curl_multi_add_handle(struct Curl_multi *multi, + struct Curl_easy *data) { struct curl_llist *timeoutlist; - struct Curl_multi *multi = (struct Curl_multi *)multi_handle; - struct SessionHandle *data = (struct SessionHandle *)easy_handle; /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ - if(!GOOD_EASY_HANDLE(easy_handle)) + if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from adding same easy handle more than once and prevent @@ -401,14 +415,14 @@ CURLMcode curl_multi_add_handle(CURLM *multi_handle, data->state.conn_cache = &multi->conn_cache; /* This adds the new entry at the 'end' of the doubly-linked circular - list of SessionHandle structs to try and maintain a FIFO queue so + list of Curl_easy structs to try and maintain a FIFO queue so the pipelined requests are in order. */ /* We add this new entry last in the list. */ data->next = NULL; /* end of the line */ if(multi->easyp) { - struct SessionHandle *last = multi->easylp; + struct Curl_easy *last = multi->easylp; last->next = data; data->prev = last; multi->easylp = data; /* the new last node */ @@ -419,8 +433,8 @@ CURLMcode curl_multi_add_handle(CURLM *multi_handle, multi->easylp = multi->easyp = data; /* both first and last */ } - /* make the SessionHandle refer back to this multi handle */ - data->multi = multi_handle; + /* make the Curl_easy refer back to this multi handle */ + data->multi = multi; /* Set the timeout for this handle to expire really soon so that it will be taken care of even when this handle is added in the midst of operation @@ -468,12 +482,171 @@ static void debug_print_sock_hash(void *p) } #endif -CURLMcode curl_multi_remove_handle(CURLM *multi_handle, - CURL *curl_handle) +/* Mark the connection as 'idle', or close it if the cache is full. + Returns TRUE if the connection is kept, or FALSE if it was closed. */ +static bool +ConnectionDone(struct Curl_easy *data, struct connectdata *conn) +{ + /* data->multi->maxconnects can be negative, deal with it. */ + size_t maxconnects = + (data->multi->maxconnects < 0) ? data->multi->num_easy * 4: + data->multi->maxconnects; + struct connectdata *conn_candidate = NULL; + + /* Mark the current connection as 'unused' */ + conn->inuse = FALSE; + + if(maxconnects > 0 && + data->state.conn_cache->num_connections > maxconnects) { + infof(data, "Connection cache is full, closing the oldest one.\n"); + + conn_candidate = Curl_oldest_idle_connection(data); + + if(conn_candidate) { + /* Set the connection's owner correctly */ + conn_candidate->data = data; + + /* the winner gets the honour of being disconnected */ + (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE); + } + } + + return (conn_candidate == conn) ? FALSE : TRUE; +} + +static CURLcode multi_done(struct connectdata **connp, + CURLcode status, /* an error if this is called + after an error was detected */ + bool premature) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - struct SessionHandle *easy = curl_handle; - struct SessionHandle *data = easy; + CURLcode result; + struct connectdata *conn; + struct Curl_easy *data; + + DEBUGASSERT(*connp); + + conn = *connp; + data = conn->data; + + DEBUGF(infof(data, "multi_done\n")); + + if(data->state.done) + /* Stop if multi_done() has already been called */ + return CURLE_OK; + + Curl_getoff_all_pipelines(data, conn); + + /* Cleanup possible redirect junk */ + free(data->req.newurl); + data->req.newurl = NULL; + free(data->req.location); + data->req.location = NULL; + + switch(status) { + case CURLE_ABORTED_BY_CALLBACK: + case CURLE_READ_ERROR: + case CURLE_WRITE_ERROR: + /* When we're aborted due to a callback return code it basically have to + be counted as premature as there is trouble ahead if we don't. We have + many callbacks and protocols work differently, we could potentially do + this more fine-grained in the future. */ + premature = TRUE; + default: + break; + } + + /* this calls the protocol-specific function pointer previously set */ + if(conn->handler->done) + result = conn->handler->done(conn, status, premature); + else + result = status; + + if(CURLE_ABORTED_BY_CALLBACK != result) { + /* avoid this if we already aborted by callback to avoid this calling + another callback */ + CURLcode rc = Curl_pgrsDone(conn); + if(!result && rc) + result = CURLE_ABORTED_BY_CALLBACK; + } + + if((!premature && + conn->send_pipe->size + conn->recv_pipe->size != 0 && + !data->set.reuse_forbid && + !conn->bits.close)) { + /* Stop if pipeline is not empty and we do not have to close + connection. */ + DEBUGF(infof(data, "Connection still in use, no more multi_done now!\n")); + return CURLE_OK; + } + + data->state.done = TRUE; /* called just now! */ + Curl_resolver_cancel(conn); + + if(conn->dns_entry) { + Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ + conn->dns_entry = NULL; + } + + /* if the transfer was completed in a paused state there can be buffered + data left to write and then kill */ + free(data->state.tempwrite); + data->state.tempwrite = NULL; + + /* if data->set.reuse_forbid is TRUE, it means the libcurl client has + forced us to close this connection. This is ignored for requests taking + place in a NTLM authentication handshake + + if conn->bits.close is TRUE, it means that the connection should be + closed in spite of all our efforts to be nice, due to protocol + restrictions in our or the server's end + + if premature is TRUE, it means this connection was said to be DONE before + the entire request operation is complete and thus we can't know in what + state it is for re-using, so we're forced to close it. In a perfect world + we can add code that keep track of if we really must close it here or not, + but currently we have no such detail knowledge. + */ + + if((data->set.reuse_forbid +#if defined(USE_NTLM) + && !(conn->ntlm.state == NTLMSTATE_TYPE2 || + conn->proxyntlm.state == NTLMSTATE_TYPE2) +#endif + ) || conn->bits.close || premature) { + CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */ + + /* If we had an error already, make sure we return that one. But + if we got a new error, return that. */ + if(!result && res2) + result = res2; + } + else { + /* the connection is no longer in use */ + if(ConnectionDone(data, conn)) { + /* remember the most recently used connection */ + data->state.lastconnect = conn; + + infof(data, "Connection #%ld to host %s left intact\n", + conn->connection_id, + conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname); + } + else + data->state.lastconnect = NULL; + } + + *connp = NULL; /* to make the caller of this function better detect that + this was either closed or handed over to the connection + cache here, and therefore cannot be used from this point on + */ + Curl_free_request_state(data); + + return result; +} + +CURLMcode curl_multi_remove_handle(struct Curl_multi *multi, + struct Curl_easy *data) +{ + struct Curl_easy *easy = data; bool premature; bool easy_owns_conn; struct curl_llist_element *e; @@ -483,7 +656,7 @@ CURLMcode curl_multi_remove_handle(CURLM *multi_handle, return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ - if(!GOOD_EASY_HANDLE(curl_handle)) + if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from trying to remove same easy handle more than once */ @@ -513,8 +686,8 @@ CURLMcode curl_multi_remove_handle(CURLM *multi_handle, request but not received its response yet, we need to close connection. */ connclose(data->easy_conn, "Removed with partial response"); - /* Set connection owner so that Curl_done() closes it. - We can safely do this here since connection is killed. */ + /* Set connection owner so that the DONE function closes it. We can + safely do this here since connection is killed. */ data->easy_conn->data = easy; easy_owns_conn = TRUE; } @@ -524,12 +697,6 @@ CURLMcode curl_multi_remove_handle(CURLM *multi_handle, curl_easy_cleanup is called. */ Curl_expire(data, 0); - /* destroy the timeout list that is held in the easy handle */ - if(data->state.timeoutlist) { - Curl_llist_destroy(data->state.timeoutlist, NULL); - data->state.timeoutlist = NULL; - } - if(data->dns.hostcachetype == HCACHE_MULTI) { /* stop using the multi handle's DNS cache */ data->dns.hostcache = NULL; @@ -538,24 +705,31 @@ CURLMcode curl_multi_remove_handle(CURLM *multi_handle, if(data->easy_conn) { - /* we must call Curl_done() here (if we still "own it") so that we don't - leave a half-baked one around */ + /* we must call multi_done() here (if we still own the connection) so that + we don't leave a half-baked one around */ if(easy_owns_conn) { - /* Curl_done() clears the conn->data field to lose the association + /* multi_done() clears the conn->data field to lose the association between the easy handle and the connection Note that this ignores the return code simply because there's nothing really useful to do with it anyway! */ - (void)Curl_done(&data->easy_conn, data->result, premature); + (void)multi_done(&data->easy_conn, data->result, premature); } else - /* Clear connection pipelines, if Curl_done above was not called */ + /* Clear connection pipelines, if multi_done above was not called */ Curl_getoff_all_pipelines(data, data->easy_conn); } Curl_wildcard_dtor(&data->wildcard); + /* destroy the timeout list that is held in the easy handle, do this *after* + multi_done() as that may actually call Curl_expire that uses this */ + if(data->state.timeoutlist) { + Curl_llist_destroy(data->state.timeoutlist, NULL); + data->state.timeoutlist = NULL; + } + /* as this was using a shared connection cache we clear the pointer to that since we're not part of that multi handle anymore */ data->state.conn_cache = NULL; @@ -613,7 +787,7 @@ bool Curl_pipeline_wanted(const struct Curl_multi *multi, int bits) return (multi && (multi->pipelining & bits)) ? TRUE : FALSE; } -void Curl_multi_handlePipeBreak(struct SessionHandle *data) +void Curl_multi_handlePipeBreak(struct Curl_easy *data) { data->easy_conn = NULL; } @@ -666,7 +840,7 @@ static int domore_getsock(struct connectdata *conn, } /* returns bitmapped flags for this handle and its sockets */ -static int multi_getsock(struct SessionHandle *data, +static int multi_getsock(struct Curl_easy *data, curl_socket_t *socks, /* points to numsocks number of sockets */ int numsocks) @@ -732,15 +906,14 @@ static int multi_getsock(struct SessionHandle *data, } -CURLMcode curl_multi_fdset(CURLM *multi_handle, +CURLMcode curl_multi_fdset(struct Curl_multi *multi, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *exc_fd_set, int *max_fd) { /* Scan through all the easy handles to get the file descriptors set. Some easy handles may not have connected to the remote host yet, and then we must make sure that is done. */ - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - struct SessionHandle *data; + struct Curl_easy *data; int this_max_fd=-1; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int bitmap; @@ -782,14 +955,13 @@ CURLMcode curl_multi_fdset(CURLM *multi_handle, return CURLM_OK; } -CURLMcode curl_multi_wait(CURLM *multi_handle, +CURLMcode curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - struct SessionHandle *data; + struct Curl_easy *data; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int bitmap; unsigned int i; @@ -797,6 +969,7 @@ CURLMcode curl_multi_wait(CURLM *multi_handle, unsigned int curlfds; struct pollfd *ufds = NULL; long timeout_internal; + int retcode = 0; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; @@ -889,18 +1062,20 @@ CURLMcode curl_multi_wait(CURLM *multi_handle, } if(nfds) { + int pollrc; /* wait... */ - infof(data, "Curl_poll(%d ds, %d ms)\n", nfds, timeout_ms); - i = Curl_poll(ufds, nfds, timeout_ms); + pollrc = Curl_poll(ufds, nfds, timeout_ms); + DEBUGF(infof(data, "Curl_poll(%d ds, %d ms) == %d\n", + nfds, timeout_ms, pollrc)); - if(i) { - unsigned int j; + if(pollrc > 0) { + retcode = pollrc; /* copy revents results from the poll to the curl_multi_wait poll struct, the bit values of the actual underlying poll() implementation may not be the same as the ones in the public libcurl API! */ - for(j = 0; j < extra_nfds; j++) { + for(i = 0; i < extra_nfds; i++) { unsigned short mask = 0; - unsigned r = ufds[curlfds + j].revents; + unsigned r = ufds[curlfds + i].revents; if(r & POLLIN) mask |= CURL_WAIT_POLLIN; @@ -909,16 +1084,14 @@ CURLMcode curl_multi_wait(CURLM *multi_handle, if(r & POLLPRI) mask |= CURL_WAIT_POLLPRI; - extra_fds[j].revents = mask; + extra_fds[i].revents = mask; } } } - else - i = 0; free(ufds); if(ret) - *ret = i; + *ret = retcode; return CURLM_OK; } @@ -951,7 +1124,7 @@ static bool multi_ischanged(struct Curl_multi *multi, bool clear) } CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, - struct SessionHandle *data, + struct Curl_easy *data, struct connectdata *conn) { CURLMcode rc; @@ -972,9 +1145,142 @@ CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, return rc; } +static CURLcode multi_reconnect_request(struct connectdata **connp) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = *connp; + struct Curl_easy *data = conn->data; + + /* This was a re-use of a connection and we got a write error in the + * DO-phase. Then we DISCONNECT this connection and have another attempt to + * CONNECT and then DO again! The retry cannot possibly find another + * connection to re-use, since we only keep one possible connection for + * each. */ + + infof(data, "Re-used connection seems dead, get a new one\n"); + + connclose(conn, "Reconnect dead connection"); /* enforce close */ + result = multi_done(&conn, result, FALSE); /* we are so done with this */ + + /* conn may no longer be a good pointer, clear it to avoid mistakes by + parent functions */ + *connp = NULL; + + /* + * We need to check for CURLE_SEND_ERROR here as well. This could happen + * when the request failed on a FTP connection and thus multi_done() itself + * tried to use the connection (again). + */ + if(!result || (CURLE_SEND_ERROR == result)) { + bool async; + bool protocol_done = TRUE; + + /* Now, redo the connect and get a new connection */ + result = Curl_connect(data, connp, &async, &protocol_done); + if(!result) { + /* We have connected or sent away a name resolve query fine */ + + conn = *connp; /* setup conn to again point to something nice */ + if(async) { + /* Now, if async is TRUE here, we need to wait for the name + to resolve */ + result = Curl_resolver_wait_resolv(conn, NULL); + if(result) + return result; + + /* Resolved, continue with the connection */ + result = Curl_async_resolved(conn, &protocol_done); + if(result) + return result; + } + } + } + + return result; +} + +/* + * do_complete is called when the DO actions are complete. + * + * We init chunking and trailer bits to their default values here immediately + * before receiving any header data for the current request in the pipeline. + */ +static void do_complete(struct connectdata *conn) +{ + conn->data->req.chunk=FALSE; + conn->data->req.maxfd = (conn->sockfd>conn->writesockfd? + conn->sockfd:conn->writesockfd)+1; + Curl_pgrsTime(conn->data, TIMER_PRETRANSFER); +} + +static CURLcode multi_do(struct connectdata **connp, bool *done) +{ + CURLcode result=CURLE_OK; + struct connectdata *conn = *connp; + struct Curl_easy *data = conn->data; + + if(conn->handler->do_it) { + /* generic protocol-specific function pointer set in curl_connect() */ + result = conn->handler->do_it(conn, done); + + /* This was formerly done in transfer.c, but we better do it here */ + if((CURLE_SEND_ERROR == result) && conn->bits.reuse) { + /* + * If the connection is using an easy handle, call reconnect + * to re-establish the connection. Otherwise, let the multi logic + * figure out how to re-establish the connection. + */ + if(!data->multi) { + result = multi_reconnect_request(connp); + + if(!result) { + /* ... finally back to actually retry the DO phase */ + conn = *connp; /* re-assign conn since multi_reconnect_request + creates a new connection */ + result = conn->handler->do_it(conn, done); + } + } + else + return result; + } + + if(!result && *done) + /* do_complete must be called after the protocol-specific DO function */ + do_complete(conn); + } + return result; +} + +/* + * multi_do_more() is called during the DO_MORE multi state. It is basically a + * second stage DO state which (wrongly) was introduced to support FTP's + * second connection. + * + * TODO: A future libcurl should be able to work away this state. + * + * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to + * DOING state there's more work to do! + */ + +static CURLcode multi_do_more(struct connectdata *conn, int *complete) +{ + CURLcode result=CURLE_OK; + + *complete = 0; + + if(conn->handler->do_more) + result = conn->handler->do_more(conn, complete); + + if(!result && (*complete == 1)) + /* do_complete must be called after the protocol-specific DO function */ + do_complete(conn); + + return result; +} + static CURLMcode multi_runsingle(struct Curl_multi *multi, struct timeval now, - struct SessionHandle *data) + struct Curl_easy *data) { struct Curl_message *msg = NULL; bool connected; @@ -1057,7 +1363,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, failf(data, "Operation timed out after %ld milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes received", - Curl_tvdiff(k->now, data->progress.t_startsingle), + Curl_tvdiff(now, data->progress.t_startsingle), k->bytecount, k->size); } else { @@ -1074,7 +1380,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, disconnect_conn = TRUE; } result = CURLE_OPERATION_TIMEDOUT; - (void)Curl_done(&data->easy_conn, result, TRUE); + (void)multi_done(&data->easy_conn, result, TRUE); /* Skip the statemachine and go directly to error handling section. */ goto statemachine_end; } @@ -1152,9 +1458,17 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, { struct Curl_dns_entry *dns = NULL; struct connectdata *conn = data->easy_conn; + const char *hostname; + + if(conn->bits.proxy) + hostname = conn->proxy.name; + else if(conn->bits.conn_to_host) + hostname = conn->conn_to_host.name; + else + hostname = conn->host.name; /* check if we have the name resolved by now */ - dns = Curl_fetch_addr(conn, conn->host.name, (int)conn->port); + dns = Curl_fetch_addr(conn, hostname, (int)conn->port); if(dns) { #ifdef CURLRES_ASYNCH @@ -1162,7 +1476,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, conn->async.done = TRUE; #endif result = CURLE_OK; - infof(data, "Hostname was found in DNS cache\n"); + infof(data, "Hostname '%s' was found in DNS cache\n", hostname); } if(!dns) @@ -1215,17 +1529,19 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */ result = Curl_http_connect(data->easy_conn, &protocol_connect); - rc = CURLM_CALL_MULTI_PERFORM; if(data->easy_conn->bits.proxy_connect_closed) { + rc = CURLM_CALL_MULTI_PERFORM; /* connect back to proxy again */ result = CURLE_OK; - Curl_done(&data->easy_conn, CURLE_OK, FALSE); + multi_done(&data->easy_conn, CURLE_OK, FALSE); multistate(data, CURLM_STATE_CONNECT); } else if(!result) { - if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_COMPLETE) + if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_COMPLETE) { + rc = CURLM_CALL_MULTI_PERFORM; /* initiate protocol connect phase */ multistate(data, CURLM_STATE_SENDPROTOCONNECT); + } } break; #endif @@ -1261,7 +1577,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, else if(result) { /* failure detected */ Curl_posttransfer(data); - Curl_done(&data->easy_conn, result, TRUE); + multi_done(&data->easy_conn, result, TRUE); disconnect_conn = TRUE; } break; @@ -1278,7 +1594,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, else if(result) { /* failure detected */ Curl_posttransfer(data); - Curl_done(&data->easy_conn, result, TRUE); + multi_done(&data->easy_conn, result, TRUE); disconnect_conn = TRUE; } break; @@ -1302,9 +1618,9 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, } else { /* Perform the protocol's DO action */ - result = Curl_do(&data->easy_conn, &dophase_done); + result = multi_do(&data->easy_conn, &dophase_done); - /* When Curl_do() returns failure, data->easy_conn might be NULL! */ + /* When multi_do() returns failure, data->easy_conn might be NULL! */ if(!result) { if(!dophase_done) { @@ -1313,7 +1629,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, struct WildcardData *wc = &data->wildcard; if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { /* skip some states if it is important */ - Curl_done(&data->easy_conn, CURLE_OK, FALSE); + multi_done(&data->easy_conn, CURLE_OK, FALSE); multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; break; @@ -1360,7 +1676,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, retry = (newurl)?TRUE:FALSE; Curl_posttransfer(data); - drc = Curl_done(&data->easy_conn, result, FALSE); + drc = multi_done(&data->easy_conn, result, FALSE); /* When set to retry the connection, we must to go back to * the CONNECT state */ @@ -1395,7 +1711,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, /* failure detected */ Curl_posttransfer(data); if(data->easy_conn) - Curl_done(&data->easy_conn, result, FALSE); + multi_done(&data->easy_conn, result, FALSE); disconnect_conn = TRUE; } } @@ -1417,7 +1733,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, else { /* failure detected */ Curl_posttransfer(data); - Curl_done(&data->easy_conn, result, FALSE); + multi_done(&data->easy_conn, result, FALSE); disconnect_conn = TRUE; } break; @@ -1426,10 +1742,10 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, /* * When we are connected, DO MORE and then go DO_DONE */ - result = Curl_do_more(data->easy_conn, &control); + result = multi_do_more(data->easy_conn, &control); /* No need to remove this handle from the send pipeline here since that - is done in Curl_done() */ + is done in multi_done() */ if(!result) { if(control) { /* if positive, advance to DO_DONE @@ -1446,7 +1762,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, else { /* failure detected */ Curl_posttransfer(data); - Curl_done(&data->easy_conn, result, FALSE); + multi_done(&data->easy_conn, result, FALSE); disconnect_conn = TRUE; } break; @@ -1484,7 +1800,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, result = Curl_speedcheck(data, now); if(( (data->set.max_send_speed == 0) || - (data->progress.ulspeed < data->set.max_send_speed )) && + (data->progress.ulspeed < data->set.max_send_speed)) && ( (data->set.max_recv_speed == 0) || (data->progress.dlspeed < data->set.max_recv_speed))) multistate(data, CURLM_STATE_PERFORM); @@ -1566,11 +1882,12 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, * happened in the data connection. */ - if(!(data->easy_conn->handler->flags & PROTOPT_DUAL)) + if(!(data->easy_conn->handler->flags & PROTOPT_DUAL) && + result != CURLE_HTTP2_STREAM) connclose(data->easy_conn, "Transfer returned error"); Curl_posttransfer(data); - Curl_done(&data->easy_conn, result, FALSE); + multi_done(&data->easy_conn, result, FALSE); } else if(done) { followtype follow=FOLLOW_NONE; @@ -1601,7 +1918,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, } else follow = FOLLOW_RETRY; - result = Curl_done(&data->easy_conn, CURLE_OK, FALSE); + result = multi_done(&data->easy_conn, CURLE_OK, FALSE); if(!result) { result = Curl_follow(data, newurl, follow); if(!result) { @@ -1651,14 +1968,14 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, Curl_multi_process_pending_handles(multi); /* post-transfer command */ - res = Curl_done(&data->easy_conn, result, FALSE); + res = multi_done(&data->easy_conn, result, FALSE); /* allow a previously set error code take precedence */ if(!result) result = res; /* - * If there are other handles on the pipeline, Curl_done won't set + * If there are other handles on the pipeline, multi_done won't set * easy_conn to NULL. In such a case, curl_multi_remove_handle() can * access free'd data, if the connection is free'd and the handle * removed before we perform the processing in CURLM_STATE_COMPLETED @@ -1677,7 +1994,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, } /* after we have DONE what we're supposed to do, go COMPLETED, and - it doesn't matter what the Curl_done() returned! */ + it doesn't matter what the multi_done() returned! */ multistate(data, CURLM_STATE_COMPLETED); break; @@ -1779,10 +2096,9 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi, } -CURLMcode curl_multi_perform(CURLM *multi_handle, int *running_handles) +CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - struct SessionHandle *data; + struct Curl_easy *data; CURLMcode returncode=CURLM_OK; struct Curl_tree *t; struct timeval now = Curl_tvnow(); @@ -1793,27 +2109,12 @@ CURLMcode curl_multi_perform(CURLM *multi_handle, int *running_handles) data=multi->easyp; while(data) { CURLMcode result; - struct WildcardData *wc = &data->wildcard; SIGPIPE_VARIABLE(pipe_st); - if(data->set.wildcardmatch) { - if(!wc->filelist) { - CURLcode ret = Curl_wildcard_init(wc); /* init wildcard structures */ - if(ret) - return CURLM_OUT_OF_MEMORY; - } - } - sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); - if(data->set.wildcardmatch) { - /* destruct wildcard structures if it is needed */ - if(wc->state == CURLWC_DONE || result) - Curl_wildcard_dtor(wc); - } - if(result) returncode = result; @@ -1856,6 +2157,8 @@ static void close_all_connections(struct Curl_multi *multi) conn->data = multi->closure_handle; sigpipe_ignore(conn->data, &pipe_st); + conn->data->easy_conn = NULL; /* clear the easy handle's connection + pointer */ /* This will remove the connection from the cache */ (void)Curl_disconnect(conn, FALSE); sigpipe_restore(&pipe_st); @@ -1864,11 +2167,10 @@ static void close_all_connections(struct Curl_multi *multi) } } -CURLMcode curl_multi_cleanup(CURLM *multi_handle) +CURLMcode curl_multi_cleanup(struct Curl_multi *multi) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - struct SessionHandle *data; - struct SessionHandle *nextdata; + struct Curl_easy *data; + struct Curl_easy *nextdata; if(GOOD_MULTI_HANDLE(multi)) { bool restore_pipe = FALSE; @@ -1939,9 +2241,8 @@ CURLMcode curl_multi_cleanup(CURLM *multi_handle) * beyond. The current design is fully O(1). */ -CURLMsg *curl_multi_info_read(CURLM *multi_handle, int *msgs_in_queue) +CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; struct Curl_message *msg; *msgs_in_queue = 0; /* default to none */ @@ -1972,7 +2273,7 @@ CURLMsg *curl_multi_info_read(CURLM *multi_handle, int *msgs_in_queue) * call the callback accordingly. */ static void singlesocket(struct Curl_multi *multi, - struct SessionHandle *data) + struct Curl_easy *data) { curl_socket_t socks[MAX_SOCKSPEREASYHANDLE]; int i; @@ -1980,7 +2281,6 @@ static void singlesocket(struct Curl_multi *multi, curl_socket_t s; int num; unsigned int curraction; - bool remove_sock_from_hash; for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) socks[i] = CURL_SOCKET_BAD; @@ -2002,7 +2302,7 @@ static void singlesocket(struct Curl_multi *multi, s = socks[i]; /* get it from the hash */ - entry = Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s)); + entry = sh_getentry(&multi->sockhash, s); if(curraction & GETSOCK_READSOCK(i)) action |= CURL_POLL_IN; @@ -2048,57 +2348,50 @@ static void singlesocket(struct Curl_multi *multi, break; } } - if(s != CURL_SOCKET_BAD) { + entry = sh_getentry(&multi->sockhash, s); + if(entry) { /* this socket has been removed. Tell the app to remove it */ - remove_sock_from_hash = TRUE; - - entry = Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s)); - if(entry) { - /* check if the socket to be removed serves a connection which has - other easy-s in a pipeline. In this case the socket should not be - removed. */ - struct connectdata *easy_conn = data->easy_conn; - if(easy_conn) { - if(easy_conn->recv_pipe && easy_conn->recv_pipe->size > 1) { - /* the handle should not be removed from the pipe yet */ - remove_sock_from_hash = FALSE; - - /* Update the sockhash entry to instead point to the next in line - for the recv_pipe, or the first (in case this particular easy - isn't already) */ - if(entry->easy == data) { - if(Curl_recvpipe_head(data, easy_conn)) - entry->easy = easy_conn->recv_pipe->head->next->ptr; - else - entry->easy = easy_conn->recv_pipe->head->ptr; - } + bool remove_sock_from_hash = TRUE; + + /* check if the socket to be removed serves a connection which has + other easy-s in a pipeline. In this case the socket should not be + removed. */ + struct connectdata *easy_conn = data->easy_conn; + if(easy_conn) { + if(easy_conn->recv_pipe && easy_conn->recv_pipe->size > 1) { + /* the handle should not be removed from the pipe yet */ + remove_sock_from_hash = FALSE; + + /* Update the sockhash entry to instead point to the next in line + for the recv_pipe, or the first (in case this particular easy + isn't already) */ + if(entry->easy == data) { + if(Curl_recvpipe_head(data, easy_conn)) + entry->easy = easy_conn->recv_pipe->head->next->ptr; + else + entry->easy = easy_conn->recv_pipe->head->ptr; } - if(easy_conn->send_pipe && easy_conn->send_pipe->size > 1) { - /* the handle should not be removed from the pipe yet */ - remove_sock_from_hash = FALSE; - - /* Update the sockhash entry to instead point to the next in line - for the send_pipe, or the first (in case this particular easy - isn't already) */ - if(entry->easy == data) { - if(Curl_sendpipe_head(data, easy_conn)) - entry->easy = easy_conn->send_pipe->head->next->ptr; - else - entry->easy = easy_conn->send_pipe->head->ptr; - } + } + if(easy_conn->send_pipe && easy_conn->send_pipe->size > 1) { + /* the handle should not be removed from the pipe yet */ + remove_sock_from_hash = FALSE; + + /* Update the sockhash entry to instead point to the next in line + for the send_pipe, or the first (in case this particular easy + isn't already) */ + if(entry->easy == data) { + if(Curl_sendpipe_head(data, easy_conn)) + entry->easy = easy_conn->send_pipe->head->next->ptr; + else + entry->easy = easy_conn->send_pipe->head->ptr; } - /* Don't worry about overwriting recv_pipe head with send_pipe_head, - when action will be asked on the socket (see multi_socket()), the - head of the correct pipe will be taken according to the - action. */ } + /* Don't worry about overwriting recv_pipe head with send_pipe_head, + when action will be asked on the socket (see multi_socket()), the + head of the correct pipe will be taken according to the + action. */ } - else - /* just a precaution, this socket really SHOULD be in the hash already - but in case it isn't, we don't have to tell the app to remove it - either since it never got to know about it */ - remove_sock_from_hash = FALSE; if(remove_sock_from_hash) { /* in this case 'entry' is always non-NULL */ @@ -2110,9 +2403,8 @@ static void singlesocket(struct Curl_multi *multi, entry->socketp); sh_delentry(&multi->sockhash, s); } - - } - } + } /* if sockhash entry existed */ + } /* for loop over numsocks */ memcpy(data->sockets, socks, num*sizeof(curl_socket_t)); data->numsocks = num; @@ -2134,8 +2426,7 @@ void Curl_multi_closed(struct connectdata *conn, curl_socket_t s) if(multi) { /* this is set if this connection is part of a handle that is added to a multi handle, and only then this is necessary */ - struct Curl_sh_entry *entry = - Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s)); + struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(entry) { if(multi->socket_cb) @@ -2154,7 +2445,7 @@ void Curl_multi_closed(struct connectdata *conn, curl_socket_t s) /* * add_next_timeout() * - * Each SessionHandle has a list of timeouts. The add_next_timeout() is called + * Each Curl_easy has a list of timeouts. The add_next_timeout() is called * when it has just been removed from the splay tree because the timeout has * expired. This function is then to advance in the list to pick the next * timeout to use (skip the already expired ones) and add this node back to @@ -2165,7 +2456,7 @@ void Curl_multi_closed(struct connectdata *conn, curl_socket_t s) */ static CURLMcode add_next_timeout(struct timeval now, struct Curl_multi *multi, - struct SessionHandle *d) + struct Curl_easy *d) { struct timeval *tv = &d->state.expiretime; struct curl_llist *list = d->state.timeoutlist; @@ -2174,7 +2465,7 @@ static CURLMcode add_next_timeout(struct timeval now, /* move over the timeout list for this specific handle and remove all timeouts that are now passed tense and store the next pending timeout in *tv */ - for(e = list->head; e; ) { + for(e = list->head; e;) { struct curl_llist_element *n = e->next; long diff = curlx_tvdiff(*(struct timeval *)e->ptr, now); if(diff <= 0) @@ -2213,7 +2504,7 @@ static CURLMcode multi_socket(struct Curl_multi *multi, int *running_handles) { CURLMcode result = CURLM_OK; - struct SessionHandle *data = NULL; + struct Curl_easy *data = NULL; struct Curl_tree *t; struct timeval now = Curl_tvnow(); @@ -2236,8 +2527,7 @@ static CURLMcode multi_socket(struct Curl_multi *multi, } else if(s != CURL_SOCKET_TIMEOUT) { - struct Curl_sh_entry *entry = - Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s)); + struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(!entry) /* Unmatched socket, we can't act on it but we ignore this fact. In @@ -2342,10 +2632,9 @@ static CURLMcode multi_socket(struct Curl_multi *multi, } #undef curl_multi_setopt -CURLMcode curl_multi_setopt(CURLM *multi_handle, +CURLMcode curl_multi_setopt(struct Curl_multi *multi, CURLMoption option, ...) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; CURLMcode res = CURLM_OK; va_list param; @@ -2413,33 +2702,32 @@ CURLMcode curl_multi_setopt(CURLM *multi_handle, /* we define curl_multi_socket() in the public multi.h header */ #undef curl_multi_socket -CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, +CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s, int *running_handles) { - CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s, - 0, running_handles); + CURLMcode result = multi_socket(multi, FALSE, s, 0, running_handles); if(CURLM_OK >= result) - update_timer((struct Curl_multi *)multi_handle); + update_timer(multi); return result; } -CURLMcode curl_multi_socket_action(CURLM *multi_handle, curl_socket_t s, +CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s, int ev_bitmask, int *running_handles) { - CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s, + CURLMcode result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles); if(CURLM_OK >= result) - update_timer((struct Curl_multi *)multi_handle); + update_timer(multi); return result; } -CURLMcode curl_multi_socket_all(CURLM *multi_handle, int *running_handles) +CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles) { - CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, - TRUE, CURL_SOCKET_BAD, 0, running_handles); + CURLMcode result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, + running_handles); if(CURLM_OK >= result) - update_timer((struct Curl_multi *)multi_handle); + update_timer(multi); return result; } @@ -2478,11 +2766,9 @@ static CURLMcode multi_timeout(struct Curl_multi *multi, return CURLM_OK; } -CURLMcode curl_multi_timeout(CURLM *multi_handle, +CURLMcode curl_multi_timeout(struct Curl_multi *multi, long *timeout_ms) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; @@ -2509,7 +2795,7 @@ static int update_timer(struct Curl_multi *multi) multi->timer_lastcall = none; /* there's no timeout now but there was one previously, tell the app to disable it */ - return multi->timer_cb((CURLM*)multi, -1, multi->timer_userp); + return multi->timer_cb(multi, -1, multi->timer_userp); } return 0; } @@ -2523,7 +2809,7 @@ static int update_timer(struct Curl_multi *multi) multi->timer_lastcall = multi->timetree->key; - return multi->timer_cb((CURLM*)multi, timeout_ms, multi->timer_userp); + return multi->timer_cb(multi, timeout_ms, multi->timer_userp); } /* @@ -2595,7 +2881,7 @@ multi_addtimeout(struct curl_llist *timeoutlist, * * Pass zero to clear all timeout values for this handle. */ -void Curl_expire(struct SessionHandle *data, long milli) +void Curl_expire(struct Curl_easy *data, long milli) { struct Curl_multi *multi = data->multi; struct timeval *nowp = &data->state.expiretime; @@ -2689,7 +2975,7 @@ void Curl_expire(struct SessionHandle *data, long milli) * time-out period to expire. * */ -void Curl_expire_latest(struct SessionHandle *data, long milli) +void Curl_expire_latest(struct Curl_easy *data, long milli) { struct timeval *expire = &data->state.expiretime; @@ -2718,15 +3004,12 @@ void Curl_expire_latest(struct SessionHandle *data, long milli) Curl_expire(data, milli); } -CURLMcode curl_multi_assign(CURLM *multi_handle, - curl_socket_t s, void *hashp) +CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s, + void *hashp) { struct Curl_sh_entry *there = NULL; - struct Curl_multi *multi = (struct Curl_multi *)multi_handle; - if(s != CURL_SOCKET_BAD) - there = Curl_hash_pick(&multi->sockhash, (char *)&s, - sizeof(curl_socket_t)); + there = sh_getentry(&multi->sockhash, s); if(!there) return CURLM_BAD_SOCKET; @@ -2771,7 +3054,7 @@ void Curl_multi_process_pending_handles(struct Curl_multi *multi) struct curl_llist_element *e = multi->pending->head; while(e) { - struct SessionHandle *data = e->ptr; + struct Curl_easy *data = e->ptr; struct curl_llist_element *next = e->next; if(data->mstate == CURLM_STATE_CONNECT_PEND) { @@ -2789,10 +3072,9 @@ void Curl_multi_process_pending_handles(struct Curl_multi *multi) } #ifdef DEBUGBUILD -void Curl_multi_dump(const struct Curl_multi *multi_handle) +void Curl_multi_dump(struct Curl_multi *multi) { - struct Curl_multi *multi=(struct Curl_multi *)multi_handle; - struct SessionHandle *data; + struct Curl_easy *data; int i; fprintf(stderr, "* Multi status: %d handles, %d alive\n", multi->num_easy, multi->num_alive); @@ -2804,8 +3086,7 @@ void Curl_multi_dump(const struct Curl_multi *multi_handle) statename[data->mstate], data->numsocks); for(i=0; i < data->numsocks; i++) { curl_socket_t s = data->sockets[i]; - struct Curl_sh_entry *entry = - Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s)); + struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); fprintf(stderr, "%d ", (int)s); if(!entry) { diff --git a/Utilities/cmcurl/lib/multihandle.h b/Utilities/cmcurl/lib/multihandle.h index 6c24f50..c56b6ae 100644 --- a/Utilities/cmcurl/lib/multihandle.h +++ b/Utilities/cmcurl/lib/multihandle.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -71,8 +71,8 @@ struct Curl_multi { long type; /* We have a doubly-linked circular list with easy handles */ - struct SessionHandle *easyp; - struct SessionHandle *easylp; /* last node */ + struct Curl_easy *easyp; + struct Curl_easy *easylp; /* last node */ int num_easy; /* amount of entries in the linked list above. */ int num_alive; /* amount of easy handles that are added but have not yet @@ -80,7 +80,7 @@ struct Curl_multi { struct curl_llist *msglist; /* a list of messages from completed transfers */ - struct curl_llist *pending; /* SessionHandles that are in the + struct curl_llist *pending; /* Curl_easys that are in the CURLM_STATE_CONNECT_PEND state */ /* callback function and user data pointer for the *socket() API */ @@ -113,7 +113,7 @@ struct Curl_multi { /* This handle will be used for closing the cached connections in curl_multi_cleanup() */ - struct SessionHandle *closure_handle; + struct Curl_easy *closure_handle; long maxconnects; /* if >0, a fixed limit of the maximum number of entries we're allowed to grow the connection cache to */ diff --git a/Utilities/cmcurl/lib/multiif.h b/Utilities/cmcurl/lib/multiif.h index e6323ad..fd2df55 100644 --- a/Utilities/cmcurl/lib/multiif.h +++ b/Utilities/cmcurl/lib/multiif.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -25,10 +25,10 @@ /* * Prototypes for library-wide functions provided by multi.c */ -void Curl_expire(struct SessionHandle *data, long milli); -void Curl_expire_latest(struct SessionHandle *data, long milli); +void Curl_expire(struct Curl_easy *data, long milli); +void Curl_expire_latest(struct Curl_easy *data, long milli); bool Curl_pipeline_wanted(const struct Curl_multi* multi, int bits); -void Curl_multi_handlePipeBreak(struct SessionHandle *data); +void Curl_multi_handlePipeBreak(struct Curl_easy *data); /* Internal version of curl_multi_init() accepts size parameters for the socket and connection hashes */ @@ -51,7 +51,7 @@ struct Curl_multi *Curl_multi_handle(int hashsize, int chashsize); * allow easier tracking of the internal handle's state and what sockets * they use. Only for research and development DEBUGBUILD enabled builds. */ -void Curl_multi_dump(const struct Curl_multi *multi_handle); +void Curl_multi_dump(struct Curl_multi *multi); #endif void Curl_multi_process_pending_handles(struct Curl_multi *multi); @@ -92,6 +92,6 @@ void Curl_multi_closed(struct connectdata *conn, curl_socket_t s); * Add a handle and move it into PERFORM state at once. For pushed streams. */ CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, - struct SessionHandle *data, + struct Curl_easy *data, struct connectdata *conn); #endif /* HEADER_CURL_MULTIIF_H */ diff --git a/Utilities/cmcurl/lib/netrc.c b/Utilities/cmcurl/lib/netrc.c index 06f8ea1..46f427a 100644 --- a/Utilities/cmcurl/lib/netrc.c +++ b/Utilities/cmcurl/lib/netrc.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -32,9 +32,9 @@ #include "strequal.h" #include "strtok.h" #include "rawstr.h" -#include "curl_printf.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" diff --git a/Utilities/cmcurl/lib/netrc.h b/Utilities/cmcurl/lib/netrc.h index a145601..d980166 100644 --- a/Utilities/cmcurl/lib/netrc.h +++ b/Utilities/cmcurl/lib/netrc.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/non-ascii.c b/Utilities/cmcurl/lib/non-ascii.c index 6ccb449..ed14618 100644 --- a/Utilities/cmcurl/lib/non-ascii.c +++ b/Utilities/cmcurl/lib/non-ascii.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -51,7 +51,7 @@ * Curl_convert_clone() returns a malloced copy of the source string (if * returning CURLE_OK), with the data converted to network format. */ -CURLcode Curl_convert_clone(struct SessionHandle *data, +CURLcode Curl_convert_clone(struct Curl_easy *data, const char *indata, size_t insize, char **outbuf) @@ -79,7 +79,7 @@ CURLcode Curl_convert_clone(struct SessionHandle *data, * Curl_convert_to_network() is an internal function for performing ASCII * conversions on non-ASCII platforms. It convers the buffer _in place_. */ -CURLcode Curl_convert_to_network(struct SessionHandle *data, +CURLcode Curl_convert_to_network(struct Curl_easy *data, char *buffer, size_t length) { if(data->set.convtonetwork) { @@ -139,7 +139,7 @@ CURLcode Curl_convert_to_network(struct SessionHandle *data, * Curl_convert_from_network() is an internal function for performing ASCII * conversions on non-ASCII platforms. It convers the buffer _in place_. */ -CURLcode Curl_convert_from_network(struct SessionHandle *data, +CURLcode Curl_convert_from_network(struct Curl_easy *data, char *buffer, size_t length) { if(data->set.convfromnetwork) { @@ -199,7 +199,7 @@ CURLcode Curl_convert_from_network(struct SessionHandle *data, * Curl_convert_from_utf8() is an internal function for performing UTF-8 * conversions on non-ASCII platforms. */ -CURLcode Curl_convert_from_utf8(struct SessionHandle *data, +CURLcode Curl_convert_from_utf8(struct Curl_easy *data, char *buffer, size_t length) { if(data->set.convfromutf8) { @@ -261,9 +261,9 @@ CURLcode Curl_convert_from_utf8(struct SessionHandle *data, } /* - * Init conversion stuff for a SessionHandle + * Init conversion stuff for a Curl_easy */ -void Curl_convert_init(struct SessionHandle *data) +void Curl_convert_init(struct Curl_easy *data) { #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV) /* conversion descriptors for iconv calls */ @@ -276,9 +276,9 @@ void Curl_convert_init(struct SessionHandle *data) } /* - * Setup conversion stuff for a SessionHandle + * Setup conversion stuff for a Curl_easy */ -void Curl_convert_setup(struct SessionHandle *data) +void Curl_convert_setup(struct Curl_easy *data) { data->inbound_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST, CURL_ICONV_CODESET_OF_NETWORK); @@ -289,10 +289,10 @@ void Curl_convert_setup(struct SessionHandle *data) } /* - * Close conversion stuff for a SessionHandle + * Close conversion stuff for a Curl_easy */ -void Curl_convert_close(struct SessionHandle *data) +void Curl_convert_close(struct Curl_easy *data) { #ifdef HAVE_ICONV /* close iconv conversion descriptors */ @@ -314,7 +314,7 @@ void Curl_convert_close(struct SessionHandle *data) * Curl_convert_form() is used from http.c, this converts any form items that need to be sent in the network encoding. Returns CURLE_OK on success. */ -CURLcode Curl_convert_form(struct SessionHandle *data, struct FormData *form) +CURLcode Curl_convert_form(struct Curl_easy *data, struct FormData *form) { CURLcode result; diff --git a/Utilities/cmcurl/lib/non-ascii.h b/Utilities/cmcurl/lib/non-ascii.h index 8b4b7c2..e27f1f4 100644 --- a/Utilities/cmcurl/lib/non-ascii.h +++ b/Utilities/cmcurl/lib/non-ascii.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -33,22 +33,22 @@ * * If no conversion was needed *outbuf may be NULL. */ -CURLcode Curl_convert_clone(struct SessionHandle *data, +CURLcode Curl_convert_clone(struct Curl_easy *data, const char *indata, size_t insize, char **outbuf); -void Curl_convert_init(struct SessionHandle *data); -void Curl_convert_setup(struct SessionHandle *data); -void Curl_convert_close(struct SessionHandle *data); +void Curl_convert_init(struct Curl_easy *data); +void Curl_convert_setup(struct Curl_easy *data); +void Curl_convert_close(struct Curl_easy *data); -CURLcode Curl_convert_to_network(struct SessionHandle *data, +CURLcode Curl_convert_to_network(struct Curl_easy *data, char *buffer, size_t length); -CURLcode Curl_convert_from_network(struct SessionHandle *data, +CURLcode Curl_convert_from_network(struct Curl_easy *data, char *buffer, size_t length); -CURLcode Curl_convert_from_utf8(struct SessionHandle *data, +CURLcode Curl_convert_from_utf8(struct Curl_easy *data, char *buffer, size_t length); -CURLcode Curl_convert_form(struct SessionHandle *data, struct FormData *form); +CURLcode Curl_convert_form(struct Curl_easy *data, struct FormData *form); #else #define Curl_convert_clone(a,b,c,d) ((void)a, CURLE_OK) #define Curl_convert_init(x) Curl_nop_stmt diff --git a/Utilities/cmcurl/lib/nonblock.c b/Utilities/cmcurl/lib/nonblock.c index 1447c87..b764278 100644 --- a/Utilities/cmcurl/lib/nonblock.c +++ b/Utilities/cmcurl/lib/nonblock.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -77,7 +77,7 @@ int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ /* Amiga */ long flags = nonblock ? 1L : 0L; - return IoctlSocket(sockfd, FIONBIO, flags); + return IoctlSocket(sockfd, FIONBIO, (char *)&flags); #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) diff --git a/Utilities/cmcurl/lib/nonblock.h b/Utilities/cmcurl/lib/nonblock.h index b540ae4..98cdc25 100644 --- a/Utilities/cmcurl/lib/nonblock.h +++ b/Utilities/cmcurl/lib/nonblock.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/nwlib.c b/Utilities/cmcurl/lib/nwlib.c index bd3f27e..42b6aa0 100644 --- a/Utilities/cmcurl/lib/nwlib.c +++ b/Utilities/cmcurl/lib/nwlib.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -58,26 +58,26 @@ rtag_t gAllocTag = (rtag_t) NULL; NXMutex_t *gLibLock = (NXMutex_t *) NULL; /* internal library function prototypes... */ -int DisposeLibraryData( void * ); -void DisposeThreadData( void * ); -int GetOrSetUpData( int id, libdata_t **data, libthreaddata_t **threaddata ); - - -int _NonAppStart( void *NLMHandle, - void *errorScreen, - const char *cmdLine, - const char *loadDirPath, - size_t uninitializedDataLength, - void *NLMFileHandle, - int (*readRoutineP)( int conn, - void *fileHandle, size_t offset, - size_t nbytes, - size_t *bytesRead, - void *buffer ), +int DisposeLibraryData(void *); +void DisposeThreadData(void *); +int GetOrSetUpData(int id, libdata_t **data, libthreaddata_t **threaddata); + + +int _NonAppStart(void *NLMHandle, + void *errorScreen, + const char *cmdLine, + const char *loadDirPath, + size_t uninitializedDataLength, + void *NLMFileHandle, + int (*readRoutineP)(int conn, + void *fileHandle, size_t offset, + size_t nbytes, + size_t *bytesRead, + void *buffer), size_t customDataOffset, size_t customDataSize, int messageCount, - const char **messages ) + const char **messages) { NX_LOCK_INFO_ALLOC(liblock, "Per-Application Data Lock", 0); @@ -132,7 +132,7 @@ int _NonAppStart( void *NLMHandle, * Here we clean up any resources we allocated. Resource tags is a big part * of what we created, but NetWare doesn't ask us to free those. */ -void _NonAppStop( void ) +void _NonAppStop(void) { (void) unregister_library(gLibId); NXMutexFree(gLibLock); @@ -149,13 +149,13 @@ void _NonAppStop( void ) * we return a non-zero value. Right now, there isn't any reason not to allow * it. */ -int _NonAppCheckUnload( void ) +int _NonAppCheckUnload(void) { return 0; } int GetOrSetUpData(int id, libdata_t **appData, - libthreaddata_t **threadData ) + libthreaddata_t **threadData) { int err; libdata_t *app_data; @@ -277,7 +277,7 @@ int GetOrSetUpData(int id, libdata_t **appData, return err; } -int DisposeLibraryData( void *data ) +int DisposeLibraryData(void *data) { if(data) { void *tenbytes = ((libdata_t *) data)->tenbytes; @@ -289,7 +289,7 @@ int DisposeLibraryData( void *data ) return 0; } -void DisposeThreadData( void *data ) +void DisposeThreadData(void *data) { if(data) { void *twentybytes = ((libthreaddata_t *) data)->twentybytes; @@ -303,7 +303,7 @@ void DisposeThreadData( void *data ) /* For native CLib-based NLM seems we can do a bit more simple. */ #include <nwthread.h> -int main ( void ) +int main (void) { /* initialize any globals here... */ diff --git a/Utilities/cmcurl/lib/nwos.c b/Utilities/cmcurl/lib/nwos.c index 23ff2a7..385f9c8 100644 --- a/Utilities/cmcurl/lib/nwos.c +++ b/Utilities/cmcurl/lib/nwos.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,7 +26,7 @@ #ifdef __NOVELL_LIBC__ /* For native LibC-based NLM we need to do nothing. */ -int netware_init ( void ) +int netware_init (void) { return 0; } @@ -45,7 +45,7 @@ NETDB_DEFINE_CONTEXT #include <arpa/inet.h> NETINET_DEFINE_CONTEXT -int netware_init ( void ) +int netware_init (void) { int rc = 0; unsigned int myHandle = GetNLMHandle(); @@ -72,13 +72,13 @@ int netware_init ( void ) } /* dummy function to satisfy newer prelude */ -int __init_environment ( void ) +int __init_environment (void) { return 0; } /* dummy function to satisfy newer prelude */ -int __deinit_environment ( void ) +int __deinit_environment (void) { return 0; } diff --git a/Utilities/cmcurl/lib/openldap.c b/Utilities/cmcurl/lib/openldap.c index bee552f..4b8cfb9 100644 --- a/Utilities/cmcurl/lib/openldap.c +++ b/Utilities/cmcurl/lib/openldap.c @@ -6,11 +6,11 @@ * \___|\___/|_| \_\_____| * * Copyright (C) 2010, Howard Chu, <hyc@openldap.org> - * Copyright (C) 2011 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2011 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -46,9 +46,8 @@ #include "curl_ldap.h" #include "curl_base64.h" #include "connect.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -151,7 +150,7 @@ static CURLcode ldap_setup_connection(struct connectdata *conn) { ldapconninfo *li; LDAPURLDesc *lud; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; int rc, proto; CURLcode status; @@ -189,7 +188,7 @@ static Sockbuf_IO ldapsb_tls; static CURLcode ldap_connect(struct connectdata *conn, bool *done) { ldapconninfo *li = conn->proto.generic; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int rc, proto = LDAP_VERSION3; char hosturl[1024]; char *ptr; @@ -227,7 +226,7 @@ static CURLcode ldap_connect(struct connectdata *conn, bool *done) static CURLcode ldap_connecting(struct connectdata *conn, bool *done) { ldapconninfo *li = conn->proto.generic; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; LDAPMessage *msg = NULL; struct timeval tv = {0, 1}, *tvp; int rc, err; @@ -353,7 +352,7 @@ static CURLcode ldap_do(struct connectdata *conn, bool *done) int rc = 0; LDAPURLDesc *ludp = NULL; int msgid; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; connkeep(conn, "OpenLDAP do"); @@ -416,7 +415,7 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, size_t len, CURLcode *err) { ldapconninfo *li = conn->proto.generic; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; ldapreqinfo *lr = data->req.protop; int rc, ret; LDAPMessage *msg = NULL; @@ -446,6 +445,7 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, ent = ldap_next_message(li->ld, ent)) { struct berval bv, *bvals, **bvp = &bvals; int binary = 0, msgtype; + CURLcode writeerr; msgtype = ldap_msgtype(ent); if(msgtype == LDAP_RES_SEARCH_RESULT) { @@ -485,18 +485,24 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, *err = CURLE_RECV_ERROR; return -1; } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4); + if(writeerr) { + *err = writeerr; return -1; + } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, - bv.bv_len); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, + bv.bv_len); + if(writeerr) { + *err = writeerr; return -1; + } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); + if(writeerr) { + *err = writeerr; return -1; + } data->req.bytecount += bv.bv_len + 5; for(rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, bvp); @@ -513,18 +519,24 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, for(i=0; bvals[i].bv_val != NULL; i++) { int binval = 0; - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1); - if(*err) - return -1; - - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, - bv.bv_len); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1); + if(writeerr) { + *err = writeerr; return -1; + } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)":", 1); - if(*err) - return -1; + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, + bv.bv_len); + if(writeerr) { + *err = writeerr; + return -1; + } + + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)":", 1); + if(writeerr) { + *err = writeerr; + return -1; + } data->req.bytecount += bv.bv_len + 2; if(!binary) { @@ -558,47 +570,62 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, *err = error; return -1; } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)": ", 2); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, + (char *)": ", 2); + if(writeerr) { + *err = writeerr; return -1; + } data->req.bytecount += 2; if(val_b64_sz > 0) { - *err = Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, val_b64_sz); - if(*err) + if(writeerr) { + *err = writeerr; return -1; + } free(val_b64); data->req.bytecount += val_b64_sz; } } else { - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)" ", 1); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)" ", 1); + if(writeerr) { + *err = writeerr; return -1; + } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, bvals[i].bv_val, - bvals[i].bv_len); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, bvals[i].bv_val, + bvals[i].bv_len); + if(writeerr) { + *err = writeerr; return -1; + } data->req.bytecount += bvals[i].bv_len + 1; } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); + if(writeerr) { + *err = writeerr; return -1; + } data->req.bytecount++; } ber_memfree(bvals); - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); + if(writeerr) { + *err = writeerr; return -1; + } data->req.bytecount++; } - *err = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); - if(*err) + writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); + if(writeerr) { + *err = writeerr; return -1; + } data->req.bytecount++; ber_free(ber, 0); } diff --git a/Utilities/cmcurl/lib/parsedate.c b/Utilities/cmcurl/lib/parsedate.c index 3e168f5..dfcf855 100644 --- a/Utilities/cmcurl/lib/parsedate.c +++ b/Utilities/cmcurl/lib/parsedate.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/parsedate.h b/Utilities/cmcurl/lib/parsedate.h index ade0f4f..2e59eb1 100644 --- a/Utilities/cmcurl/lib/parsedate.h +++ b/Utilities/cmcurl/lib/parsedate.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/pingpong.c b/Utilities/cmcurl/lib/pingpong.c index 1670792..92ff84b 100644 --- a/Utilities/cmcurl/lib/pingpong.c +++ b/Utilities/cmcurl/lib/pingpong.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -34,10 +34,10 @@ #include "multiif.h" #include "non-ascii.h" #include "vtls/vtls.h" -#include "curl_printf.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" #ifdef USE_PINGPONG @@ -47,7 +47,7 @@ long Curl_pp_state_timeout(struct pingpong *pp) { struct connectdata *conn = pp->conn; - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; long timeout_ms; /* in milliseconds */ long timeout2_ms; /* in milliseconds */ long response_time= (data->set.server_response_timeout)? @@ -85,10 +85,10 @@ CURLcode Curl_pp_statemach(struct pingpong *pp, bool block) int rc; long interval_ms; long timeout_ms = Curl_pp_state_timeout(pp); - struct SessionHandle *data=conn->data; + struct Curl_easy *data=conn->data; CURLcode result = CURLE_OK; - if(timeout_ms <=0 ) { + if(timeout_ms <=0) { failf(data, "server response timeout"); return CURLE_OPERATION_TIMEDOUT; /* already too little time */ } @@ -165,7 +165,7 @@ CURLcode Curl_pp_vsendf(struct pingpong *pp, char *s; CURLcode result; struct connectdata *conn = pp->conn; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; #ifdef HAVE_GSSAPI enum protection_level data_sec = conn->data_prot; @@ -271,7 +271,7 @@ CURLcode Curl_pp_readresp(curl_socket_t sockfd, ssize_t gotbytes; char *ptr; struct connectdata *conn = pp->conn; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char * const buf = data->state.buffer; CURLcode result = CURLE_OK; diff --git a/Utilities/cmcurl/lib/pingpong.h b/Utilities/cmcurl/lib/pingpong.h index b925ab9..2f649d5 100644 --- a/Utilities/cmcurl/lib/pingpong.h +++ b/Utilities/cmcurl/lib/pingpong.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/pipeline.c b/Utilities/cmcurl/lib/pipeline.c index 1b38836..0ff82f0 100644 --- a/Utilities/cmcurl/lib/pipeline.c +++ b/Utilities/cmcurl/lib/pipeline.c @@ -10,7 +10,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -57,7 +57,7 @@ static void server_blacklist_llist_dtor(void *user, void *element) free(element); } -bool Curl_pipeline_penalized(struct SessionHandle *data, +bool Curl_pipeline_penalized(struct Curl_easy *data, struct connectdata *conn) { if(data) { @@ -70,7 +70,7 @@ bool Curl_pipeline_penalized(struct SessionHandle *data, /* Find the head of the recv pipe, if any */ if(conn->recv_pipe && conn->recv_pipe->head) { - struct SessionHandle *recv_handle = conn->recv_pipe->head->ptr; + struct Curl_easy *recv_handle = conn->recv_pipe->head->ptr; recv_size = recv_handle->req.size; @@ -91,7 +91,7 @@ bool Curl_pipeline_penalized(struct SessionHandle *data, return FALSE; } -static CURLcode addHandleToPipeline(struct SessionHandle *data, +static CURLcode addHandleToPipeline(struct Curl_easy *data, struct curl_llist *pipeline) { if(!Curl_llist_insert_next(pipeline, pipeline->tail, data)) @@ -100,7 +100,7 @@ static CURLcode addHandleToPipeline(struct SessionHandle *data, } -CURLcode Curl_add_handle_to_pipeline(struct SessionHandle *handle, +CURLcode Curl_add_handle_to_pipeline(struct Curl_easy *handle, struct connectdata *conn) { struct curl_llist_element *sendhead = conn->send_pipe->head; @@ -130,7 +130,7 @@ CURLcode Curl_add_handle_to_pipeline(struct SessionHandle *handle, checked to update what sockets it acts on. */ -void Curl_move_handle_from_send_to_recv_pipe(struct SessionHandle *handle, +void Curl_move_handle_from_send_to_recv_pipe(struct Curl_easy *handle, struct connectdata *conn) { struct curl_llist_element *curr; @@ -162,7 +162,7 @@ void Curl_move_handle_from_send_to_recv_pipe(struct SessionHandle *handle, } } -bool Curl_pipeline_site_blacklisted(struct SessionHandle *handle, +bool Curl_pipeline_site_blacklisted(struct Curl_easy *handle, struct connectdata *conn) { if(handle->multi) { @@ -254,7 +254,7 @@ CURLMcode Curl_pipeline_set_site_blacklist(char **sites, return CURLM_OK; } -bool Curl_pipeline_server_blacklisted(struct SessionHandle *handle, +bool Curl_pipeline_server_blacklisted(struct Curl_easy *handle, char *server_name) { if(handle->multi && server_name) { @@ -299,11 +299,16 @@ CURLMcode Curl_pipeline_set_server_blacklist(char **servers, char *server_name; server_name = strdup(*servers); - if(!server_name) + if(!server_name) { + Curl_llist_destroy(new_list, NULL); return CURLM_OUT_OF_MEMORY; + } - if(!Curl_llist_insert_next(new_list, new_list->tail, server_name)) + if(!Curl_llist_insert_next(new_list, new_list->tail, server_name)) { + Curl_llist_destroy(new_list, NULL); + Curl_safefree(server_name); return CURLM_OUT_OF_MEMORY; + } servers++; } @@ -320,25 +325,26 @@ CURLMcode Curl_pipeline_set_server_blacklist(char **servers, return CURLM_OK; } -static bool pipe_head(struct SessionHandle *data, +static bool pipe_head(struct Curl_easy *data, struct curl_llist *pipeline) { - struct curl_llist_element *curr = pipeline->head; - if(curr) - return (curr->ptr == data) ? TRUE : FALSE; - + if(pipeline) { + struct curl_llist_element *curr = pipeline->head; + if(curr) + return (curr->ptr == data) ? TRUE : FALSE; + } return FALSE; } /* returns TRUE if the given handle is head of the recv pipe */ -bool Curl_recvpipe_head(struct SessionHandle *data, +bool Curl_recvpipe_head(struct Curl_easy *data, struct connectdata *conn) { return pipe_head(data, conn->recv_pipe); } /* returns TRUE if the given handle is head of the send pipe */ -bool Curl_sendpipe_head(struct SessionHandle *data, +bool Curl_sendpipe_head(struct Curl_easy *data, struct connectdata *conn) { return pipe_head(data, conn->send_pipe); @@ -352,7 +358,7 @@ bool Curl_sendpipe_head(struct SessionHandle *data, * If not available, return FALSE. */ -bool Curl_pipeline_checkget_write(struct SessionHandle *data, +bool Curl_pipeline_checkget_write(struct Curl_easy *data, struct connectdata *conn) { if(conn->bits.multiplex) @@ -375,7 +381,7 @@ bool Curl_pipeline_checkget_write(struct SessionHandle *data, * If not available, return FALSE. */ -bool Curl_pipeline_checkget_read(struct SessionHandle *data, +bool Curl_pipeline_checkget_read(struct Curl_easy *data, struct connectdata *conn) { if(conn->bits.multiplex) @@ -412,7 +418,7 @@ void print_pipeline(struct connectdata *conn) { struct curl_llist_element *curr; struct connectbundle *cb_ptr; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; cb_ptr = conn->bundle; diff --git a/Utilities/cmcurl/lib/pipeline.h b/Utilities/cmcurl/lib/pipeline.h index bf229f1..a64f710 100644 --- a/Utilities/cmcurl/lib/pipeline.h +++ b/Utilities/cmcurl/lib/pipeline.h @@ -12,7 +12,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -23,34 +23,34 @@ * ***************************************************************************/ -CURLcode Curl_add_handle_to_pipeline(struct SessionHandle *handle, +CURLcode Curl_add_handle_to_pipeline(struct Curl_easy *handle, struct connectdata *conn); -void Curl_move_handle_from_send_to_recv_pipe(struct SessionHandle *handle, +void Curl_move_handle_from_send_to_recv_pipe(struct Curl_easy *handle, struct connectdata *conn); -bool Curl_pipeline_penalized(struct SessionHandle *data, +bool Curl_pipeline_penalized(struct Curl_easy *data, struct connectdata *conn); -bool Curl_pipeline_site_blacklisted(struct SessionHandle *handle, +bool Curl_pipeline_site_blacklisted(struct Curl_easy *handle, struct connectdata *conn); CURLMcode Curl_pipeline_set_site_blacklist(char **sites, struct curl_llist **list_ptr); -bool Curl_pipeline_server_blacklisted(struct SessionHandle *handle, +bool Curl_pipeline_server_blacklisted(struct Curl_easy *handle, char *server_name); CURLMcode Curl_pipeline_set_server_blacklist(char **servers, struct curl_llist **list_ptr); -bool Curl_pipeline_checkget_write(struct SessionHandle *data, +bool Curl_pipeline_checkget_write(struct Curl_easy *data, struct connectdata *conn); -bool Curl_pipeline_checkget_read(struct SessionHandle *data, +bool Curl_pipeline_checkget_read(struct Curl_easy *data, struct connectdata *conn); void Curl_pipeline_leave_write(struct connectdata *conn); void Curl_pipeline_leave_read(struct connectdata *conn); -bool Curl_recvpipe_head(struct SessionHandle *data, +bool Curl_recvpipe_head(struct Curl_easy *data, struct connectdata *conn); -bool Curl_sendpipe_head(struct SessionHandle *data, +bool Curl_sendpipe_head(struct Curl_easy *data, struct connectdata *conn); #endif /* HEADER_CURL_PIPELINE_H */ diff --git a/Utilities/cmcurl/lib/pop3.c b/Utilities/cmcurl/lib/pop3.c index 53510a2..591e877 100644 --- a/Utilities/cmcurl/lib/pop3.c +++ b/Utilities/cmcurl/lib/pop3.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -83,9 +83,9 @@ #include "curl_sasl.h" #include "curl_md5.h" #include "warnless.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* Local API functions */ @@ -214,7 +214,7 @@ static const struct Curl_handler Curl_handler_pop3s_proxy = { /* SASL parameters for the pop3 protocol */ static const struct SASLproto saslpop3 = { "pop", /* The service name */ - '+', /* Code received when continuation is expected */ + '*', /* Code received when continuation is expected */ '+', /* Code to receive upon authentication success */ 255 - 8, /* Maximum initial response length (no max) */ pop3_perform_auth, /* Send authentication command */ @@ -225,7 +225,11 @@ static const struct SASLproto saslpop3 = { #ifdef USE_SSL static void pop3_to_pop3s(struct connectdata *conn) { + /* Change the connection handler */ conn->handler = &Curl_handler_pop3s; + + /* Set the connection's upgraded to TLS flag */ + conn->tls_upgraded = TRUE; } #else #define pop3_to_pop3s(x) Curl_nop_stmt @@ -256,21 +260,29 @@ static bool pop3_endofresp(struct connectdata *conn, char *line, size_t len, if(pop3c->state == POP3_CAPA) { /* Do we have the terminating line? */ if(len >= 1 && !memcmp(line, ".", 1)) + /* Treat the response as a success */ *resp = '+'; else + /* Treat the response as an untagged continuation */ *resp = '*'; return TRUE; } - /* Do we have a command or continuation response? */ - if((len >= 3 && !memcmp("+OK", line, 3)) || - (len >= 1 && !memcmp("+", line, 1))) { + /* Do we have a success response? */ + if(len >= 3 && !memcmp("+OK", line, 3)) { *resp = '+'; return TRUE; } + /* Do we have a continuation response? */ + if(len >= 1 && !memcmp("+", line, 1)) { + *resp = '*'; + + return TRUE; + } + return FALSE; /* Nothing for us */ } @@ -585,7 +597,7 @@ static CURLcode pop3_perform_authentication(struct connectdata *conn) static CURLcode pop3_perform_command(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; const char *command = NULL; @@ -641,7 +653,7 @@ static CURLcode pop3_state_servergreet_resp(struct connectdata *conn, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct pop3_conn *pop3c = &conn->proto.pop3c; const char *line = data->state.buffer; size_t len = strlen(line); @@ -692,7 +704,7 @@ static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct pop3_conn *pop3c = &conn->proto.pop3c; const char *line = data->state.buffer; size_t len = strlen(line); @@ -700,7 +712,7 @@ static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code, (void)instate; /* no use for this yet */ - /* Do we have a untagged response? */ + /* Do we have a untagged continuation response? */ if(pop3code == '*') { /* Does the server support the STLS capability? */ if(len >= 4 && !memcmp(line, "STLS", 4)) @@ -741,8 +753,8 @@ static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code, wordlen++; /* Test the word for a matching authentication mechanism */ - if((mechbit = Curl_sasl_decode_mech(line, wordlen, &llen)) && - llen == wordlen) + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) pop3c->sasl.authmechs |= mechbit; line += wordlen; @@ -783,7 +795,7 @@ static CURLcode pop3_state_starttls_resp(struct connectdata *conn, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -807,7 +819,7 @@ static CURLcode pop3_state_auth_resp(struct connectdata *conn, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct pop3_conn *pop3c = &conn->proto.pop3c; saslprogress progress; @@ -847,7 +859,7 @@ static CURLcode pop3_state_apop_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -868,7 +880,7 @@ static CURLcode pop3_state_user_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -891,7 +903,7 @@ static CURLcode pop3_state_pass_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -912,7 +924,7 @@ static CURLcode pop3_state_command_resp(struct connectdata *conn, pop3state instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; struct pop3_conn *pop3c = &conn->proto.pop3c; struct pingpong *pp = &pop3c->pp; @@ -1066,12 +1078,12 @@ static CURLcode pop3_block_statemach(struct connectdata *conn) return result; } -/* Allocate and initialize the POP3 struct for the current SessionHandle if +/* Allocate and initialize the POP3 struct for the current Curl_easy if required */ static CURLcode pop3_init(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct POP3 *pop3; pop3 = data->req.protop = calloc(sizeof(struct POP3), 1); @@ -1148,16 +1160,12 @@ static CURLcode pop3_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; (void)premature; if(!pop3) - /* When the easy handle is removed from the multi interface while libcurl - is still trying to resolve the host name, the POP3 struct is not yet - initialized. However, the removal action calls Curl_done() which in - turn calls this function, so we simply return success. */ return CURLE_OK; if(status) { @@ -1316,7 +1324,7 @@ static CURLcode pop3_regular_transfer(struct connectdata *conn, { CURLcode result = CURLE_OK; bool connected = FALSE; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Make sure size is unknown at this point */ data->req.size = -1; @@ -1339,13 +1347,17 @@ static CURLcode pop3_regular_transfer(struct connectdata *conn, static CURLcode pop3_setup_connection(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Initialise the POP3 layer */ CURLcode result = pop3_init(conn); if(result) return result; + /* Clear the TLS upgraded flag */ + conn->tls_upgraded = FALSE; + + /* Set up the proxy if necessary */ if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) { /* Unless we have asked to tunnel POP3 operations through the proxy, we switch and use HTTP operations only */ @@ -1442,7 +1454,7 @@ static CURLcode pop3_parse_url_options(struct connectdata *conn) static CURLcode pop3_parse_url_path(struct connectdata *conn) { /* The POP3 struct is already initialised in pop3_connect() */ - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; const char *path = data->state.path; @@ -1459,7 +1471,7 @@ static CURLcode pop3_parse_url_path(struct connectdata *conn) static CURLcode pop3_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; @@ -1481,7 +1493,7 @@ CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread) { /* This code could be made into a special function in the handler struct */ CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; struct pop3_conn *pop3c = &conn->proto.pop3c; diff --git a/Utilities/cmcurl/lib/pop3.h b/Utilities/cmcurl/lib/pop3.h index 7bc53aa..a8e697c 100644 --- a/Utilities/cmcurl/lib/pop3.h +++ b/Utilities/cmcurl/lib/pop3.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -45,9 +45,9 @@ typedef enum { POP3_LAST /* never used */ } pop3state; -/* This POP3 struct is used in the SessionHandle. All POP3 data that is +/* This POP3 struct is used in the Curl_easy. All POP3 data that is connection-oriented must be in pop3_conn to properly deal with the fact that - perhaps the SessionHandle is changed between the times the connection is + perhaps the Curl_easy is changed between the times the connection is used. */ struct POP3 { curl_pp_transfer transfer; diff --git a/Utilities/cmcurl/lib/progress.c b/Utilities/cmcurl/lib/progress.c index b46e274..760ca1c 100644 --- a/Utilities/cmcurl/lib/progress.c +++ b/Utilities/cmcurl/lib/progress.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -133,7 +133,7 @@ static char *max5data(curl_off_t bytes, char *max5) int Curl_pgrsDone(struct connectdata *conn) { int rc; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; data->progress.lastshow=0; rc = Curl_pgrsUpdate(conn); /* the final (forced) update */ if(rc) @@ -150,7 +150,7 @@ int Curl_pgrsDone(struct connectdata *conn) } /* reset all times except redirect, and reset the known transfer sizes */ -void Curl_pgrsResetTimesSizes(struct SessionHandle *data) +void Curl_pgrsResetTimesSizes(struct Curl_easy *data) { data->progress.t_nslookup = 0.0; data->progress.t_connect = 0.0; @@ -161,7 +161,7 @@ void Curl_pgrsResetTimesSizes(struct SessionHandle *data) Curl_pgrsSetUploadSize(data, -1); } -void Curl_pgrsTime(struct SessionHandle *data, timerid timer) +void Curl_pgrsTime(struct Curl_easy *data, timerid timer) { struct timeval now = Curl_tvnow(); @@ -212,7 +212,7 @@ void Curl_pgrsTime(struct SessionHandle *data, timerid timer) } } -void Curl_pgrsStartNow(struct SessionHandle *data) +void Curl_pgrsStartNow(struct Curl_easy *data) { data->progress.speeder_c = 0; /* reset the progress meter display */ data->progress.start = Curl_tvnow(); @@ -220,17 +220,17 @@ void Curl_pgrsStartNow(struct SessionHandle *data) data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT; } -void Curl_pgrsSetDownloadCounter(struct SessionHandle *data, curl_off_t size) +void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size) { data->progress.downloaded = size; } -void Curl_pgrsSetUploadCounter(struct SessionHandle *data, curl_off_t size) +void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size) { data->progress.uploaded = size; } -void Curl_pgrsSetDownloadSize(struct SessionHandle *data, curl_off_t size) +void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size) { if(size >= 0) { data->progress.size_dl = size; @@ -242,7 +242,7 @@ void Curl_pgrsSetDownloadSize(struct SessionHandle *data, curl_off_t size) } } -void Curl_pgrsSetUploadSize(struct SessionHandle *data, curl_off_t size) +void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size) { if(size >= 0) { data->progress.size_ul = size; @@ -269,7 +269,7 @@ int Curl_pgrsUpdate(struct connectdata *conn) curl_off_t total_transfer; curl_off_t total_expected_transfer; curl_off_t timespent; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int nowindex = data->progress.speeder_c% CURR_TIME; int checkindex; int countindex; /* amount of seconds stored in the speeder array */ diff --git a/Utilities/cmcurl/lib/progress.h b/Utilities/cmcurl/lib/progress.h index a1e6f1a..a77b7ce 100644 --- a/Utilities/cmcurl/lib/progress.h +++ b/Utilities/cmcurl/lib/progress.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -41,14 +41,14 @@ typedef enum { } timerid; int Curl_pgrsDone(struct connectdata *); -void Curl_pgrsStartNow(struct SessionHandle *data); -void Curl_pgrsSetDownloadSize(struct SessionHandle *data, curl_off_t size); -void Curl_pgrsSetUploadSize(struct SessionHandle *data, curl_off_t size); -void Curl_pgrsSetDownloadCounter(struct SessionHandle *data, curl_off_t size); -void Curl_pgrsSetUploadCounter(struct SessionHandle *data, curl_off_t size); +void Curl_pgrsStartNow(struct Curl_easy *data); +void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size); +void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size); +void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size); +void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size); int Curl_pgrsUpdate(struct connectdata *); -void Curl_pgrsResetTimesSizes(struct SessionHandle *data); -void Curl_pgrsTime(struct SessionHandle *data, timerid timer); +void Curl_pgrsResetTimesSizes(struct Curl_easy *data); +void Curl_pgrsTime(struct Curl_easy *data, timerid timer); /* Don't show progress for sizes smaller than: */ diff --git a/Utilities/cmcurl/lib/rawstr.c b/Utilities/cmcurl/lib/rawstr.c index e27dac4..5665ebd 100644 --- a/Utilities/cmcurl/lib/rawstr.c +++ b/Utilities/cmcurl/lib/rawstr.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,6 +28,10 @@ its behavior is altered by the current locale. */ char Curl_raw_toupper(char in) { +#if !defined(CURL_DOES_CONVERSIONS) + if(in >= 'a' && in <= 'z') + return (char)('A' + in - 'a'); +#else switch (in) { case 'a': return 'A'; @@ -82,13 +86,15 @@ char Curl_raw_toupper(char in) case 'z': return 'Z'; } +#endif + return in; } /* * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant * to be locale independent and only compare strings we know are safe for - * this. See http://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for + * this. See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for * some further explanation to why this function is necessary. * * The function is capable of comparing a-z case insensitively even for diff --git a/Utilities/cmcurl/lib/rawstr.h b/Utilities/cmcurl/lib/rawstr.h index b491460..4af00f1 100644 --- a/Utilities/cmcurl/lib/rawstr.h +++ b/Utilities/cmcurl/lib/rawstr.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/rtsp.c b/Utilities/cmcurl/lib/rtsp.c index c30afd3..27955bc 100644 --- a/Utilities/cmcurl/lib/rtsp.c +++ b/Utilities/cmcurl/lib/rtsp.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -36,9 +36,8 @@ #include "rawstr.h" #include "select.h" #include "connect.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" - -/* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -74,7 +73,7 @@ static int rtsp_getsock_do(struct connectdata *conn, * data is parsed and k->str is moved up * readmore: whether or not the RTP parser needs more data right away */ -static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data, +static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *readmore); @@ -159,7 +158,7 @@ bool Curl_rtsp_connisdead(struct connectdata *check) } else if((sval & CURL_CSELECT_IN) && check->data) { /* readable with no error. could be closed or could be alive but we can - only check if we have a proper SessionHandle for the connection */ + only check if we have a proper Curl_easy for the connection */ curl_socket_t connectinfo = Curl_getconnectinfo(check->data, &check); if(connectinfo != CURL_SOCKET_BAD) ret_val = FALSE; @@ -171,7 +170,7 @@ bool Curl_rtsp_connisdead(struct connectdata *check) static CURLcode rtsp_connect(struct connectdata *conn, bool *done) { CURLcode httpStatus; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; httpStatus = Curl_http_connect(conn, done); @@ -197,7 +196,7 @@ static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead) static CURLcode rtsp_done(struct connectdata *conn, CURLcode status, bool premature) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct RTSP *rtsp = data->req.protop; CURLcode httpStatus; long CSeq_sent; @@ -231,7 +230,7 @@ static CURLcode rtsp_done(struct connectdata *conn, static CURLcode rtsp_do(struct connectdata *conn, bool *done) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result=CURLE_OK; Curl_RtspReq rtspreq = data->set.rtspreq; struct RTSP *rtsp = data->req.protop; @@ -249,6 +248,8 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done) const char *p_stream_uri = NULL; const char *p_transport = NULL; const char *p_uagent = NULL; + const char *p_proxyuserpwd = NULL; + const char *p_userpwd = NULL; *done = TRUE; @@ -326,7 +327,6 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done) return CURLE_BAD_FUNCTION_ARGUMENT; } - /* TODO: auth? */ /* TODO: proxy? */ /* Stream URI. Default to server '*' if not specified */ @@ -392,6 +392,14 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done) p_uagent = conn->allocptr.uagent; } + /* setup the authentication headers */ + result = Curl_http_output_auth(conn, p_request, p_stream_uri, FALSE); + if(result) + return result; + + p_proxyuserpwd = conn->allocptr.proxyuserpwd; + p_userpwd = conn->allocptr.userpwd; + /* Referrer */ Curl_safefree(conn->allocptr.ref); if(data->change.referer && !Curl_checkheaders(conn, "Referer:")) @@ -464,13 +472,25 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done) "%s" /* range */ "%s" /* referrer */ "%s" /* user-agent */ + "%s" /* proxyuserpwd */ + "%s" /* userpwd */ , p_transport ? p_transport : "", p_accept ? p_accept : "", p_accept_encoding ? p_accept_encoding : "", p_range ? p_range : "", p_referrer ? p_referrer : "", - p_uagent ? p_uagent : ""); + p_uagent ? p_uagent : "", + p_proxyuserpwd ? p_proxyuserpwd : "", + p_userpwd ? p_userpwd : ""); + + /* + * Free userpwd now --- cannot reuse this for Negotiate and possibly NTLM + * with basic and digest, it will be freed anyway by the next request + */ + Curl_safefree (conn->allocptr.userpwd); + conn->allocptr.userpwd = NULL; + if(result) return result; @@ -580,7 +600,7 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done) } -static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data, +static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *readmore) { @@ -711,7 +731,7 @@ static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data, static CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; size_t wrote; curl_write_callback writeit; @@ -739,7 +759,7 @@ CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len) CURLcode Curl_rtsp_parseheader(struct connectdata *conn, char *header) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; long CSeq = 0; if(checkprefix("CSeq:", header)) { diff --git a/Utilities/cmcurl/lib/rtsp.h b/Utilities/cmcurl/lib/rtsp.h index 3ffa70c..5a8d555 100644 --- a/Utilities/cmcurl/lib/rtsp.h +++ b/Utilities/cmcurl/lib/rtsp.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/security.c b/Utilities/cmcurl/lib/security.c index 014bbf1..a0bcaea 100644 --- a/Utilities/cmcurl/lib/security.c +++ b/Utilities/cmcurl/lib/security.c @@ -476,7 +476,7 @@ Curl_sec_request_prot(struct connectdata *conn, const char *level) static CURLcode choose_mech(struct connectdata *conn) { int ret; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; void *tmp_allocation; const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech; diff --git a/Utilities/cmcurl/lib/select.c b/Utilities/cmcurl/lib/select.c index 6eff070..2002349 100644 --- a/Utilities/cmcurl/lib/select.c +++ b/Utilities/cmcurl/lib/select.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -316,15 +316,15 @@ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */ curl_socket_t is unsigned in such cases and thus -1 is the largest value). */ +#ifdef USE_WINSOCK r = select((int)maxfd + 1, -#ifndef USE_WINSOCK - &fds_read, - &fds_write, -#else fds_read.fd_count ? &fds_read : NULL, fds_write.fd_count ? &fds_write : NULL, -#endif &fds_err, ptimeout); +#else + r = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, ptimeout); +#endif + if(r != -1) break; error = SOCKERRNO; @@ -505,19 +505,19 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms) pending_tv.tv_sec = 0; pending_tv.tv_usec = 0; } + +#ifdef USE_WINSOCK r = select((int)maxfd + 1, -#ifndef USE_WINSOCK - &fds_read, &fds_write, &fds_err, -#else /* WinSock select() can't handle fd_sets with zero bits set, so don't give it such arguments. See the comment about this in Curl_check_socket(). */ fds_read.fd_count ? &fds_read : NULL, fds_write.fd_count ? &fds_write : NULL, - fds_err.fd_count ? &fds_err : NULL, + fds_err.fd_count ? &fds_err : NULL, ptimeout); +#else + r = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, ptimeout); #endif - ptimeout); if(r != -1) break; error = SOCKERRNO; diff --git a/Utilities/cmcurl/lib/select.h b/Utilities/cmcurl/lib/select.h index c00afe1..695bb69 100644 --- a/Utilities/cmcurl/lib/select.h +++ b/Utilities/cmcurl/lib/select.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/sendf.c b/Utilities/cmcurl/lib/sendf.c index 5f39d1f..2101797 100644 --- a/Utilities/cmcurl/lib/sendf.c +++ b/Utilities/cmcurl/lib/sendf.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -31,10 +31,11 @@ #include "ssh.h" #include "multiif.h" #include "non-ascii.h" -#include "curl_printf.h" #include "strerror.h" +#include "select.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -45,7 +46,7 @@ * blocks of data. Remaining, bare CRs are changed to LFs. The possibly new * size of the data is returned. */ -static size_t convert_lineends(struct SessionHandle *data, +static size_t convert_lineends(struct Curl_easy *data, char *startPtr, size_t size) { char *inPtr, *outPtr; @@ -120,9 +121,93 @@ static size_t convert_lineends(struct SessionHandle *data, } #endif /* CURL_DO_LINEEND_CONV */ +#ifdef USE_RECV_BEFORE_SEND_WORKAROUND +static void pre_receive_plain(struct connectdata *conn, int num) +{ + const curl_socket_t sockfd = conn->sock[num]; + struct postponed_data * const psnd = &(conn->postponed[num]); + size_t bytestorecv = psnd->allocated_size - psnd->recv_size; + /* WinSock will destroy unread received data if send() is + failed. + To avoid lossage of received data, recv() must be + performed before every send() if any incoming data is + available. However, skip this, if buffer is already full. */ + if((conn->handler->protocol&PROTO_FAMILY_HTTP) != 0 && + conn->recv[num] == Curl_recv_plain && + (!psnd->buffer || bytestorecv)) { + const int readymask = Curl_socket_check(sockfd, CURL_SOCKET_BAD, + CURL_SOCKET_BAD, 0); + if(readymask != -1 && (readymask & CURL_CSELECT_IN) != 0) { + /* Have some incoming data */ + if(!psnd->buffer) { + /* Use buffer double default size for intermediate buffer */ + psnd->allocated_size = 2 * BUFSIZE; + psnd->buffer = malloc(psnd->allocated_size); + psnd->recv_size = 0; + psnd->recv_processed = 0; +#ifdef DEBUGBUILD + psnd->bindsock = sockfd; /* Used only for DEBUGASSERT */ +#endif /* DEBUGBUILD */ + bytestorecv = psnd->allocated_size; + } + if(psnd->buffer) { + ssize_t recvedbytes; + DEBUGASSERT(psnd->bindsock == sockfd); + recvedbytes = sread(sockfd, psnd->buffer + psnd->recv_size, + bytestorecv); + if(recvedbytes > 0) + psnd->recv_size += recvedbytes; + } + else + psnd->allocated_size = 0; + } + } +} + +static ssize_t get_pre_recved(struct connectdata *conn, int num, char *buf, + size_t len) +{ + struct postponed_data * const psnd = &(conn->postponed[num]); + size_t copysize; + if(!psnd->buffer) + return 0; + + DEBUGASSERT(psnd->allocated_size > 0); + DEBUGASSERT(psnd->recv_size <= psnd->allocated_size); + DEBUGASSERT(psnd->recv_processed <= psnd->recv_size); + /* Check and process data that already received and storied in internal + intermediate buffer */ + if(psnd->recv_size > psnd->recv_processed) { + DEBUGASSERT(psnd->bindsock == conn->sock[num]); + copysize = CURLMIN(len, psnd->recv_size - psnd->recv_processed); + memcpy(buf, psnd->buffer + psnd->recv_processed, copysize); + psnd->recv_processed += copysize; + } + else + copysize = 0; /* buffer was allocated, but nothing was received */ + + /* Free intermediate buffer if it has no unprocessed data */ + if(psnd->recv_processed == psnd->recv_size) { + free(psnd->buffer); + psnd->buffer = NULL; + psnd->allocated_size = 0; + psnd->recv_size = 0; + psnd->recv_processed = 0; +#ifdef DEBUGBUILD + psnd->bindsock = CURL_SOCKET_BAD; +#endif /* DEBUGBUILD */ + } + return (ssize_t)copysize; +} +#else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ +/* Use "do-nothing" macros instead of functions when workaround not used */ +#define pre_receive_plain(c,n) do {} WHILE_FALSE +#define get_pre_recved(c,n,b,l) 0 +#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ + /* Curl_infof() is for info message along the way */ -void Curl_infof(struct SessionHandle *data, const char *fmt, ...) +void Curl_infof(struct Curl_easy *data, const char *fmt, ...) { if(data && data->set.verbose) { va_list ap; @@ -140,7 +225,7 @@ void Curl_infof(struct SessionHandle *data, const char *fmt, ...) * The message SHALL NOT include any LF or CR. */ -void Curl_failf(struct SessionHandle *data, const char *fmt, ...) +void Curl_failf(struct Curl_easy *data, const char *fmt, ...) { va_list ap; size_t len; @@ -168,7 +253,7 @@ void Curl_failf(struct SessionHandle *data, const char *fmt, ...) CURLcode Curl_sendf(curl_socket_t sockfd, struct connectdata *conn, const char *fmt, ...) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; ssize_t bytes_written; size_t write_len; CURLcode result = CURLE_OK; @@ -254,7 +339,23 @@ ssize_t Curl_send_plain(struct connectdata *conn, int num, const void *mem, size_t len, CURLcode *code) { curl_socket_t sockfd = conn->sock[num]; - ssize_t bytes_written = swrite(sockfd, mem, len); + ssize_t bytes_written; + /* WinSock will destroy unread received data if send() is + failed. + To avoid lossage of received data, recv() must be + performed before every send() if any incoming data is + available. */ + pre_receive_plain(conn, num); + +#ifdef MSG_FASTOPEN /* Linux */ + if(conn->bits.tcp_fastopen) { + bytes_written = sendto(sockfd, mem, len, MSG_FASTOPEN, + conn->ip_addr->ai_addr, conn->ip_addr->ai_addrlen); + conn->bits.tcp_fastopen = FALSE; + } + else +#endif + bytes_written = swrite(sockfd, mem, len); *code = CURLE_OK; if(-1 == bytes_written) { @@ -268,7 +369,8 @@ ssize_t Curl_send_plain(struct connectdata *conn, int num, /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned due to its inability to send off data without blocking. We therefor treat both error codes the same here */ - (EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err) + (EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err) || + (EINPROGRESS == err) #endif ) { /* this is just a case of EWOULDBLOCK */ @@ -311,7 +413,16 @@ ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf, size_t len, CURLcode *code) { curl_socket_t sockfd = conn->sock[num]; - ssize_t nread = sread(sockfd, buf, len); + ssize_t nread; + /* Check and return data that already received and storied in internal + intermediate buffer */ + nread = get_pre_recved(conn, num, buf, len); + if(nread > 0) { + *code = CURLE_OK; + return nread; + } + + nread = sread(sockfd, buf, len); *code = CURLE_OK; if(-1 == nread) { @@ -341,7 +452,7 @@ ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf, return nread; } -static CURLcode pausewrite(struct SessionHandle *data, +static CURLcode pausewrite(struct Curl_easy *data, int type, /* what type of data */ const char *ptr, size_t len) @@ -380,7 +491,7 @@ CURLcode Curl_client_chop_write(struct connectdata *conn, char * ptr, size_t len) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_write_callback writeheader = NULL; curl_write_callback writebody = NULL; @@ -487,7 +598,7 @@ CURLcode Curl_client_write(struct connectdata *conn, char *ptr, size_t len) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(0 == len) len = strlen(ptr); @@ -520,11 +631,13 @@ CURLcode Curl_read_plain(curl_socket_t sockfd, if(-1 == nread) { int err = SOCKERRNO; + int return_error; #ifdef USE_WINSOCK - if(WSAEWOULDBLOCK == err) + return_error = WSAEWOULDBLOCK == err; #else - if((EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err)) + return_error = EWOULDBLOCK == err || EAGAIN == err || EINTR == err; #endif + if(return_error) return CURLE_AGAIN; else return CURLE_RECV_ERROR; @@ -551,7 +664,10 @@ CURLcode Curl_read(struct connectdata *conn, /* connection data */ ssize_t nread = 0; size_t bytesfromsocket = 0; char *buffertofill = NULL; - bool pipelining = Curl_pipeline_wanted(conn->data->multi, CURLPIPE_HTTP1); + + /* if HTTP/1 pipelining is both wanted and possible */ + bool pipelining = Curl_pipeline_wanted(conn->data->multi, CURLPIPE_HTTP1) && + (conn->bundle->multiuse == BUNDLE_PIPELINING); /* Set 'num' to 0 or 1, depending on which socket that has been sent here. If it is the second socket, we set num to 1. Otherwise to 0. This lets @@ -602,7 +718,7 @@ CURLcode Curl_read(struct connectdata *conn, /* connection data */ } /* return 0 on success */ -static int showit(struct SessionHandle *data, curl_infotype type, +static int showit(struct Curl_easy *data, curl_infotype type, char *ptr, size_t size) { static const char s_infotype[CURLINFO_END][3] = { @@ -671,7 +787,7 @@ static int showit(struct SessionHandle *data, curl_infotype type, return 0; } -int Curl_debug(struct SessionHandle *data, curl_infotype type, +int Curl_debug(struct Curl_easy *data, curl_infotype type, char *ptr, size_t size, struct connectdata *conn) { diff --git a/Utilities/cmcurl/lib/sendf.h b/Utilities/cmcurl/lib/sendf.h index 86f06cf..a951a0b 100644 --- a/Utilities/cmcurl/lib/sendf.h +++ b/Utilities/cmcurl/lib/sendf.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,8 +26,8 @@ CURLcode Curl_sendf(curl_socket_t sockfd, struct connectdata *, const char *fmt, ...); -void Curl_infof(struct SessionHandle *, const char *fmt, ...); -void Curl_failf(struct SessionHandle *, const char *fmt, ...); +void Curl_infof(struct Curl_easy *, const char *fmt, ...); +void Curl_failf(struct Curl_easy *, const char *fmt, ...); #if defined(CURL_DISABLE_VERBOSE_STRINGS) @@ -84,7 +84,7 @@ CURLcode Curl_write_plain(struct connectdata *conn, ssize_t *written); /* the function used to output verbose information */ -int Curl_debug(struct SessionHandle *handle, curl_infotype type, +int Curl_debug(struct Curl_easy *handle, curl_infotype type, char *data, size_t size, struct connectdata *conn); diff --git a/Utilities/cmcurl/lib/setup-os400.h b/Utilities/cmcurl/lib/setup-os400.h index fae8567..e32b72f 100644 --- a/Utilities/cmcurl/lib/setup-os400.h +++ b/Utilities/cmcurl/lib/setup-os400.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/setup-vms.h b/Utilities/cmcurl/lib/setup-vms.h index 520a35d..4b78e0b 100644 --- a/Utilities/cmcurl/lib/setup-vms.h +++ b/Utilities/cmcurl/lib/setup-vms.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/share.c b/Utilities/cmcurl/lib/share.c index 1720248..5b3957f 100644 --- a/Utilities/cmcurl/lib/share.c +++ b/Utilities/cmcurl/lib/share.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -31,7 +31,7 @@ /* The last #include file should be: */ #include "memdebug.h" -CURLSH * +struct Curl_share * curl_share_init(void) { struct Curl_share *share = calloc(1, sizeof(struct Curl_share)); @@ -49,9 +49,8 @@ curl_share_init(void) #undef curl_share_setopt CURLSHcode -curl_share_setopt(CURLSH *sh, CURLSHoption option, ...) +curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...) { - struct Curl_share *share = (struct Curl_share *)sh; va_list param; int type; curl_lock_function lockfunc; @@ -71,14 +70,14 @@ curl_share_setopt(CURLSH *sh, CURLSHoption option, ...) /* this is a type this share will share */ type = va_arg(param, int); share->specifier |= (1<<type); - switch( type ) { + switch(type) { case CURL_LOCK_DATA_DNS: break; case CURL_LOCK_DATA_COOKIE: #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(!share->cookies) { - share->cookies = Curl_cookie_init(NULL, NULL, NULL, TRUE ); + share->cookies = Curl_cookie_init(NULL, NULL, NULL, TRUE); if(!share->cookies) res = CURLSHE_NOMEM; } @@ -114,7 +113,7 @@ curl_share_setopt(CURLSH *sh, CURLSHoption option, ...) /* this is a type this share will no longer share */ type = va_arg(param, int); share->specifier &= ~(1<<type); - switch( type ) { + switch(type) { case CURL_LOCK_DATA_DNS: break; @@ -172,10 +171,8 @@ curl_share_setopt(CURLSH *sh, CURLSHoption option, ...) } CURLSHcode -curl_share_cleanup(CURLSH *sh) +curl_share_cleanup(struct Curl_share *share) { - struct Curl_share *share = (struct Curl_share *)sh; - if(share == NULL) return CURLSHE_INVALID; @@ -213,7 +210,7 @@ curl_share_cleanup(CURLSH *sh) CURLSHcode -Curl_share_lock(struct SessionHandle *data, curl_lock_data type, +Curl_share_lock(struct Curl_easy *data, curl_lock_data type, curl_lock_access accesstype) { struct Curl_share *share = data->share; @@ -231,7 +228,7 @@ Curl_share_lock(struct SessionHandle *data, curl_lock_data type, } CURLSHcode -Curl_share_unlock(struct SessionHandle *data, curl_lock_data type) +Curl_share_unlock(struct Curl_easy *data, curl_lock_data type) { struct Curl_share *share = data->share; diff --git a/Utilities/cmcurl/lib/share.h b/Utilities/cmcurl/lib/share.h index 8e6629b..e689ff2 100644 --- a/Utilities/cmcurl/lib/share.h +++ b/Utilities/cmcurl/lib/share.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -54,8 +54,8 @@ struct Curl_share { long sessionage; }; -CURLSHcode Curl_share_lock (struct SessionHandle *, curl_lock_data, +CURLSHcode Curl_share_lock (struct Curl_easy *, curl_lock_data, curl_lock_access); -CURLSHcode Curl_share_unlock (struct SessionHandle *, curl_lock_data); +CURLSHcode Curl_share_unlock (struct Curl_easy *, curl_lock_data); #endif /* HEADER_CURL_SHARE_H */ diff --git a/Utilities/cmcurl/lib/sigpipe.h b/Utilities/cmcurl/lib/sigpipe.h index e8d2acd..800f9d3 100644 --- a/Utilities/cmcurl/lib/sigpipe.h +++ b/Utilities/cmcurl/lib/sigpipe.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -38,10 +38,10 @@ struct sigpipe_ignore { * internals, and then sigpipe_restore() will restore the situation when we * return from libcurl again. */ -static void sigpipe_ignore(struct SessionHandle *data, +static void sigpipe_ignore(struct Curl_easy *data, struct sigpipe_ignore *ig) { - /* get a local copy of no_signal because the SessionHandle might not be + /* get a local copy of no_signal because the Curl_easy might not be around when we restore */ ig->no_signal = data->set.no_signal; if(!data->set.no_signal) { diff --git a/Utilities/cmcurl/lib/slist.c b/Utilities/cmcurl/lib/slist.c index 9c0b2a5..e5adc0e 100644 --- a/Utilities/cmcurl/lib/slist.c +++ b/Utilities/cmcurl/lib/slist.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,6 +22,8 @@ #include "curl_setup.h" +#include <curl/curl.h> + #include "slist.h" /* The last #include files should be: */ diff --git a/Utilities/cmcurl/lib/slist.h b/Utilities/cmcurl/lib/slist.h index ea7dcc4..b3f498c 100644 --- a/Utilities/cmcurl/lib/slist.h +++ b/Utilities/cmcurl/lib/slist.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/smb.c b/Utilities/cmcurl/lib/smb.c index d461a71..56a38c2 100644 --- a/Utilities/cmcurl/lib/smb.c +++ b/Utilities/cmcurl/lib/smb.c @@ -10,7 +10,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -131,7 +131,7 @@ const struct Curl_handler Curl_handler_smbs = { defined(__OS400__) static unsigned short smb_swap16(unsigned short x) { - return (x << 8) | ((x >> 8) & 0xff); + return (unsigned short) ((x << 8) | ((x >> 8) & 0xff)); } static unsigned int smb_swap32(unsigned int x) @@ -143,12 +143,14 @@ static unsigned int smb_swap32(unsigned int x) #ifdef HAVE_LONGLONG static unsigned long long smb_swap64(unsigned long long x) { - return ((unsigned long long)smb_swap32(x) << 32) | smb_swap32(x >> 32); + return ((unsigned long long) smb_swap32((unsigned int) x) << 32) | + smb_swap32((unsigned int) (x >> 32)); } #else static unsigned __int64 smb_swap64(unsigned __int64 x) { - return ((unsigned __int64)smb_swap32(x) << 32) | smb_swap32(x >> 32); + return ((unsigned __int64) smb_swap32((unsigned int) x) << 32) | + smb_swap32((unsigned int) (x >> 32)); } #endif #else @@ -903,7 +905,6 @@ static CURLcode smb_disconnect(struct connectdata *conn, bool dead) /* smb_done is not always called, so cleanup the request */ if(req) { Curl_safefree(req->share); - Curl_safefree(conn->data->req.protop); } return CURLE_OK; @@ -928,7 +929,7 @@ static int smb_getsock(struct connectdata *conn, curl_socket_t *socks, static CURLcode smb_parse_url_path(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct smb_request *req = data->req.protop; char *path; char *slash; diff --git a/Utilities/cmcurl/lib/smb.h b/Utilities/cmcurl/lib/smb.h index 7852fa1..1a4f66e 100644 --- a/Utilities/cmcurl/lib/smb.h +++ b/Utilities/cmcurl/lib/smb.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/smtp.c b/Utilities/cmcurl/lib/smtp.c index dada087..d203b53 100644 --- a/Utilities/cmcurl/lib/smtp.c +++ b/Utilities/cmcurl/lib/smtp.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -82,9 +82,9 @@ #include "curl_gethostname.h" #include "curl_sasl.h" #include "warnless.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* Local API functions */ @@ -224,7 +224,11 @@ static const struct SASLproto saslsmtp = { #ifdef USE_SSL static void smtp_to_smtps(struct connectdata *conn) { + /* Change the connection handler */ conn->handler = &Curl_handler_smtps; + + /* Set the connection's upgraded to TLS flag */ + conn->tls_upgraded = TRUE; } #else #define smtp_to_smtps(x) Curl_nop_stmt @@ -288,7 +292,7 @@ static void smtp_get_message(char *buffer, char** outptr) /* Find the end of the message */ for(len = strlen(message); len--;) if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && - message[len] != '\t') + message[len] != '\t') break; /* Terminate the message */ @@ -486,7 +490,7 @@ static CURLcode smtp_perform_authentication(struct connectdata *conn) /* Check we have enough data to authenticate with, and the server supports authentiation, and end the connect phase if not */ if(!smtpc->auth_supported || - !Curl_sasl_can_authenticate(&smtpc->sasl, conn)) { + !Curl_sasl_can_authenticate(&smtpc->sasl, conn)) { state(conn, SMTP_STOP); return result; } @@ -516,15 +520,15 @@ static CURLcode smtp_perform_authentication(struct connectdata *conn) static CURLcode smtp_perform_command(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; /* Send the command */ if(smtp->rcpt) result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s %s", - smtp->custom && smtp->custom[0] != '\0' ? - smtp->custom : "VRFY", - smtp->rcpt->data); + smtp->custom && smtp->custom[0] != '\0' ? + smtp->custom : "VRFY", + smtp->rcpt->data); else result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", smtp->custom && smtp->custom[0] != '\0' ? @@ -548,7 +552,7 @@ static CURLcode smtp_perform_mail(struct connectdata *conn) char *auth = NULL; char *size = NULL; CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Calculate the FROM parameter */ if(!data->set.str[STRING_MAIL_FROM]) @@ -623,16 +627,16 @@ static CURLcode smtp_perform_mail(struct connectdata *conn) static CURLcode smtp_perform_rcpt_to(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; /* Send the RCPT TO command */ if(smtp->rcpt->data[0] == '<') result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:%s", - smtp->rcpt->data); + smtp->rcpt->data); else result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s>", - smtp->rcpt->data); + smtp->rcpt->data); if(!result) state(conn, SMTP_RCPT); @@ -664,7 +668,7 @@ static CURLcode smtp_state_servergreet_resp(struct connectdata *conn, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -684,7 +688,7 @@ static CURLcode smtp_state_starttls_resp(struct connectdata *conn, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -707,7 +711,7 @@ static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct smtp_conn *smtpc = &conn->proto.smtpc; const char *line = data->state.buffer; size_t len = strlen(line); @@ -766,8 +770,8 @@ static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode, wordlen++; /* Test the word for a matching authentication mechanism */ - if((mechbit = Curl_sasl_decode_mech(line, wordlen, &llen)) && - llen == wordlen) + mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); + if(mechbit && llen == wordlen) smtpc->sasl.authmechs |= mechbit; line += wordlen; @@ -802,7 +806,7 @@ static CURLcode smtp_state_helo_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -823,7 +827,7 @@ static CURLcode smtp_state_auth_resp(struct connectdata *conn, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct smtp_conn *smtpc = &conn->proto.smtpc; saslprogress progress; @@ -851,7 +855,7 @@ static CURLcode smtp_state_command_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *line = data->state.buffer; size_t len = strlen(line); @@ -897,7 +901,7 @@ static CURLcode smtp_state_mail_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -917,7 +921,7 @@ static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; (void)instate; /* no use for this yet */ @@ -949,7 +953,7 @@ static CURLcode smtp_state_data_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ @@ -994,7 +998,7 @@ static CURLcode smtp_statemach_act(struct connectdata *conn) { CURLcode result = CURLE_OK; curl_socket_t sock = conn->sock[FIRSTSOCKET]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int smtpcode; struct smtp_conn *smtpc = &conn->proto.smtpc; struct pingpong *pp = &smtpc->pp; @@ -1104,12 +1108,12 @@ static CURLcode smtp_block_statemach(struct connectdata *conn) return result; } -/* Allocate and initialize the SMTP struct for the current SessionHandle if +/* Allocate and initialize the SMTP struct for the current Curl_easy if required */ static CURLcode smtp_init(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp; smtp = data->req.protop = calloc(sizeof(struct SMTP), 1); @@ -1190,7 +1194,7 @@ static CURLcode smtp_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; struct pingpong *pp = &conn->proto.smtpc.pp; char *eob; @@ -1200,10 +1204,6 @@ static CURLcode smtp_done(struct connectdata *conn, CURLcode status, (void)premature; if(!smtp || !pp->conn) - /* When the easy handle is removed from the multi interface while libcurl - is still trying to resolve the host name, the SMTP struct is not yet - initialized. However, the removal action calls Curl_done() which in - turn calls this function, so we simply return success. */ return CURLE_OK; if(status) { @@ -1258,8 +1258,7 @@ static CURLcode smtp_done(struct connectdata *conn, CURLcode status, TODO: when the multi interface is used, this _really_ should be using the smtp_multi_statemach function but we have no general support for - non-blocking DONE operations, not in the multi state machine and with - Curl_done() invokes on several places in the code! + non-blocking DONE operations! */ result = smtp_block_statemach(conn); } @@ -1285,7 +1284,7 @@ static CURLcode smtp_perform(struct connectdata *conn, bool *connected, { /* This is SMTP and no proxy */ CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; DEBUGF(infof(conn->data, "DO phase starts\n")); @@ -1424,7 +1423,7 @@ static CURLcode smtp_regular_transfer(struct connectdata *conn, { CURLcode result = CURLE_OK; bool connected = FALSE; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* Make sure size is unknown at this point */ data->req.size = -1; @@ -1447,9 +1446,13 @@ static CURLcode smtp_regular_transfer(struct connectdata *conn, static CURLcode smtp_setup_connection(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result; + /* Clear the TLS upgraded flag */ + conn->tls_upgraded = FALSE; + + /* Set up the proxy if necessary */ if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) { /* Unless we have asked to tunnel SMTP operations through the proxy, we switch and use HTTP operations only */ @@ -1502,7 +1505,7 @@ static CURLcode smtp_parse_url_options(struct connectdata *conn) const char *value; while(*ptr && *ptr != '=') - ptr++; + ptr++; value = ptr + 1; @@ -1531,7 +1534,7 @@ static CURLcode smtp_parse_url_options(struct connectdata *conn) static CURLcode smtp_parse_url_path(struct connectdata *conn) { /* The SMTP struct is already initialised in smtp_connect() */ - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct smtp_conn *smtpc = &conn->proto.smtpc; const char *path = data->state.path; char localhost[HOSTNAME_MAX + 1]; @@ -1557,7 +1560,7 @@ static CURLcode smtp_parse_url_path(struct connectdata *conn) static CURLcode smtp_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; @@ -1578,7 +1581,7 @@ CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread) */ ssize_t i; ssize_t si; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *scratch = data->state.scratch; char *newscratch = NULL; diff --git a/Utilities/cmcurl/lib/smtp.h b/Utilities/cmcurl/lib/smtp.h index 9fbe0c5..b67340a 100644 --- a/Utilities/cmcurl/lib/smtp.h +++ b/Utilities/cmcurl/lib/smtp.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -47,9 +47,9 @@ typedef enum { SMTP_LAST /* never used */ } smtpstate; -/* This SMTP struct is used in the SessionHandle. All SMTP data that is +/* This SMTP struct is used in the Curl_easy. All SMTP data that is connection-oriented must be in smtp_conn to properly deal with the fact that - perhaps the SessionHandle is changed between the times the connection is + perhaps the Curl_easy is changed between the times the connection is used. */ struct SMTP { curl_pp_transfer transfer; diff --git a/Utilities/cmcurl/lib/sockaddr.h b/Utilities/cmcurl/lib/sockaddr.h index 6a2151c..95ba4c3 100644 --- a/Utilities/cmcurl/lib/sockaddr.h +++ b/Utilities/cmcurl/lib/sockaddr.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/socks.c b/Utilities/cmcurl/lib/socks.c index 7d3f782..fccb16d 100644 --- a/Utilities/cmcurl/lib/socks.c +++ b/Utilities/cmcurl/lib/socks.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -119,7 +119,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name, int result; CURLcode code; curl_socket_t sock = conn->sock[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(Curl_timeleft(data, NULL, TRUE) < 0) { /* time-out, bail out, go home */ @@ -173,8 +173,8 @@ CURLcode Curl_SOCKS4(const char *proxy_name, unsigned short ip[4]; Curl_printable_address(hp, buf, sizeof(buf)); - if(4 == sscanf( buf, "%hu.%hu.%hu.%hu", - &ip[0], &ip[1], &ip[2], &ip[3])) { + if(4 == sscanf(buf, "%hu.%hu.%hu.%hu", + &ip[0], &ip[1], &ip[2], &ip[3])) { /* Set DSTIP */ socksreq[4] = (unsigned char)ip[0]; socksreq[5] = (unsigned char)ip[1]; @@ -300,8 +300,8 @@ CURLcode Curl_SOCKS4(const char *proxy_name, ", request rejected or failed.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; case 92: failf(data, @@ -310,8 +310,8 @@ CURLcode Curl_SOCKS4(const char *proxy_name, "identd on the client.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; case 93: failf(data, @@ -320,8 +320,8 @@ CURLcode Curl_SOCKS4(const char *proxy_name, "report different user-ids.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; default: failf(data, @@ -329,8 +329,8 @@ CURLcode Curl_SOCKS4(const char *proxy_name, ", Unknown.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; } } @@ -374,7 +374,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name, int result; CURLcode code; curl_socket_t sock = conn->sock[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; long timeout; bool socks5_resolve_local = (conn->proxytype == CURLPROXY_SOCKS5)?TRUE:FALSE; const size_t hostname_len = strlen(hostname); @@ -603,7 +603,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name, if(hp->ai_family == AF_INET) { socksreq[len++] = 1; /* ATYP: IPv4 = 1 */ - saddr_in = (struct sockaddr_in*)hp->ai_addr; + saddr_in = (struct sockaddr_in*)(void*)hp->ai_addr; for(i = 0; i < 4; i++) { socksreq[len++] = ((unsigned char*)&saddr_in->sin_addr.s_addr)[i]; infof(data, "%d\n", socksreq[len-1]); @@ -613,7 +613,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name, else if(hp->ai_family == AF_INET6) { socksreq[len++] = 4; /* ATYP: IPv6 = 4 */ - saddr_in6 = (struct sockaddr_in6*)hp->ai_addr; + saddr_in6 = (struct sockaddr_in6*)(void*)hp->ai_addr; for(i = 0; i < 16; i++) { socksreq[len++] = ((unsigned char*)&saddr_in6->sin6_addr.s6_addr)[i]; } @@ -674,15 +674,15 @@ CURLcode Curl_SOCKS5(const char *proxy_name, "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); } else if(socksreq[3] == 3) { failf(data, "Can't complete SOCKS5 connection to %s:%d. (%d)", hostname, - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); } else if(socksreq[3] == 4) { failf(data, @@ -696,8 +696,8 @@ CURLcode Curl_SOCKS5(const char *proxy_name, (unsigned char)socksreq[14], (unsigned char)socksreq[15], (unsigned char)socksreq[16], (unsigned char)socksreq[17], (unsigned char)socksreq[18], (unsigned char)socksreq[19], - ((socksreq[8] << 8) | socksreq[9]), - socksreq[1]); + (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), + (unsigned char)socksreq[1]); } return CURLE_COULDNT_CONNECT; } diff --git a/Utilities/cmcurl/lib/socks.h b/Utilities/cmcurl/lib/socks.h index 29e3bf0..a44ada6 100644 --- a/Utilities/cmcurl/lib/socks.h +++ b/Utilities/cmcurl/lib/socks.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/socks_gssapi.c b/Utilities/cmcurl/lib/socks_gssapi.c index 8e575c2..369245a 100644 --- a/Utilities/cmcurl/lib/socks_gssapi.c +++ b/Utilities/cmcurl/lib/socks_gssapi.c @@ -6,11 +6,11 @@ * \___|\___/|_| \_\_____| * * Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com> - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -32,9 +32,10 @@ #include "timeval.h" #include "socks.h" #include "warnless.h" + +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" static gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; @@ -42,7 +43,7 @@ static gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; /* * Helper GSS-API error functions. */ -static int check_gss_err(struct SessionHandle *data, +static int check_gss_err(struct Curl_easy *data, OM_uint32 major_status, OM_uint32 minor_status, const char* function) @@ -101,7 +102,7 @@ static int check_gss_err(struct SessionHandle *data, CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sock = conn->sock[sockindex]; CURLcode code; ssize_t actualread; @@ -120,7 +121,8 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, unsigned short us_length; char *user=NULL; unsigned char socksreq[4]; /* room for GSS-API exchange header only */ - char *serviceptr = data->set.str[STRING_SOCKS5_GSSAPI_SERVICE]; + const char *serviceptr = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd"; /* GSS-API request looks like * +----+------+-----+----------------+ diff --git a/Utilities/cmcurl/lib/socks_sspi.c b/Utilities/cmcurl/lib/socks_sspi.c index a7708b2..6053490 100644 --- a/Utilities/cmcurl/lib/socks_sspi.c +++ b/Utilities/cmcurl/lib/socks_sspi.c @@ -5,12 +5,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -34,9 +34,10 @@ #include "curl_sspi.h" #include "curl_multibyte.h" #include "warnless.h" +#include "strdup.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* @@ -61,7 +62,7 @@ static int check_sspi_err(struct connectdata *conn, CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sock = conn->sock[sockindex]; CURLcode code; ssize_t actualread; @@ -70,7 +71,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, /* Needs GSS-API authentication */ SECURITY_STATUS status; unsigned long sspi_ret_flags = 0; - int gss_enc; + unsigned char gss_enc; SecBuffer sspi_send_token, sspi_recv_token, sspi_w_token[3]; SecBufferDesc input_desc, output_desc, wrap_desc; SecPkgContext_Sizes sspi_sizes; @@ -83,7 +84,8 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, unsigned short us_length; unsigned long qop; unsigned char socksreq[4]; /* room for GSS-API exchange header only */ - char *service = data->set.str[STRING_SOCKS5_GSSAPI_SERVICE]; + const char *service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd"; /* GSS-API request looks like * +----+------+-----+----------------+ @@ -95,10 +97,9 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, /* prepare service name */ if(strchr(service, '/')) { - service_name = malloc(strlen(service)); + service_name = strdup(service); if(!service_name) return CURLE_OUT_OF_MEMORY; - memcpy(service_name, service, strlen(service)); } else { service_name = malloc(strlen(service) + strlen(conn->proxy.name) + 2); diff --git a/Utilities/cmcurl/lib/speedcheck.c b/Utilities/cmcurl/lib/speedcheck.c index ac7447c..13c34af 100644 --- a/Utilities/cmcurl/lib/speedcheck.c +++ b/Utilities/cmcurl/lib/speedcheck.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,12 +28,12 @@ #include "multiif.h" #include "speedcheck.h" -void Curl_speedinit(struct SessionHandle *data) +void Curl_speedinit(struct Curl_easy *data) { memset(&data->state.keeps_speed, 0, sizeof(struct timeval)); } -CURLcode Curl_speedcheck(struct SessionHandle *data, +CURLcode Curl_speedcheck(struct Curl_easy *data, struct timeval now) { if((data->progress.current_speed >= 0) && diff --git a/Utilities/cmcurl/lib/speedcheck.h b/Utilities/cmcurl/lib/speedcheck.h index 786cd12..7dbe3d6 100644 --- a/Utilities/cmcurl/lib/speedcheck.h +++ b/Utilities/cmcurl/lib/speedcheck.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,8 +26,8 @@ #include "timeval.h" -void Curl_speedinit(struct SessionHandle *data); -CURLcode Curl_speedcheck(struct SessionHandle *data, +void Curl_speedinit(struct Curl_easy *data); +CURLcode Curl_speedcheck(struct Curl_easy *data, struct timeval now); #endif /* HEADER_CURL_SPEEDCHECK_H */ diff --git a/Utilities/cmcurl/lib/splay.c b/Utilities/cmcurl/lib/splay.c index b87b6cf..7aa2e4b 100644 --- a/Utilities/cmcurl/lib/splay.c +++ b/Utilities/cmcurl/lib/splay.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/splay.h b/Utilities/cmcurl/lib/splay.h index 5f9ef24..427bfc8 100644 --- a/Utilities/cmcurl/lib/splay.h +++ b/Utilities/cmcurl/lib/splay.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1997 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1997 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -55,7 +55,7 @@ int Curl_splayremovebyaddr(struct Curl_tree *t, #define Curl_splaycomparekeys(i,j) ( ((i.tv_sec) < (j.tv_sec)) ? -1 : \ ( ((i.tv_sec) > (j.tv_sec)) ? 1 : \ ( ((i.tv_usec) < (j.tv_usec)) ? -1 : \ - ( ((i.tv_usec) > (j.tv_usec)) ? 1 : 0 )))) + ( ((i.tv_usec) > (j.tv_usec)) ? 1 : 0)))) #ifdef DEBUGBUILD void Curl_splayprint(struct Curl_tree * t, int d, char output); diff --git a/Utilities/cmcurl/lib/ssh.c b/Utilities/cmcurl/lib/ssh.c index 94195a7..7bc3136 100644 --- a/Utilities/cmcurl/lib/ssh.c +++ b/Utilities/cmcurl/lib/ssh.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -83,9 +83,10 @@ #include "multiif.h" #include "select.h" #include "warnless.h" + +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" #ifdef WIN32 @@ -101,6 +102,11 @@ have their definition hidden well */ #endif +#if LIBSSH2_VERSION_NUM >= 0x010206 +/* libssh2_sftp_statvfs and friends were added in 1.2.6 */ +#define HAS_STATVFS_SUPPORT 1 +#endif + #define sftp_libssh2_last_error(s) curlx_ultosi(libssh2_sftp_last_error(s)) #define sftp_libssh2_realpath(s,p,t,m) \ @@ -362,6 +368,9 @@ static void state(struct connectdata *conn, sshstate nowstate) "SSH_SFTP_QUOTE_RENAME", "SSH_SFTP_QUOTE_RMDIR", "SSH_SFTP_QUOTE_UNLINK", + "SSH_SFTP_QUOTE_STATVFS", + "SSH_SFTP_GETINFO", + "SSH_SFTP_FILETIME", "SSH_SFTP_TRANS_INIT", "SSH_SFTP_UPLOAD_INIT", "SSH_SFTP_CREATE_DIRS_INIT", @@ -404,7 +413,7 @@ static CURLcode ssh_getworkingpath(struct connectdata *conn, char **path) /* returns the allocated real path to work with */ { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char *real_path = NULL; char *working_path; int working_path_len; @@ -414,7 +423,7 @@ static CURLcode ssh_getworkingpath(struct connectdata *conn, if(!working_path) return CURLE_OUT_OF_MEMORY; - /* Check for /~/ , indicating relative to the user's home directory */ + /* Check for /~/, indicating relative to the user's home directory */ if(conn->handler->protocol & CURLPROTO_SCP) { real_path = malloc(working_path_len+1); if(real_path == NULL) { @@ -464,7 +473,7 @@ static CURLcode ssh_getworkingpath(struct connectdata *conn, } #ifdef HAVE_LIBSSH2_KNOWNHOST_API -static int sshkeycallback(CURL *easy, +static int sshkeycallback(struct Curl_easy *easy, const struct curl_khkey *knownkey, /* known */ const struct curl_khkey *foundkey, /* found */ enum curl_khmatch match, @@ -513,7 +522,7 @@ static CURLcode ssh_knownhost(struct connectdata *conn) CURLcode result = CURLE_OK; #ifdef HAVE_LIBSSH2_KNOWNHOST_API - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; if(data->set.str[STRING_SSH_KNOWNHOSTS]) { /* we're asked to verify the host against a file */ @@ -648,7 +657,7 @@ static CURLcode ssh_knownhost(struct connectdata *conn) static CURLcode ssh_check_fingerprint(struct connectdata *conn) { struct ssh_conn *sshc = &conn->proto.sshc; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; const char *pubkey_md5 = data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]; char md5buffer[33]; int i; @@ -699,7 +708,7 @@ static CURLcode ssh_check_fingerprint(struct connectdata *conn) static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct SSHPROTO *sftp_scp = data->req.protop; struct ssh_conn *sshc = &conn->proto.sshc; curl_socket_t sock = conn->sock[FIRSTSOCKET]; @@ -848,7 +857,9 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) * libssh2 extract the public key from the private key file. * This is done by simply passing sshc->rsa_pub = NULL. */ - if(data->set.str[STRING_SSH_PUBLIC_KEY]) { + if(data->set.str[STRING_SSH_PUBLIC_KEY] + /* treat empty string the same way as NULL */ + && data->set.str[STRING_SSH_PUBLIC_KEY][0]) { sshc->rsa_pub = strdup(data->set.str[STRING_SSH_PUBLIC_KEY]); if(!sshc->rsa_pub) out_of_memory = TRUE; @@ -869,7 +880,8 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) free(home); - infof(data, "Using SSH public key file '%s'\n", sshc->rsa_pub); + if(sshc->rsa_pub) + infof(data, "Using SSH public key file '%s'\n", sshc->rsa_pub); infof(data, "Using SSH private key file '%s'\n", sshc->rsa); state(conn, SSH_AUTH_PKEY); @@ -1149,8 +1161,13 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) else { /* Return the error type */ err = sftp_libssh2_last_error(sshc->sftp_session); - result = sftp_libssh2_error_to_CURLE(err); - sshc->actualcode = result?result:CURLE_SSH; + if(err) + result = sftp_libssh2_error_to_CURLE(err); + else + /* in this case, the error wasn't in the SFTP level but for example + a time-out or similar */ + result = CURLE_SSH; + sshc->actualcode = result; DEBUGF(infof(data, "error = %d makes libcurl = %d\n", err, (int)result)); state(conn, SSH_STOP); @@ -1180,7 +1197,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) state(conn, SSH_SFTP_QUOTE); } else { - state(conn, SSH_SFTP_TRANS_INIT); + state(conn, SSH_SFTP_GETINFO); } break; @@ -1358,6 +1375,12 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) state(conn, SSH_SFTP_QUOTE_UNLINK); break; } +#ifdef HAS_STATVFS_SUPPORT + else if(curl_strnequal(cmd, "statvfs ", 8)) { + state(conn, SSH_SFTP_QUOTE_STATVFS); + break; + } +#endif failf(data, "Unknown SFTP command"); Curl_safefree(sshc->quote_path1); @@ -1369,7 +1392,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) } } if(!sshc->quote_item) { - state(conn, SSH_SFTP_TRANS_INIT); + state(conn, SSH_SFTP_GETINFO); } break; @@ -1388,7 +1411,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) sshc->nextstate = SSH_NO_STATE; } else { - state(conn, SSH_SFTP_TRANS_INIT); + state(conn, SSH_SFTP_GETINFO); } } break; @@ -1608,6 +1631,88 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) state(conn, SSH_SFTP_NEXT_QUOTE); break; +#ifdef HAS_STATVFS_SUPPORT + case SSH_SFTP_QUOTE_STATVFS: + { + LIBSSH2_SFTP_STATVFS statvfs; + rc = libssh2_sftp_statvfs(sshc->sftp_session, sshc->quote_path1, + curlx_uztoui(strlen(sshc->quote_path1)), + &statvfs); + + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + else if(rc != 0 && !sshc->acceptfail) { + err = sftp_libssh2_last_error(sshc->sftp_session); + Curl_safefree(sshc->quote_path1); + failf(data, "statvfs command failed: %s", sftp_libssh2_strerror(err)); + state(conn, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = CURLE_QUOTE_ERROR; + break; + } + else if(rc == 0) { + char *tmp = aprintf("statvfs:\n" + "f_bsize: %llu\n" "f_frsize: %llu\n" + "f_blocks: %llu\n" "f_bfree: %llu\n" + "f_bavail: %llu\n" "f_files: %llu\n" + "f_ffree: %llu\n" "f_favail: %llu\n" + "f_fsid: %llu\n" "f_flag: %llu\n" + "f_namemax: %llu\n", + statvfs.f_bsize, statvfs.f_frsize, + statvfs.f_blocks, statvfs.f_bfree, + statvfs.f_bavail, statvfs.f_files, + statvfs.f_ffree, statvfs.f_favail, + statvfs.f_fsid, statvfs.f_flag, + statvfs.f_namemax); + if(!tmp) { + result = CURLE_OUT_OF_MEMORY; + state(conn, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + break; + } + + result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp)); + free(tmp); + if(result) { + state(conn, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + } + state(conn, SSH_SFTP_NEXT_QUOTE); + break; + } +#endif + case SSH_SFTP_GETINFO: + { + if(data->set.get_filetime) { + state(conn, SSH_SFTP_FILETIME); + } + else { + state(conn, SSH_SFTP_TRANS_INIT); + } + break; + } + + case SSH_SFTP_FILETIME: + { + LIBSSH2_SFTP_ATTRIBUTES attrs; + + rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path, + curlx_uztoui(strlen(sftp_scp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + else if(rc == 0) { + data->info.filetime = (long)attrs.mtime; + } + + state(conn, SSH_SFTP_TRANS_INIT); + break; + } + case SSH_SFTP_TRANS_INIT: if(data->set.upload) state(conn, SSH_SFTP_UPLOAD_INIT); @@ -1740,8 +1845,8 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) BUFSIZE : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = - data->set.fread_func(data->state.buffer, 1, readthisamountnow, - data->set.in); + data->state.fread_func(data->state.buffer, 1, + readthisamountnow, data->state.in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { @@ -2368,19 +2473,30 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) case SSH_SCP_DOWNLOAD_INIT: { + curl_off_t bytecount; + /* * We must check the remote file; if it is a directory no values will * be set in sb */ - struct stat sb; - curl_off_t bytecount; - /* clear the struct scp recv will fill in */ - memset(&sb, 0, sizeof(struct stat)); + /* + * If support for >2GB files exists, use it. + */ /* get a fresh new channel from the ssh layer */ +#if LIBSSH2_VERSION_NUM < 0x010700 + struct stat sb; + memset(&sb, 0, sizeof(struct stat)); sshc->ssh_channel = libssh2_scp_recv(sshc->ssh_session, sftp_scp->path, &sb); +#else + libssh2_struct_stat sb; + memset(&sb, 0, sizeof(libssh2_struct_stat)); + sshc->ssh_channel = libssh2_scp_recv2(sshc->ssh_session, + sftp_scp->path, &sb); +#endif + if(!sshc->ssh_channel) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { @@ -2708,7 +2824,7 @@ static CURLcode ssh_block_statemach(struct connectdata *conn, { struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; while((sshc->state != SSH_STOP) && !result) { bool block; @@ -2782,7 +2898,7 @@ static CURLcode ssh_connect(struct connectdata *conn, bool *done) #endif struct ssh_conn *ssh; CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* initialize per-handle data if not already */ if(!data->req.protop) @@ -2908,7 +3024,7 @@ static CURLcode ssh_do(struct connectdata *conn, bool *done) { CURLcode result; bool connected = 0; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssh_conn *sshc = &conn->proto.sshc; *done = FALSE; /* default to false */ @@ -2941,8 +3057,6 @@ static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection) struct ssh_conn *ssh = &conn->proto.sshc; (void) dead_connection; - Curl_safefree(conn->data->req.protop); - if(ssh->ssh_session) { /* only if there's a session still around to use! */ @@ -2966,8 +3080,7 @@ static CURLcode ssh_done(struct connectdata *conn, CURLcode status) TODO: when the multi interface is used, this _really_ should be using the ssh_multi_statemach function but we have no general support for - non-blocking DONE operations, not in the multi state machine and with - Curl_done() invokes on several places in the code! + non-blocking DONE operations! */ result = ssh_block_statemach(conn, FALSE); } @@ -3105,8 +3218,6 @@ static CURLcode sftp_disconnect(struct connectdata *conn, bool dead_connection) DEBUGF(infof(conn->data, "SSH DISCONNECT starts now\n")); - Curl_safefree(conn->data->req.protop); - if(conn->proto.sshc.ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SFTP_SHUTDOWN); diff --git a/Utilities/cmcurl/lib/ssh.h b/Utilities/cmcurl/lib/ssh.h index b3cc54c..b350dcf 100644 --- a/Utilities/cmcurl/lib/ssh.h +++ b/Utilities/cmcurl/lib/ssh.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -66,6 +66,9 @@ typedef enum { SSH_SFTP_QUOTE_RENAME, SSH_SFTP_QUOTE_RMDIR, SSH_SFTP_QUOTE_UNLINK, + SSH_SFTP_QUOTE_STATVFS, + SSH_SFTP_GETINFO, + SSH_SFTP_FILETIME, SSH_SFTP_TRANS_INIT, SSH_SFTP_UPLOAD_INIT, SSH_SFTP_CREATE_DIRS_INIT, @@ -95,7 +98,7 @@ typedef enum { } sshstate; /* this struct is used in the HandleData struct which is part of the - SessionHandle, which means this is used on a per-easy handle basis. + Curl_easy, which means this is used on a per-easy handle basis. Everything that is strictly related to a connection is banned from this struct. */ struct SSHPROTO { diff --git a/Utilities/cmcurl/lib/strdup.c b/Utilities/cmcurl/lib/strdup.c index 5685b81..23f554e 100644 --- a/Utilities/cmcurl/lib/strdup.c +++ b/Utilities/cmcurl/lib/strdup.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -19,7 +19,11 @@ * KIND, either express or implied. * ***************************************************************************/ + #include "curl_setup.h" + +#include <curl/curl.h> + #include "strdup.h" #include "curl_memory.h" diff --git a/Utilities/cmcurl/lib/strdup.h b/Utilities/cmcurl/lib/strdup.h index 23a71f8..4c48ca4 100644 --- a/Utilities/cmcurl/lib/strdup.h +++ b/Utilities/cmcurl/lib/strdup.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strequal.c b/Utilities/cmcurl/lib/strequal.c index 5f2f508..01c3784 100644 --- a/Utilities/cmcurl/lib/strequal.c +++ b/Utilities/cmcurl/lib/strequal.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strequal.h b/Utilities/cmcurl/lib/strequal.h index 117a305..ff56df5 100644 --- a/Utilities/cmcurl/lib/strequal.h +++ b/Utilities/cmcurl/lib/strequal.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strerror.c b/Utilities/cmcurl/lib/strerror.c index 5657141..0e268d5 100644 --- a/Utilities/cmcurl/lib/strerror.c +++ b/Utilities/cmcurl/lib/strerror.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2004 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2004 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -39,10 +39,14 @@ #include <idna.h> #endif +#ifdef USE_WINDOWS_SSPI +#include "curl_sspi.h" +#endif + #include "strerror.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" const char * @@ -301,6 +305,9 @@ curl_easy_strerror(CURLcode error) case CURLE_SSL_INVALIDCERTSTATUS: return "SSL server certificate status verification FAILED"; + case CURLE_HTTP2_STREAM: + return "Stream error in the HTTP/2 framing layer"; + /* error codes not used by current libcurl */ case CURLE_OBSOLETE20: case CURLE_OBSOLETE24: @@ -1072,14 +1079,13 @@ const char *Curl_sspi_strerror (struct connectdata *conn, int err) strncpy(outbuf, txt, outmax); else if(err == SEC_E_ILLEGAL_MESSAGE) snprintf(outbuf, outmax, - "SEC_E_ILLEGAL_MESSAGE (0x%04X%04X) - This error usually occurs " + "SEC_E_ILLEGAL_MESSAGE (0x%08X) - This error usually occurs " "when a fatal SSL/TLS alert is received (e.g. handshake failed). " "More detail may be available in the Windows System event log.", - (err >> 16) & 0xffff, err & 0xffff); + err); else { str = txtbuf; - snprintf(txtbuf, sizeof(txtbuf), "%s (0x%04X%04X)", - txt, (err >> 16) & 0xffff, err & 0xffff); + snprintf(txtbuf, sizeof(txtbuf), "%s (0x%08X)", txt, err); txtbuf[sizeof(txtbuf)-1] = '\0'; #ifdef _WIN32_WCE diff --git a/Utilities/cmcurl/lib/strerror.h b/Utilities/cmcurl/lib/strerror.h index f1b2221..ae8c96b 100644 --- a/Utilities/cmcurl/lib/strerror.h +++ b/Utilities/cmcurl/lib/strerror.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strtok.c b/Utilities/cmcurl/lib/strtok.c index 0d31351..460eb87 100644 --- a/Utilities/cmcurl/lib/strtok.c +++ b/Utilities/cmcurl/lib/strtok.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strtok.h b/Utilities/cmcurl/lib/strtok.h index 1147d70..90b831e 100644 --- a/Utilities/cmcurl/lib/strtok.h +++ b/Utilities/cmcurl/lib/strtok.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strtoofft.c b/Utilities/cmcurl/lib/strtoofft.c index 03a97e8..6d5d2d5 100644 --- a/Utilities/cmcurl/lib/strtoofft.c +++ b/Utilities/cmcurl/lib/strtoofft.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/strtoofft.h b/Utilities/cmcurl/lib/strtoofft.h index 75c73d4..f4039f3 100644 --- a/Utilities/cmcurl/lib/strtoofft.h +++ b/Utilities/cmcurl/lib/strtoofft.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/system_win32.c b/Utilities/cmcurl/lib/system_win32.c new file mode 100644 index 0000000..d6a998b --- /dev/null +++ b/Utilities/cmcurl/lib/system_win32.c @@ -0,0 +1,294 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2016, Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(WIN32) + +#include <curl/curl.h> +#include "system_win32.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(USE_WINDOWS_SSPI) || (!defined(CURL_DISABLE_TELNET) && \ + defined(USE_WINSOCK)) + + +#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH) +#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008 +#endif + +#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32) +#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 +#endif + +/* We use our own typedef here since some headers might lack these */ +typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD); + +/* See function definitions in winbase.h */ +#ifdef UNICODE +# ifdef _WIN32_WCE +# define LOADLIBARYEX L"LoadLibraryExW" +# else +# define LOADLIBARYEX "LoadLibraryExW" +# endif +#else +# define LOADLIBARYEX "LoadLibraryExA" +#endif + +#endif /* USE_WINDOWS_SSPI || (!CURL_DISABLE_TELNET && USE_WINSOCK) */ + +/* + * Curl_verify_windows_version() + * + * This is used to verify if we are running on a specific windows version. + * + * Parameters: + * + * majorVersion [in] - The major version number. + * minorVersion [in] - The minor version number. + * platform [in] - The optional platform identifer. + * condition [in] - The test condition used to specifier whether we are + * checking a version less then, equal to or greater than + * what is specified in the major and minor version + * numbers. + * + * Returns TRUE if matched; otherwise FALSE. + */ +bool Curl_verify_windows_version(const unsigned int majorVersion, + const unsigned int minorVersion, + const PlatformIdentifier platform, + const VersionCondition condition) +{ + bool matched = FALSE; + +#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \ + (_WIN32_WINNT < _WIN32_WINNT_WIN2K) + OSVERSIONINFO osver; + + memset(&osver, 0, sizeof(osver)); + osver.dwOSVersionInfoSize = sizeof(osver); + + /* Find out Windows version */ + if(GetVersionEx(&osver)) { + /* Verify the Operating System version number */ + switch(condition) { + case VERSION_LESS_THAN: + if(osver.dwMajorVersion < majorVersion || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion < minorVersion)) + matched = TRUE; + break; + + case VERSION_LESS_THAN_EQUAL: + if(osver.dwMajorVersion <= majorVersion && + osver.dwMinorVersion <= minorVersion) + matched = TRUE; + break; + + case VERSION_EQUAL: + if(osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion == minorVersion) + matched = TRUE; + break; + + case VERSION_GREATER_THAN_EQUAL: + if(osver.dwMajorVersion >= majorVersion && + osver.dwMinorVersion >= minorVersion) + matched = TRUE; + break; + + case VERSION_GREATER_THAN: + if(osver.dwMajorVersion > majorVersion || + (osver.dwMajorVersion == majorVersion && + osver.dwMinorVersion > minorVersion)) + matched = TRUE; + break; + } + + /* Verify the platform identifier (if necessary) */ + if(matched && platform != PLATFORM_DONT_CARE) { + switch(platform) { + case PLATFORM_WINDOWS: + if(osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) + matched = FALSE; + break; + + case PLATFORM_WINNT: + if(osver.dwPlatformId != VER_PLATFORM_WIN32_NT) + matched = FALSE; + } + } + } +#else + ULONGLONG cm = 0; + OSVERSIONINFOEX osver; + BYTE majorCondition; + BYTE minorCondition; + BYTE spMajorCondition; + BYTE spMinorCondition; + + switch(condition) { + case VERSION_LESS_THAN: + majorCondition = VER_LESS; + minorCondition = VER_LESS; + spMajorCondition = VER_LESS_EQUAL; + spMinorCondition = VER_LESS_EQUAL; + break; + + case VERSION_LESS_THAN_EQUAL: + majorCondition = VER_LESS_EQUAL; + minorCondition = VER_LESS_EQUAL; + spMajorCondition = VER_LESS_EQUAL; + spMinorCondition = VER_LESS_EQUAL; + break; + + case VERSION_EQUAL: + majorCondition = VER_EQUAL; + minorCondition = VER_EQUAL; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + case VERSION_GREATER_THAN_EQUAL: + majorCondition = VER_GREATER_EQUAL; + minorCondition = VER_GREATER_EQUAL; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + case VERSION_GREATER_THAN: + majorCondition = VER_GREATER; + minorCondition = VER_GREATER; + spMajorCondition = VER_GREATER_EQUAL; + spMinorCondition = VER_GREATER_EQUAL; + break; + + default: + return FALSE; + } + + memset(&osver, 0, sizeof(osver)); + osver.dwOSVersionInfoSize = sizeof(osver); + osver.dwMajorVersion = majorVersion; + osver.dwMinorVersion = minorVersion; + if(platform == PLATFORM_WINDOWS) + osver.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS; + else if(platform == PLATFORM_WINNT) + osver.dwPlatformId = VER_PLATFORM_WIN32_NT; + + cm = VerSetConditionMask(cm, VER_MAJORVERSION, majorCondition); + cm = VerSetConditionMask(cm, VER_MINORVERSION, minorCondition); + cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, spMajorCondition); + cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, spMinorCondition); + if(platform != PLATFORM_DONT_CARE) + cm = VerSetConditionMask(cm, VER_PLATFORMID, VER_EQUAL); + + if(VerifyVersionInfo(&osver, (VER_MAJORVERSION | VER_MINORVERSION | + VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR), + cm)) + matched = TRUE; +#endif + + return matched; +} + +#if defined(USE_WINDOWS_SSPI) || (!defined(CURL_DISABLE_TELNET) && \ + defined(USE_WINSOCK)) + +/* + * Curl_load_library() + * + * This is used to dynamically load DLLs using the most secure method available + * for the version of Windows that we are running on. + * + * Parameters: + * + * filename [in] - The filename or full path of the DLL to load. If only the + * filename is passed then the DLL will be loaded from the + * Windows system directory. + * + * Returns the handle of the module on success; otherwise NULL. + */ +HMODULE Curl_load_library(LPCTSTR filename) +{ + HMODULE hModule = NULL; + LOADLIBRARYEX_FN pLoadLibraryEx = NULL; + + /* Get a handle to kernel32 so we can access it's functions at runtime */ + HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32")); + if(!hKernel32) + return NULL; + + /* Attempt to find LoadLibraryEx() which is only available on Windows 2000 + and above */ + pLoadLibraryEx = (LOADLIBRARYEX_FN) GetProcAddress(hKernel32, LOADLIBARYEX); + + /* Detect if there's already a path in the filename and load the library if + there is. Note: Both back slashes and forward slashes have been supported + since the earlier days of DOS at an API level although they are not + supported by command prompt */ + if(_tcspbrk(filename, TEXT("\\/"))) { + /** !checksrc! disable BANNEDFUNC 1 **/ + hModule = pLoadLibraryEx ? + pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) : + LoadLibrary(filename); + } + /* Detect if KB2533623 is installed, as LOAD_LIBARY_SEARCH_SYSTEM32 is only + supported on Windows Vista, Windows Server 2008, Windows 7 and Windows + Server 2008 R2 with this patch or natively on Windows 8 and above */ + else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) { + /* Load the DLL from the Windows system directory */ + hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + } + else { + /* Attempt to get the Windows system path */ + UINT systemdirlen = GetSystemDirectory(NULL, 0); + if(systemdirlen) { + /* Allocate space for the full DLL path (Room for the null terminator + is included in systemdirlen) */ + size_t filenamelen = _tcslen(filename); + TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen)); + if(path && GetSystemDirectory(path, systemdirlen)) { + /* Calculate the full DLL path */ + _tcscpy(path + _tcslen(path), TEXT("\\")); + _tcscpy(path + _tcslen(path), filename); + + /* Load the DLL from the Windows system directory */ + /** !checksrc! disable BANNEDFUNC 1 **/ + hModule = pLoadLibraryEx ? + pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) : + LoadLibrary(path); + + } + free(path); + } + } + + return hModule; +} + +#endif /* USE_WINDOWS_SSPI || (!CURL_DISABLE_TELNET && USE_WINSOCK) */ + +#endif /* WIN32 */ diff --git a/Utilities/cmcurl/lib/system_win32.h b/Utilities/cmcurl/lib/system_win32.h new file mode 100644 index 0000000..1e77285 --- /dev/null +++ b/Utilities/cmcurl/lib/system_win32.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_SYSTEM_WIN32_H +#define HEADER_CURL_SYSTEM_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2016, Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(WIN32) + +/* Version condition */ +typedef enum { + VERSION_LESS_THAN, + VERSION_LESS_THAN_EQUAL, + VERSION_EQUAL, + VERSION_GREATER_THAN_EQUAL, + VERSION_GREATER_THAN +} VersionCondition; + +/* Platform identifier */ +typedef enum { + PLATFORM_DONT_CARE, + PLATFORM_WINDOWS, + PLATFORM_WINNT +} PlatformIdentifier; + +/* This is used to verify if we are running on a specific windows version */ +bool Curl_verify_windows_version(const unsigned int majorVersion, + const unsigned int minorVersion, + const PlatformIdentifier platform, + const VersionCondition condition); + +#if defined(USE_WINDOWS_SSPI) || (!defined(CURL_DISABLE_TELNET) && \ + defined(USE_WINSOCK)) + +/* This is used to dynamically load DLLs */ +HMODULE Curl_load_library(LPCTSTR filename); + +#endif /* USE_WINDOWS_SSPI || (!CURL_DISABLE_TELNET && USE_WINSOCK) */ + +#endif /* WIN32 */ + +#endif /* HEADER_CURL_SYSTEM_WIN32_H */ diff --git a/Utilities/cmcurl/lib/telnet.c b/Utilities/cmcurl/lib/telnet.c index aabf99d..cc705cf 100644 --- a/Utilities/cmcurl/lib/telnet.c +++ b/Utilities/cmcurl/lib/telnet.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -51,7 +51,7 @@ #include "telnet.h" #include "connect.h" #include "progress.h" -#include "curl_printf.h" +#include "system_win32.h" #define TELOPTS #define TELCMDS @@ -62,7 +62,8 @@ #include "rawstr.h" #include "warnless.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -91,7 +92,7 @@ #ifdef USE_WINSOCK typedef FARPROC WSOCK2_FUNC; -static CURLcode check_wsock2 ( struct SessionHandle *data ); +static CURLcode check_wsock2 (struct Curl_easy *data); #endif static @@ -100,7 +101,7 @@ CURLcode telrcv(struct connectdata *, ssize_t count); /* Number of bytes received */ #ifndef CURL_DISABLE_VERBOSE_STRINGS -static void printoption(struct SessionHandle *data, +static void printoption(struct Curl_easy *data, const char *direction, int cmd, int option); #endif @@ -110,7 +111,7 @@ static void send_negotiation(struct connectdata *, int cmd, int option); static void set_local_option(struct connectdata *, int cmd, int option); static void set_remote_option(struct connectdata *, int cmd, int option); -static void printsub(struct SessionHandle *data, +static void printsub(struct Curl_easy *data, int direction, unsigned char *pointer, size_t length); static void suboption(struct connectdata *); @@ -198,7 +199,7 @@ const struct Curl_handler Curl_handler_telnet = { #ifdef USE_WINSOCK static CURLcode -check_wsock2 ( struct SessionHandle *data ) +check_wsock2(struct Curl_easy *data) { int err; WORD wVersionRequested; @@ -305,7 +306,7 @@ static void negotiate(struct connectdata *conn) } #ifndef CURL_DISABLE_VERBOSE_STRINGS -static void printoption(struct SessionHandle *data, +static void printoption(struct Curl_easy *data, const char *direction, int cmd, int option) { const char *fmt; @@ -346,7 +347,7 @@ static void send_negotiation(struct connectdata *conn, int cmd, int option) unsigned char buf[3]; ssize_t bytes_written; int err; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; buf[0] = CURL_IAC; buf[1] = (unsigned char)cmd; @@ -702,7 +703,7 @@ void rec_dont(struct connectdata *conn, int option) } -static void printsub(struct SessionHandle *data, +static void printsub(struct Curl_easy *data, int direction, /* '<' or '>' */ unsigned char *pointer, /* where suboption data is */ size_t length) /* length of suboption data */ @@ -821,7 +822,7 @@ static CURLcode check_telnet_options(struct connectdata *conn) struct curl_slist *beg; char option_keyword[128] = ""; char option_arg[256] = ""; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)conn->data->req.protop; CURLcode result = CURLE_OK; int binary_option; @@ -931,7 +932,7 @@ static void suboption(struct connectdata *conn) int err; char varname[128] = ""; char varval[128] = ""; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)data->req.protop; printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn)+2); @@ -1006,7 +1007,7 @@ static void sendsuboption(struct connectdata *conn, int option) unsigned short x, y; unsigned char*uc1, *uc2; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)data->req.protop; switch (option) { @@ -1064,7 +1065,7 @@ CURLcode telrcv(struct connectdata *conn, CURLcode result; int in = 0; int startwrite=-1; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)data->req.protop; #define startskipping() \ @@ -1281,7 +1282,7 @@ static CURLcode telnet_done(struct connectdata *conn, static CURLcode telnet_do(struct connectdata *conn, bool *done) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #ifdef USE_WINSOCK HMODULE wsock2; @@ -1334,7 +1335,7 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done) /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ - wsock2 = LoadLibrary(TEXT("WS2_32.DLL")); + wsock2 = Curl_load_library(TEXT("WS2_32.DLL")); if(wsock2 == NULL) { failf(data, "failed to load WS2_32.DLL (%d)", ERRNO); return CURLE_FAILED_INIT; @@ -1423,8 +1424,8 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done) for(;;) { if(data->set.is_fread_set) { /* read from user-supplied method */ - result = (int)data->set.fread_func(buf, 1, BUFSIZE - 1, - data->set.in); + result = (int)data->state.fread_func(buf, 1, BUFSIZE - 1, + data->state.in); if(result == CURL_READFUNC_ABORT) { keepon = FALSE; result = CURLE_READ_ERROR; @@ -1563,13 +1564,13 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done) pfd[0].fd = sockfd; pfd[0].events = POLLIN; - if(data->set.fread_func != (curl_read_callback)fread) { + if(data->set.is_fread_set) { poll_cnt = 1; interval_ms = 100; /* poll user-supplied read function */ } else { /* really using fread, so infile is a FILE* */ - pfd[1].fd = fileno((FILE *)data->set.in); + pfd[1].fd = fileno((FILE *)data->state.in); pfd[1].events = POLLIN; poll_cnt = 2; interval_ms = 1 * 1000; @@ -1628,7 +1629,8 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done) } else { /* read from user-supplied method */ - nread = (int)data->set.fread_func(buf, 1, BUFSIZE - 1, data->set.in); + nread = (int)data->state.fread_func(buf, 1, BUFSIZE - 1, + data->state.in); if(nread == CURL_READFUNC_ABORT) { keepon = FALSE; break; diff --git a/Utilities/cmcurl/lib/telnet.h b/Utilities/cmcurl/lib/telnet.h index ddb9e54..419a399 100644 --- a/Utilities/cmcurl/lib/telnet.h +++ b/Utilities/cmcurl/lib/telnet.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/tftp.c b/Utilities/cmcurl/lib/tftp.c index 4c5796f..d7ff94f 100644 --- a/Utilities/cmcurl/lib/tftp.c +++ b/Utilities/cmcurl/lib/tftp.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -57,10 +57,10 @@ #include "url.h" #include "rawstr.h" #include "speedcheck.h" -#include "curl_printf.h" #include "select.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -312,14 +312,14 @@ static const char *tftp_option_get(const char *buf, size_t len, { size_t loc; - loc = Curl_strnlen( buf, len ); + loc = Curl_strnlen(buf, len); loc++; /* NULL term */ if(loc >= len) return NULL; *option = buf; - loc += Curl_strnlen( buf+loc, len-loc ); + loc += Curl_strnlen(buf+loc, len-loc); loc++; /* NULL term */ if(loc > len) @@ -333,7 +333,7 @@ static CURLcode tftp_parse_option_ack(tftp_state_data_t *state, const char *ptr, int len) { const char *tmp = ptr; - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; /* if OACK doesn't contain blksize option, the default (512) must be used */ state->blksize = TFTP_BLKSIZE_DEFAULT; @@ -352,7 +352,7 @@ static CURLcode tftp_parse_option_ack(tftp_state_data_t *state, if(checkprefix(option, TFTP_OPTION_BLKSIZE)) { long blksize; - blksize = strtol( value, NULL, 10 ); + blksize = strtol(value, NULL, 10); if(!blksize) { failf(data, "invalid blocksize value in OACK packet"); @@ -384,7 +384,7 @@ static CURLcode tftp_parse_option_ack(tftp_state_data_t *state, else if(checkprefix(option, TFTP_OPTION_TSIZE)) { long tsize = 0; - tsize = strtol( value, NULL, 10 ); + tsize = strtol(value, NULL, 10); infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize); /* tsize should be ignored on upload: Who cares about the size of the @@ -405,7 +405,7 @@ static CURLcode tftp_parse_option_ack(tftp_state_data_t *state, static size_t tftp_option_add(tftp_state_data_t *state, size_t csize, char *buf, const char *option) { - if(( strlen(option) + csize + 1 ) > (size_t)state->blksize) + if(( strlen(option) + csize + 1) > (size_t)state->blksize) return 0; strcpy(buf, option); return strlen(option) + 1; @@ -416,7 +416,7 @@ static CURLcode tftp_connect_for_tx(tftp_state_data_t *state, { CURLcode result; #ifndef CURL_DISABLE_VERBOSE_STRINGS - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; infof(data, "%s\n", "Connected for transmit"); #endif @@ -432,7 +432,7 @@ static CURLcode tftp_connect_for_rx(tftp_state_data_t *state, { CURLcode result; #ifndef CURL_DISABLE_VERBOSE_STRINGS - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; infof(data, "%s\n", "Connected for receive"); #endif @@ -450,7 +450,7 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event) const char *mode = "octet"; char *filename; char buf[64]; - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; CURLcode result = CURLE_OK; /* Set ascii mode if -B flag was used */ @@ -494,33 +494,36 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event) "%s%c%s%c", filename, '\0', mode, '\0'); sbytes = 4 + strlen(filename) + strlen(mode); - /* add tsize option */ - if(data->set.upload && (data->state.infilesize != -1)) - snprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T, - data->state.infilesize); - else - strcpy(buf, "0"); /* the destination is large enough */ - - sbytes += tftp_option_add(state, sbytes, - (char *)state->spacket.data+sbytes, - TFTP_OPTION_TSIZE); - sbytes += tftp_option_add(state, sbytes, - (char *)state->spacket.data+sbytes, buf); - /* add blksize option */ - snprintf( buf, sizeof(buf), "%d", state->requested_blksize ); - sbytes += tftp_option_add(state, sbytes, - (char *)state->spacket.data+sbytes, - TFTP_OPTION_BLKSIZE); - sbytes += tftp_option_add(state, sbytes, - (char *)state->spacket.data+sbytes, buf ); - - /* add timeout option */ - snprintf( buf, sizeof(buf), "%d", state->retry_time); - sbytes += tftp_option_add(state, sbytes, - (char *)state->spacket.data+sbytes, - TFTP_OPTION_INTERVAL); - sbytes += tftp_option_add(state, sbytes, - (char *)state->spacket.data+sbytes, buf ); + /* optional addition of TFTP options */ + if(!data->set.tftp_no_options) { + /* add tsize option */ + if(data->set.upload && (data->state.infilesize != -1)) + snprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T, + data->state.infilesize); + else + strcpy(buf, "0"); /* the destination is large enough */ + + sbytes += tftp_option_add(state, sbytes, + (char *)state->spacket.data+sbytes, + TFTP_OPTION_TSIZE); + sbytes += tftp_option_add(state, sbytes, + (char *)state->spacket.data+sbytes, buf); + /* add blksize option */ + snprintf(buf, sizeof(buf), "%d", state->requested_blksize); + sbytes += tftp_option_add(state, sbytes, + (char *)state->spacket.data+sbytes, + TFTP_OPTION_BLKSIZE); + sbytes += tftp_option_add(state, sbytes, + (char *)state->spacket.data+sbytes, buf); + + /* add timeout option */ + snprintf(buf, sizeof(buf), "%d", state->retry_time); + sbytes += tftp_option_add(state, sbytes, + (char *)state->spacket.data+sbytes, + TFTP_OPTION_INTERVAL); + sbytes += tftp_option_add(state, sbytes, + (char *)state->spacket.data+sbytes, buf); + } /* the typecase for the 3rd argument is mostly for systems that do not have a size_t argument, like older unixes that want an 'int' */ @@ -578,7 +581,7 @@ static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) { ssize_t sbytes; int rblock; - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; switch(event) { @@ -697,7 +700,7 @@ static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) **********************************************************/ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) { - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; ssize_t sbytes; int rblock; CURLcode result = CURLE_OK; @@ -886,7 +889,7 @@ static CURLcode tftp_state_machine(tftp_state_data_t *state, tftp_event_t event) { CURLcode result = CURLE_OK; - struct SessionHandle *data = state->conn->data; + struct Curl_easy *data = state->conn->data; switch(state->state) { case TFTP_STATE_START: @@ -957,7 +960,7 @@ static CURLcode tftp_connect(struct connectdata *conn, bool *done) /* alloc pkt buffers based on specified blksize */ if(conn->data->set.tftp_blksize) { blksize = (int)conn->data->set.tftp_blksize; - if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN ) + if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN) return CURLE_TFTP_ILLEGAL; } @@ -975,7 +978,7 @@ static CURLcode tftp_connect(struct connectdata *conn, bool *done) return CURLE_OUT_OF_MEMORY; } - /* we don't keep TFTP connections up bascially because there's none or very + /* we don't keep TFTP connections up basically because there's none or very * little gain for UDP */ connclose(conn, "TFTP"); @@ -1078,7 +1081,7 @@ static CURLcode tftp_receive_packet(struct connectdata *conn) struct Curl_sockaddr_storage fromaddr; curl_socklen_t fromlen; CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; struct SingleRequest *k = &data->req; @@ -1197,7 +1200,7 @@ static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done) int rc; tftp_event_t event; CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; long timeout_ms = tftp_state_timeout(conn, &event); @@ -1339,7 +1342,7 @@ static CURLcode tftp_do(struct connectdata *conn, bool *done) static CURLcode tftp_setup_connection(struct connectdata * conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; char * type; char command; diff --git a/Utilities/cmcurl/lib/tftp.h b/Utilities/cmcurl/lib/tftp.h index 117b40f..c2325b2 100644 --- a/Utilities/cmcurl/lib/tftp.h +++ b/Utilities/cmcurl/lib/tftp.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/timeval.c b/Utilities/cmcurl/lib/timeval.c index 45731ac..629f1c8 100644 --- a/Utilities/cmcurl/lib/timeval.c +++ b/Utilities/cmcurl/lib/timeval.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -113,10 +113,18 @@ struct timeval curlx_tvnow(void) * Make sure that the first argument is the more recent time, as otherwise * we'll get a weird negative time-diff back... * - * Returns: the time difference in number of milliseconds. + * Returns: the time difference in number of milliseconds. For large diffs it + * returns 0x7fffffff on 32bit time_t systems. */ long curlx_tvdiff(struct timeval newer, struct timeval older) { +#if SIZEOF_TIME_T < 8 + /* for 32bit time_t systems, add a precaution to avoid overflow for really + big time differences */ + time_t diff = newer.tv_sec-older.tv_sec; + if(diff >= (0x7fffffff/1000)) + return 0x7fffffff; +#endif return (newer.tv_sec-older.tv_sec)*1000+ (long)(newer.tv_usec-older.tv_usec)/1000; } diff --git a/Utilities/cmcurl/lib/timeval.h b/Utilities/cmcurl/lib/timeval.h index 3f1b9ea..50c31a2 100644 --- a/Utilities/cmcurl/lib/timeval.h +++ b/Utilities/cmcurl/lib/timeval.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/transfer.c b/Utilities/cmcurl/lib/transfer.c index 718139b..f5987fe 100644 --- a/Utilities/cmcurl/lib/transfer.c +++ b/Utilities/cmcurl/lib/transfer.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -71,17 +71,13 @@ #include "url.h" #include "getinfo.h" #include "vtls/vtls.h" -#include "http_digest.h" -#include "curl_ntlm.h" -#include "http_negotiate.h" -#include "share.h" #include "select.h" #include "multiif.h" #include "connect.h" #include "non-ascii.h" -#include "curl_printf.h" -/* The last #include files should be: */ +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" @@ -91,7 +87,7 @@ */ CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; size_t buffersize = (size_t)bytes; int nread; #ifdef CURL_DOES_CONVERSIONS @@ -115,8 +111,8 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp) /* this function returns a size_t, so we typecast to int to prevent warnings with picky compilers */ - nread = (int)data->set.fread_func(data->req.upload_fromhere, 1, - buffersize, data->set.in); + nread = (int)data->state.fread_func(data->req.upload_fromhere, 1, + buffersize, data->state.in); if(nread == CURL_READFUNC_ABORT) { failf(data, "operation aborted by callback"); @@ -246,7 +242,7 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp) */ CURLcode Curl_readrewind(struct connectdata *conn) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; conn->bits.rewindaftersend = FALSE; /* we rewind now */ @@ -289,8 +285,8 @@ CURLcode Curl_readrewind(struct connectdata *conn) /* If no CURLOPT_READFUNCTION is used, we know that we operate on a given FILE * stream and we can actually attempt to rewind that ourselves with fseek() */ - if(data->set.fread_func == (curl_read_callback)fread) { - if(-1 != fseek(data->set.in, 0, SEEK_SET)) + if(data->state.fread_func == (curl_read_callback)fread) { + if(-1 != fseek(data->state.in, 0, SEEK_SET)) /* successful rewind */ return CURLE_OK; } @@ -356,7 +352,7 @@ static void read_rewind(struct connectdata *conn, * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the * remote document with the time provided by CURLOPT_TIMEVAL */ -bool Curl_meets_timecondition(struct SessionHandle *data, time_t timeofdoc) +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc) { if((timeofdoc == 0) || (data->set.timevalue == 0)) return TRUE; @@ -389,7 +385,7 @@ bool Curl_meets_timecondition(struct SessionHandle *data, time_t timeofdoc) * the stream was rewound (in which case we have data in a * buffer) */ -static CURLcode readwrite_data(struct SessionHandle *data, +static CURLcode readwrite_data(struct Curl_easy *data, struct connectdata *conn, struct SingleRequest *k, int *didwhat, bool *done) @@ -399,6 +395,7 @@ static CURLcode readwrite_data(struct SessionHandle *data, size_t excess = 0; /* excess bytes read */ bool is_empty_data = FALSE; bool readmore = FALSE; /* used by RTP to signal for more data */ + int maxloops = 100; *done = FALSE; @@ -409,7 +406,18 @@ static CURLcode readwrite_data(struct SessionHandle *data, data->set.buffer_size : BUFSIZE; size_t bytestoread = buffersize; - if(k->size != -1 && !k->header) { + if( +#if defined(USE_NGHTTP2) + /* For HTTP/2, read data without caring about the content + length. This is safe because body in HTTP/2 is always + segmented thanks to its framing layer. Meanwhile, we have to + call Curl_read to ensure that http2_handle_stream_close is + called when we read all incoming bytes for a particular + stream. */ + !((conn->handler->protocol & PROTO_FAMILY_HTTP) && + conn->httpversion == 20) && +#endif + k->size != -1 && !k->header) { /* make sure we don't read "too much" if we can help it since we might be pipelining and then someone else might want to read what follows! */ @@ -686,7 +694,7 @@ static CURLcode readwrite_data(struct SessionHandle *data, } nread = (ssize_t) (k->maxdownload - k->bytecount); - if(nread < 0 ) /* this should be unusual */ + if(nread < 0) /* this should be unusual */ nread = 0; k->keepon &= ~KEEP_RECV; /* we're done reading */ @@ -771,7 +779,7 @@ static CURLcode readwrite_data(struct SessionHandle *data, return result; } - } /* if(! header and data to read ) */ + } /* if(!header and data to read) */ if(conn->handler->readwrite && (excess > 0 && !conn->bits.stream_was_rewound)) { @@ -794,10 +802,10 @@ static CURLcode readwrite_data(struct SessionHandle *data, k->keepon &= ~KEEP_RECV; } - } while(data_pending(conn)); + } while(data_pending(conn) && maxloops--); if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) && - conn->bits.close ) { + conn->bits.close) { /* When we've read the entire thing and the close bit is set, the server may now close the connection. If there's now any kind of sending going on from our side, we need to stop that immediately. */ @@ -808,10 +816,24 @@ static CURLcode readwrite_data(struct SessionHandle *data, return CURLE_OK; } +static CURLcode done_sending(struct connectdata *conn, + struct SingleRequest *k) +{ + k->keepon &= ~KEEP_SEND; /* we're done writing */ + + if(conn->bits.rewindaftersend) { + CURLcode result = Curl_readrewind(conn); + if(result) + return result; + } + return CURLE_OK; +} + + /* * Send data to upload to the server, when the socket is writable. */ -static CURLcode readwrite_upload(struct SessionHandle *data, +static CURLcode readwrite_upload(struct Curl_easy *data, struct connectdata *conn, struct SingleRequest *k, int *didwhat) @@ -879,14 +901,9 @@ static CURLcode readwrite_upload(struct SessionHandle *data, break; } else if(nread<=0) { - /* done */ - k->keepon &= ~KEEP_SEND; /* we're done writing */ - - if(conn->bits.rewindaftersend) { - result = Curl_readrewind(conn); - if(result) - return result; - } + result = done_sending(conn, k); + if(result) + return result; break; } @@ -923,7 +940,8 @@ static CURLcode readwrite_upload(struct SessionHandle *data, if(!data->set.crlf) { /* we're here only because FTP is in ASCII mode... bump infilesize for the LF we just added */ - data->state.infilesize++; + if(data->state.infilesize != -1) + data->state.infilesize++; } } else @@ -995,8 +1013,9 @@ static CURLcode readwrite_upload(struct SessionHandle *data, data->req.upload_present = 0; /* no more bytes left */ if(k->upload_done) { - /* switch off writing, we're done! */ - k->keepon &= ~KEEP_SEND; /* we're done writing */ + result = done_sending(conn, k); + if(result) + return result; } } @@ -1012,7 +1031,7 @@ static CURLcode readwrite_upload(struct SessionHandle *data, * be read and written to/from the connection. */ CURLcode Curl_readwrite(struct connectdata *conn, - struct SessionHandle *data, + struct Curl_easy *data, bool *done) { struct SingleRequest *k = &data->req; @@ -1189,7 +1208,7 @@ int Curl_single_getsock(const struct connectdata *conn, of sockets */ int numsocks) { - const struct SessionHandle *data = conn->data; + const struct Curl_easy *data = conn->data; int bitmap = GETSOCK_BLANK; unsigned sockindex = 0; @@ -1284,10 +1303,20 @@ long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps, return (long)rv; } +/* Curl_init_CONNECT() gets called each time the handle switches to CONNECT + which means this gets called once for each subsequent redirect etc */ +void Curl_init_CONNECT(struct Curl_easy *data) +{ + data->state.fread_func = data->set.fread_func_set; + data->state.in = data->set.in_set; +} + /* - * Curl_pretransfer() is called immediately before a transfer starts. + * Curl_pretransfer() is called immediately before a transfer starts, and only + * once for one transfer no matter if it has redirects or do multi-pass + * authentication etc. */ -CURLcode Curl_pretransfer(struct SessionHandle *data) +CURLcode Curl_pretransfer(struct Curl_easy *data) { CURLcode result; if(!data->change.url) { @@ -1356,6 +1385,16 @@ CURLcode Curl_pretransfer(struct SessionHandle *data) consider to be fine */ data->state.authhost.picked &= data->state.authhost.want; data->state.authproxy.picked &= data->state.authproxy.want; + + if(data->set.wildcardmatch) { + struct WildcardData *wc = &data->wildcard; + if(!wc->filelist) { + result = Curl_wildcard_init(wc); /* init wildcard structures */ + if(result) + return CURLE_OUT_OF_MEMORY; + } + } + } return result; @@ -1364,7 +1403,7 @@ CURLcode Curl_pretransfer(struct SessionHandle *data) /* * Curl_posttransfer() is called immediately after a transfer ends */ -CURLcode Curl_posttransfer(struct SessionHandle *data) +CURLcode Curl_posttransfer(struct Curl_easy *data) { #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) /* restore the signal handler for SIGPIPE before we get back */ @@ -1384,16 +1423,18 @@ CURLcode Curl_posttransfer(struct SessionHandle *data) */ static size_t strlen_url(const char *url) { - const char *ptr; + const unsigned char *ptr; size_t newlen=0; bool left=TRUE; /* left side of the ? */ - for(ptr=url; *ptr; ptr++) { + for(ptr=(unsigned char *)url; *ptr; ptr++) { switch(*ptr) { case '?': left=FALSE; /* fall through */ default: + if(*ptr >= 0x80) + newlen += 2; newlen++; break; case ' ': @@ -1414,9 +1455,9 @@ static void strcpy_url(char *output, const char *url) { /* we must add this with whitespace-replacing */ bool left=TRUE; - const char *iptr; + const unsigned char *iptr; char *optr = output; - for(iptr = url; /* read from here */ + for(iptr = (unsigned char *)url; /* read from here */ *iptr; /* until zero byte */ iptr++) { switch(*iptr) { @@ -1424,7 +1465,12 @@ static void strcpy_url(char *output, const char *url) left=FALSE; /* fall through */ default: - *optr++=*iptr; + if(*iptr >= 0x80) { + snprintf(optr, 4, "%%%02x", *iptr); + optr += 3; + } + else + *optr++=*iptr; break; case ' ': if(left) { @@ -1614,7 +1660,7 @@ static char *concat_url(const char *base, const char *relurl) * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string * as given by the remote server and set up the new URL to request. */ -CURLcode Curl_follow(struct SessionHandle *data, +CURLcode Curl_follow(struct Curl_easy *data, char *newurl, /* this 'newurl' is the Location: string, and it must be malloc()ed before passed here */ @@ -1672,23 +1718,21 @@ CURLcode Curl_follow(struct SessionHandle *data, newurl = absolute; } else { + /* The new URL MAY contain space or high byte values, that means a mighty + stupid redirect URL but we still make an effort to do "right". */ + char *newest; + size_t newlen = strlen_url(newurl); + /* This is an absolute URL, don't allow the custom port number */ disallowport = TRUE; - if(strchr(newurl, ' ')) { - /* This new URL contains at least one space, this is a mighty stupid - redirect but we still make an effort to do "right". */ - char *newest; - size_t newlen = strlen_url(newurl); - - newest = malloc(newlen+1); /* get memory for this */ - if(!newest) - return CURLE_OUT_OF_MEMORY; - strcpy_url(newest, newurl); /* create a space-free URL */ + newest = malloc(newlen+1); /* get memory for this */ + if(!newest) + return CURLE_OUT_OF_MEMORY; + strcpy_url(newest, newurl); /* create a space-free URL */ - free(newurl); /* that was no good */ - newurl = newest; /* use this instead now */ - } + free(newurl); /* that was no good */ + newurl = newest; /* use this instead now */ } @@ -1814,70 +1858,13 @@ CURLcode Curl_follow(struct SessionHandle *data, #endif /* CURL_DISABLE_HTTP */ } -CURLcode -Curl_reconnect_request(struct connectdata **connp) -{ - CURLcode result = CURLE_OK; - struct connectdata *conn = *connp; - struct SessionHandle *data = conn->data; - - /* This was a re-use of a connection and we got a write error in the - * DO-phase. Then we DISCONNECT this connection and have another attempt to - * CONNECT and then DO again! The retry cannot possibly find another - * connection to re-use, since we only keep one possible connection for - * each. */ - - infof(data, "Re-used connection seems dead, get a new one\n"); - - connclose(conn, "Reconnect dead connection"); /* enforce close */ - result = Curl_done(&conn, result, FALSE); /* we are so done with this */ - - /* conn may no longer be a good pointer, clear it to avoid mistakes by - parent functions */ - *connp = NULL; - - /* - * According to bug report #1330310. We need to check for CURLE_SEND_ERROR - * here as well. I figure this could happen when the request failed on a FTP - * connection and thus Curl_done() itself tried to use the connection - * (again). Slight Lack of feedback in the report, but I don't think this - * extra check can do much harm. - */ - if(!result || (CURLE_SEND_ERROR == result)) { - bool async; - bool protocol_done = TRUE; - - /* Now, redo the connect and get a new connection */ - result = Curl_connect(data, connp, &async, &protocol_done); - if(!result) { - /* We have connected or sent away a name resolve query fine */ - - conn = *connp; /* setup conn to again point to something nice */ - if(async) { - /* Now, if async is TRUE here, we need to wait for the name - to resolve */ - result = Curl_resolver_wait_resolv(conn, NULL); - if(result) - return result; - - /* Resolved, continue with the connection */ - result = Curl_async_resolved(conn, &protocol_done); - if(result) - return result; - } - } - } - - return result; -} - /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted. NOTE: that the *url is malloc()ed. */ CURLcode Curl_retry_request(struct connectdata *conn, char **url) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; *url = NULL; @@ -1933,7 +1920,7 @@ Curl_setup_transfer( curl_off_t *writecountp /* return number of bytes written or NULL */ ) { - struct SessionHandle *data; + struct Curl_easy *data; struct SingleRequest *k; DEBUGASSERT(conn != NULL); diff --git a/Utilities/cmcurl/lib/transfer.h b/Utilities/cmcurl/lib/transfer.h index 316aeae..0e253e3 100644 --- a/Utilities/cmcurl/lib/transfer.h +++ b/Utilities/cmcurl/lib/transfer.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,9 +22,11 @@ * ***************************************************************************/ -CURLcode Curl_pretransfer(struct SessionHandle *data); +void Curl_init_CONNECT(struct Curl_easy *data); + +CURLcode Curl_pretransfer(struct Curl_easy *data); CURLcode Curl_second_connect(struct connectdata *conn); -CURLcode Curl_posttransfer(struct SessionHandle *data); +CURLcode Curl_posttransfer(struct Curl_easy *data); typedef enum { FOLLOW_NONE, /* not used within the function, just a placeholder to @@ -36,20 +38,19 @@ typedef enum { FOLLOW_LAST /* never used */ } followtype; -CURLcode Curl_follow(struct SessionHandle *data, char *newurl, +CURLcode Curl_follow(struct Curl_easy *data, char *newurl, followtype type); CURLcode Curl_readwrite(struct connectdata *conn, - struct SessionHandle *data, bool *done); + struct Curl_easy *data, bool *done); int Curl_single_getsock(const struct connectdata *conn, curl_socket_t *socks, int numsocks); CURLcode Curl_readrewind(struct connectdata *conn); CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp); -CURLcode Curl_reconnect_request(struct connectdata **connp); CURLcode Curl_retry_request(struct connectdata *conn, char **url); -bool Curl_meets_timecondition(struct SessionHandle *data, time_t timeofdoc); +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc); /* This sets up a forthcoming transfer */ void diff --git a/Utilities/cmcurl/lib/url.c b/Utilities/cmcurl/lib/url.c index 406c1f0..e547e5c 100644 --- a/Utilities/cmcurl/lib/url.c +++ b/Utilities/cmcurl/lib/url.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -75,7 +75,7 @@ void idn_free (void *ptr); #endif #elif defined(USE_WIN32_IDN) /* prototype for curl_win32_idn_to_ascii() */ -int curl_win32_idn_to_ascii(const char *in, char **out); +bool curl_win32_idn_to_ascii(const char *in, char **out); #endif /* USE_LIBIDN */ #include "urldata.h" @@ -111,6 +111,7 @@ int curl_win32_idn_to_ascii(const char *in, char **out); #include "telnet.h" #include "tftp.h" #include "http.h" +#include "http2.h" #include "file.h" #include "curl_ldap.h" #include "ssh.h" @@ -118,7 +119,7 @@ int curl_win32_idn_to_ascii(const char *in, char **out); #include "url.h" #include "connect.h" #include "inet_ntop.h" -#include "curl_ntlm.h" +#include "http_ntlm.h" #include "curl_ntlm_wb.h" #include "socks.h" #include "curl_rtmp.h" @@ -129,26 +130,27 @@ int curl_win32_idn_to_ascii(const char *in, char **out); #include "pipeline.h" #include "dotdot.h" #include "strdup.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" /* Local static prototypes */ static struct connectdata * -find_oldest_idle_connection(struct SessionHandle *data); -static struct connectdata * -find_oldest_idle_connection_in_bundle(struct SessionHandle *data, +find_oldest_idle_connection_in_bundle(struct Curl_easy *data, struct connectbundle *bundle); static void conn_free(struct connectdata *conn); +static void free_fixed_hostname(struct hostname *host); static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke); -static CURLcode parse_url_login(struct SessionHandle *data, +static CURLcode parse_url_login(struct Curl_easy *data, struct connectdata *conn, char **userptr, char **passwdptr, char **optionsptr); static CURLcode parse_login_details(const char *login, const size_t len, char **userptr, char **passwdptr, char **optionsptr); +static unsigned int get_protocol_family(unsigned int protocol); + /* * Protocol table. */ @@ -275,7 +277,7 @@ static const struct Curl_handler Curl_handler_dummy = { PROTOPT_NONE /* flags */ }; -void Curl_freeset(struct SessionHandle *data) +void Curl_freeset(struct Curl_easy *data) { /* Free all dynamic strings stored in the data->set substructure. */ enum dupstring i; @@ -295,7 +297,7 @@ void Curl_freeset(struct SessionHandle *data) data->change.url = NULL; } -static CURLcode setstropt(char **charp, char *s) +static CURLcode setstropt(char **charp, const char *s) { /* Release the previous storage at `charp' and replace by a dynamic storage copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */ @@ -303,12 +305,12 @@ static CURLcode setstropt(char **charp, char *s) Curl_safefree(*charp); if(s) { - s = strdup(s); + char *str = strdup(s); - if(!s) + if(!str) return CURLE_OUT_OF_MEMORY; - *charp = s; + *charp = str; } return CURLE_OK; @@ -353,7 +355,7 @@ static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp) return result; } -CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src) +CURLcode Curl_dupset(struct Curl_easy *dst, struct Curl_easy *src) { CURLcode result = CURLE_OK; enum dupstring i; @@ -396,7 +398,7 @@ CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src) * when curl_easy_perform() is invoked. */ -CURLcode Curl_close(struct SessionHandle *data) +CURLcode Curl_close(struct Curl_easy *data) { struct Curl_multi *m; @@ -482,28 +484,34 @@ CURLcode Curl_close(struct SessionHandle *data) Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } + if(data->set.wildcardmatch) { + /* destruct wildcard structures if it is needed */ + struct WildcardData *wc = &data->wildcard; + Curl_wildcard_dtor(wc); + } + Curl_freeset(data); free(data); return CURLE_OK; } /* - * Initialize the UserDefined fields within a SessionHandle. - * This may be safely called on a new or existing SessionHandle. + * Initialize the UserDefined fields within a Curl_easy. + * This may be safely called on a new or existing Curl_easy. */ CURLcode Curl_init_userdefined(struct UserDefined *set) { CURLcode result = CURLE_OK; set->out = stdout; /* default output to stdout */ - set->in = stdin; /* default input from stdin */ + set->in_set = stdin; /* default input from stdin */ set->err = stderr; /* default stderr to stderr */ /* use fwrite as default function to store output */ set->fwrite_func = (curl_write_callback)fwrite; /* use fread as default function to read input */ - set->fread_func = (curl_read_callback)fread; + set->fread_func_set = (curl_read_callback)fread; set->is_fread_set = 0; set->is_fwrite_set = 0; @@ -569,33 +577,16 @@ CURLcode Curl_init_userdefined(struct UserDefined *set) * seem not to follow rfc1961 section 4.3/4.4 */ set->socks5_gssapi_nec = FALSE; - /* set default GSS-API service name */ - result = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE], - (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE); - if(result) - return result; - - /* set default negotiate proxy service name */ - result = setstropt(&set->str[STRING_PROXY_SERVICE_NAME], - (char *) CURL_DEFAULT_PROXY_SERVICE_NAME); - if(result) - return result; - - /* set default negotiate service name */ - result = setstropt(&set->str[STRING_SERVICE_NAME], - (char *) CURL_DEFAULT_SERVICE_NAME); - if(result) - return result; #endif /* This is our preferred CA cert bundle/path since install time */ #if defined(CURL_CA_BUNDLE) - result = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE); + result = setstropt(&set->str[STRING_SSL_CAFILE], CURL_CA_BUNDLE); if(result) return result; #endif #if defined(CURL_CA_PATH) - result = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH); + result = setstropt(&set->str[STRING_SSL_CAPATH], CURL_CA_PATH); if(result) return result; #endif @@ -610,12 +601,15 @@ CURLcode Curl_init_userdefined(struct UserDefined *set) set->tcp_keepalive = FALSE; set->tcp_keepintvl = 60; set->tcp_keepidle = 60; + set->tcp_fastopen = FALSE; set->ssl_enable_npn = TRUE; set->ssl_enable_alpn = TRUE; set->expect_100_timeout = 1000L; /* Wait for a second by default. */ set->sep_headers = TRUE; /* separated header lists by default */ + + Curl_http2_init_userset(set); return result; } @@ -627,16 +621,16 @@ CURLcode Curl_init_userdefined(struct UserDefined *set) * @return CURLcode */ -CURLcode Curl_open(struct SessionHandle **curl) +CURLcode Curl_open(struct Curl_easy **curl) { CURLcode result; - struct SessionHandle *data; + struct Curl_easy *data; /* Very simple start-up: alloc the struct, init it with zeroes and return */ - data = calloc(1, sizeof(struct SessionHandle)); + data = calloc(1, sizeof(struct Curl_easy)); if(!data) { /* this is a very serious error */ - DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n")); + DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n")); return CURLE_OUT_OF_MEMORY; } @@ -673,6 +667,8 @@ CURLcode Curl_open(struct SessionHandle **curl) data->wildcard.filelist = NULL; data->set.fnmatch = ZERO_NULL; data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */ + + Curl_http2_init_state(&data->state); } if(result) { @@ -688,7 +684,7 @@ CURLcode Curl_open(struct SessionHandle **curl) return result; } -CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, +CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option, va_list param) { char *argptr; @@ -705,7 +701,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, case CURLOPT_DNS_USE_GLOBAL_CACHE: /* remember we want this enabled */ arg = va_arg(param, long); - data->set.global_dns_cache = (0 != arg)?TRUE:FALSE; + data->set.global_dns_cache = (0 != arg) ? TRUE : FALSE; break; case CURLOPT_SSL_CIPHER_LIST: /* set a list of cipher we want to use in the SSL connection */ @@ -740,33 +736,33 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * When this transfer is done, it must not be left to be reused by a * subsequent transfer but shall be closed immediately. */ - data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.reuse_forbid = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FRESH_CONNECT: /* * This transfer shall not use a previously cached connection but * should be made with a fresh new connect! */ - data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.reuse_fresh = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_VERBOSE: /* * Verbose means infof() calls that give a lot of information about * the connection and transfer procedures as well as internal choices. */ - data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.verbose = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_HEADER: /* * Set to include the header in the general data output stream. */ - data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.include_header = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_NOPROGRESS: /* * Shut off the internal supported progress meter */ - data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.hide_progress = (0 != va_arg(param, long)) ? TRUE : FALSE; if(data->set.hide_progress) data->progress.flags |= PGRS_HIDE; else @@ -776,14 +772,14 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * Do not include the body part in the output data stream. */ - data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.opt_no_body = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FAILONERROR: /* * Don't output the >=400 error code HTML-page, but instead only * return error. */ - data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_UPLOAD: case CURLOPT_PUT: @@ -791,7 +787,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * We want to sent data to the remote host. If this is HTTP, that equals * using the PUT request. */ - data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.upload = (0 != va_arg(param, long)) ? TRUE : FALSE; if(data->set.upload) { /* If this is HTTP, PUT is what's needed to "upload" */ data->set.httpreq = HTTPREQ_PUT; @@ -807,7 +803,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * Try to get the file time of the remote document. The time will * later (possibly) become available using curl_easy_getinfo(). */ - data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.get_filetime = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_CREATE_MISSING_DIRS: /* @@ -835,11 +831,18 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * Option that specifies how quickly an server response must be obtained * before it is considered failure. For pingpong protocols. */ - data->set.server_response_timeout = va_arg( param , long ) * 1000; + data->set.server_response_timeout = va_arg(param, long) * 1000; + break; + case CURLOPT_TFTP_NO_OPTIONS: + /* + * Option that prevents libcurl from sending TFTP option requests to the + * server. + */ + data->set.tftp_no_options = va_arg(param, long) != 0; break; case CURLOPT_TFTP_BLKSIZE: /* - * TFTP option that specifies the block size to use for data transmission + * TFTP option that specifies the block size to use for data transmission. */ data->set.tftp_blksize = va_arg(param, long); break; @@ -848,13 +851,13 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * An option that changes the command to one that asks for a list * only, no file info details. */ - data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ftp_list_only = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_APPEND: /* * We want to upload and append to an existing file. */ - data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ftp_append = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_FILEMETHOD: /* @@ -882,7 +885,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * * Transfer using ASCII (instead of BINARY). */ - data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.prefer_ascii = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_TIMECONDITION: /* @@ -915,7 +918,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * Switch on automatic referer that gets set if curl follows locations. */ - data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.http_auto_referer = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_ACCEPT_ENCODING: @@ -931,18 +934,19 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, argptr = va_arg(param, char *); result = setstropt(&data->set.str[STRING_ENCODING], (argptr && !*argptr)? - (char *) ALL_CONTENT_ENCODINGS: argptr); + ALL_CONTENT_ENCODINGS: argptr); break; case CURLOPT_TRANSFER_ENCODING: - data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.http_transfer_encoding = (0 != va_arg(param, long)) ? + TRUE : FALSE; break; case CURLOPT_FOLLOWLOCATION: /* * Follow Location: header hints on a HTTP-server. */ - data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.http_follow_location = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_UNRESTRICTED_AUTH: @@ -951,7 +955,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * hostname changed. */ data->set.http_disable_hostname_check_before_authentication = - (0 != va_arg(param, long))?TRUE:FALSE; + (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_MAXREDIRS: @@ -1212,7 +1216,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * We run mostly with the original cookie spec, as hardly anyone implements * anything else. */ - data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.cookiesession = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_COOKIELIST: @@ -1289,7 +1293,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, */ arg = va_arg(param, long); #ifndef USE_NGHTTP2 - if(arg == CURL_HTTP_VERSION_2_0) + if(arg >= CURL_HTTP_VERSION_2) return CURLE_UNSUPPORTED_PROTOCOL; #endif data->set.httpversion = arg; @@ -1311,7 +1315,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ - data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE; + data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE; if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ @@ -1374,7 +1378,8 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * Tunnel operations through the proxy instead of normal proxy use */ - data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)) ? + TRUE : FALSE; break; case CURLOPT_PROXYPORT: @@ -1400,7 +1405,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ - data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE; + data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE; if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ @@ -1475,32 +1480,28 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, #endif /* CURL_DISABLE_PROXY */ #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) - case CURLOPT_SOCKS5_GSSAPI_SERVICE: + case CURLOPT_SOCKS5_GSSAPI_NEC: /* - * Set GSS-API service name + * Set flag for NEC SOCK5 support */ - result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE], - va_arg(param, char *)); + data->set.socks5_gssapi_nec = (0 != va_arg(param, long)) ? TRUE : FALSE; break; + case CURLOPT_SOCKS5_GSSAPI_SERVICE: case CURLOPT_PROXY_SERVICE_NAME: /* - * Set negotiate proxy service name + * Set proxy authentication service name for Kerberos 5 and SPNEGO */ result = setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME], va_arg(param, char *)); break; +#endif - case CURLOPT_SOCKS5_GSSAPI_NEC: - /* - * set flag for nec socks5 support - */ - data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE; - break; - +#if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \ + defined(USE_SPNEGO) case CURLOPT_SERVICE_NAME: /* - * Set negotiate service identity + * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO */ result = setstropt(&data->set.str[STRING_SERVICE_NAME], va_arg(param, char *)); @@ -1534,20 +1535,19 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, */ result = setstropt(&data->set.str[STRING_FTPPORT], va_arg(param, char *)); - data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ? - TRUE:FALSE; + data->set.ftp_use_port = (data->set.str[STRING_FTPPORT]) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_EPRT: - data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ftp_use_eprt = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_EPSV: - data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ftp_use_epsv = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_PRET: - data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ftp_use_pret = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_SSL_CCC: @@ -1559,7 +1559,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the * bypass of the IP address in PASV responses. */ - data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ftp_skip_ip = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_READDATA: @@ -1567,7 +1567,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * FILE pointer to read the file to be uploaded from. Or possibly * used as argument to the read callback. */ - data->set.in = va_arg(param, void *); + data->set.in_set = va_arg(param, void *); break; case CURLOPT_INFILESIZE: /* @@ -1695,7 +1695,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, case CURLOPT_XOAUTH2_BEARER: /* - * XOAUTH2 bearer token to use in the operation + * OAuth 2.0 bearer token to use in the operation */ result = setstropt(&data->set.str[STRING_BEARER], va_arg(param, char *)); @@ -1862,11 +1862,11 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * Read data callback */ - data->set.fread_func = va_arg(param, curl_read_callback); - if(!data->set.fread_func) { + data->set.fread_func_set = va_arg(param, curl_read_callback); + if(!data->set.fread_func_set) { data->set.is_fread_set = 0; /* When set to NULL, reset to our internal default function */ - data->set.fread_func = (curl_read_callback)fread; + data->set.fread_func_set = (curl_read_callback)fread; } else data->set.is_fread_set = 1; @@ -1967,7 +1967,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * Kludgy option to enable CRLF conversions. Subject for removal. */ - data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.crlf = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_INTERFACE: @@ -1996,7 +1996,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, */ result = setstropt(&data->set.str[STRING_KRB_LEVEL], va_arg(param, char *)); - data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE; + data->set.krb = (data->set.str[STRING_KRB_LEVEL]) ? TRUE : FALSE; break; case CURLOPT_GSSAPI_DELEGATION: /* @@ -2008,7 +2008,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * Enable peer SSL verifying. */ - data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl.verifypeer = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SSL_VERIFYHOST: /* @@ -2026,7 +2026,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, return CURLE_BAD_FUNCTION_ARGUMENT; } - data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE; + data->set.ssl.verifyhost = (0 != arg) ? TRUE : FALSE; break; case CURLOPT_SSL_VERIFYSTATUS: /* @@ -2037,7 +2037,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, break; } - data->set.ssl.verifystatus = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl.verifystatus = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SSL_CTX_FUNCTION: #ifdef have_curlssl_ssl_ctx @@ -2068,22 +2068,26 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, break; } - data->set.ssl.falsestart = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CERTINFO: #ifdef have_curlssl_certinfo - data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE; #else result = CURLE_NOT_BUILT_IN; #endif break; case CURLOPT_PINNEDPUBLICKEY: +#ifdef have_curlssl_pinnedpubkey /* only by supported backends */ /* * Set pinned public key for SSL connection. * Specify file name of the public key in DER format. */ result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY], va_arg(param, char *)); +#else + result = CURLE_NOT_BUILT_IN; +#endif break; case CURLOPT_CAINFO: /* @@ -2135,7 +2139,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, */ data->set.buffer_size = va_arg(param, long); - if((data->set.buffer_size> (BUFSIZE -1 )) || + if((data->set.buffer_size> (BUFSIZE -1)) || (data->set.buffer_size < 1)) data->set.buffer_size = 0; /* huge internal default */ @@ -2146,7 +2150,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * The application asks not to set any signal() or alarm() handlers, * even when using a timeout. */ - data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.no_signal = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SHARE: @@ -2262,7 +2266,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, * Enable or disable TCP_NODELAY, which will disable/enable the Nagle * algorithm */ - data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.tcp_nodelay = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_ACCOUNT: @@ -2271,14 +2275,14 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, break; case CURLOPT_IGNORE_CONTENT_LENGTH: - data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ignorecl = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CONNECT_ONLY: /* * No data transfer, set up connection and let application use the socket */ - data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.connect_only = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_ALTERNATIVE_TO_USER: @@ -2331,7 +2335,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, break; case CURLOPT_SSL_SESSIONID_CACHE: - data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl.sessionid = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifdef USE_LIBSSH2 @@ -2392,14 +2396,14 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, /* * disable libcurl transfer encoding is used */ - data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE; + data->set.http_te_skip = (0 == va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_HTTP_CONTENT_DECODING: /* * raw data passed to the application when content encoding is used */ - data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE; + data->set.http_ce_skip = (0 == va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_NEW_FILE_PERMS: @@ -2441,6 +2445,12 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, data->set.redir_protocols = va_arg(param, long); break; + case CURLOPT_DEFAULT_PROTOCOL: + /* Set the protocol to use when the URL doesn't include any protocol */ + result = setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL], + va_arg(param, char *)); + break; + case CURLOPT_MAIL_FROM: /* Set the SMTP mail originator */ result = setstropt(&data->set.str[STRING_MAIL_FROM], @@ -2573,7 +2583,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, break; case CURLOPT_WILDCARDMATCH: - data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.wildcardmatch = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CHUNK_BGN_FUNCTION: data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback); @@ -2624,7 +2634,7 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, break; case CURLOPT_TCP_KEEPALIVE: - data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.tcp_keepalive = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_TCP_KEEPIDLE: data->set.tcp_keepidle = va_arg(param, long); @@ -2632,11 +2642,18 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, case CURLOPT_TCP_KEEPINTVL: data->set.tcp_keepintvl = va_arg(param, long); break; + case CURLOPT_TCP_FASTOPEN: +#if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN) + data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE; +#else + result = CURLE_NOT_BUILT_IN; +#endif + break; case CURLOPT_SSL_ENABLE_NPN: - data->set.ssl_enable_npn = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl_enable_npn = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SSL_ENABLE_ALPN: - data->set.ssl_enable_alpn = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.ssl_enable_alpn = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifdef USE_UNIX_SOCKETS @@ -2647,10 +2664,36 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, #endif case CURLOPT_PATH_AS_IS: - data->set.path_as_is = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.path_as_is = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_PIPEWAIT: - data->set.pipewait = (0 != va_arg(param, long))?TRUE:FALSE; + data->set.pipewait = (0 != va_arg(param, long)) ? TRUE : FALSE; + break; + case CURLOPT_STREAM_WEIGHT: +#ifndef USE_NGHTTP2 + return CURLE_NOT_BUILT_IN; +#else + arg = va_arg(param, long); + if((arg>=1) && (arg <= 256)) + data->set.stream_weight = (int)arg; + break; +#endif + case CURLOPT_STREAM_DEPENDS: + case CURLOPT_STREAM_DEPENDS_E: + { +#ifndef USE_NGHTTP2 + return CURLE_NOT_BUILT_IN; +#else + struct Curl_easy *dep = va_arg(param, struct Curl_easy *); + if(dep && GOOD_EASY_HANDLE(dep)) { + data->set.stream_depends_on = dep; + data->set.stream_depends_e = (option == CURLOPT_STREAM_DEPENDS_E); + } + break; +#endif + } + case CURLOPT_CONNECT_TO: + data->set.connect_to = va_arg(param, struct curl_slist *); break; default: /* unknown tag and its companion, just ignore: */ @@ -2661,6 +2704,45 @@ CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, return result; } +#ifdef USE_RECV_BEFORE_SEND_WORKAROUND +static void conn_reset_postponed_data(struct connectdata *conn, int num) +{ + struct postponed_data * const psnd = &(conn->postponed[num]); + if(psnd->buffer) { + DEBUGASSERT(psnd->allocated_size > 0); + DEBUGASSERT(psnd->recv_size <= psnd->allocated_size); + DEBUGASSERT(psnd->recv_size ? + (psnd->recv_processed < psnd->recv_size) : + (psnd->recv_processed == 0)); + DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD); + free(psnd->buffer); + psnd->buffer = NULL; + psnd->allocated_size = 0; + psnd->recv_size = 0; + psnd->recv_processed = 0; +#ifdef DEBUGBUILD + psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */ +#endif /* DEBUGBUILD */ + } + else { + DEBUGASSERT (psnd->allocated_size == 0); + DEBUGASSERT (psnd->recv_size == 0); + DEBUGASSERT (psnd->recv_processed == 0); + DEBUGASSERT (psnd->bindsock == CURL_SOCKET_BAD); + } +} + +static void conn_reset_all_postponed_data(struct connectdata *conn) +{ + conn_reset_postponed_data(conn, 0); + conn_reset_postponed_data(conn, 1); +} +#else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ +/* Use "do-nothing" macros instead of functions when workaround not used */ +#define conn_reset_postponed_data(c,n) do {} WHILE_FALSE +#define conn_reset_all_postponed_data(c) do {} WHILE_FALSE +#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ + static void conn_free(struct connectdata *conn) { if(!conn) @@ -2691,7 +2773,7 @@ static void conn_free(struct connectdata *conn) Curl_safefree(conn->user); Curl_safefree(conn->passwd); - Curl_safefree(conn->xoauth2_bearer); + Curl_safefree(conn->oauth_bearer); Curl_safefree(conn->options); Curl_safefree(conn->proxyuser); Curl_safefree(conn->proxypasswd); @@ -2707,9 +2789,12 @@ static void conn_free(struct connectdata *conn) Curl_safefree(conn->allocptr.rtsp_transport); Curl_safefree(conn->trailer); Curl_safefree(conn->host.rawalloc); /* host name buffer */ + Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */ Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */ Curl_safefree(conn->master_buffer); + conn_reset_all_postponed_data(conn); + Curl_llist_destroy(conn->send_pipe, NULL); Curl_llist_destroy(conn->recv_pipe, NULL); @@ -2727,14 +2812,14 @@ static void conn_free(struct connectdata *conn) * primary connection, like when freeing room in the connection cache or * killing of a dead old connection. * - * This function MUST NOT reset state in the SessionHandle struct if that + * This function MUST NOT reset state in the Curl_easy struct if that * isn't strictly bound to the life-time of *this* particular connection. * */ CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection) { - struct SessionHandle *data; + struct Curl_easy *data; if(!conn) return CURLE_OK; /* this is closed and fine already */ data = conn->data; @@ -2764,23 +2849,9 @@ CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection) infof(data, "Closing connection %ld\n", conn->connection_id); Curl_conncache_remove_conn(data->state.conn_cache, conn); -#if defined(USE_LIBIDN) - if(conn->host.encalloc) - idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed - with idn_free() since this was allocated - by libidn */ - if(conn->proxy.encalloc) - idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be - freed with idn_free() since this was - allocated by libidn */ -#elif defined(USE_WIN32_IDN) - free(conn->host.encalloc); /* encoded host name buffer, must be freed with - idn_free() since this was allocated by - curl_win32_idn_to_ascii */ - free(conn->proxy.encalloc); /* encoded proxy name buffer, must be freed - with idn_free() since this was allocated by - curl_win32_idn_to_ascii */ -#endif + free_fixed_hostname(&conn->host); + free_fixed_hostname(&conn->conn_to_host); + free_fixed_hostname(&conn->proxy); Curl_ssl_close(conn, FIRSTSOCKET); @@ -2817,7 +2888,7 @@ static bool SocketIsDead(curl_socket_t sock) * IsPipeliningPossible() returns TRUE if the options set would allow * pipelining/multiplexing and the connection is using a HTTP protocol. */ -static bool IsPipeliningPossible(const struct SessionHandle *handle, +static bool IsPipeliningPossible(const struct Curl_easy *handle, const struct connectdata *conn) { /* If a HTTP protocol and pipelining is enabled */ @@ -2831,25 +2902,27 @@ static bool IsPipeliningPossible(const struct SessionHandle *handle, return TRUE; if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) && - (handle->set.httpversion == CURL_HTTP_VERSION_2_0)) + (handle->set.httpversion >= CURL_HTTP_VERSION_2)) /* allows HTTP/2 */ return TRUE; } return FALSE; } -int Curl_removeHandleFromPipeline(struct SessionHandle *handle, +int Curl_removeHandleFromPipeline(struct Curl_easy *handle, struct curl_llist *pipeline) { - struct curl_llist_element *curr; + if(pipeline) { + struct curl_llist_element *curr; - curr = pipeline->head; - while(curr) { - if(curr->ptr == handle) { - Curl_llist_remove(pipeline, curr, NULL); - return 1; /* we removed a handle */ + curr = pipeline->head; + while(curr) { + if(curr->ptr == handle) { + Curl_llist_remove(pipeline, curr, NULL); + return 1; /* we removed a handle */ + } + curr = curr->next; } - curr = curr->next; } return 0; @@ -2862,18 +2935,18 @@ static void Curl_printPipeline(struct curl_llist *pipeline) curr = pipeline->head; while(curr) { - struct SessionHandle *data = (struct SessionHandle *) curr->ptr; + struct Curl_easy *data = (struct Curl_easy *) curr->ptr; infof(data, "Handle in pipeline: %s\n", data->state.path); curr = curr->next; } } #endif -static struct SessionHandle* gethandleathead(struct curl_llist *pipeline) +static struct Curl_easy* gethandleathead(struct curl_llist *pipeline) { struct curl_llist_element *curr = pipeline->head; if(curr) { - return (struct SessionHandle *) curr->ptr; + return (struct Curl_easy *) curr->ptr; } return NULL; @@ -2881,7 +2954,7 @@ static struct SessionHandle* gethandleathead(struct curl_llist *pipeline) /* remove the specified connection from all (possible) pipelines and related queues */ -void Curl_getoff_all_pipelines(struct SessionHandle *data, +void Curl_getoff_all_pipelines(struct Curl_easy *data, struct connectdata *conn) { bool recv_head = (conn->readchannel_inuse && @@ -2905,7 +2978,7 @@ static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke) curr = pipeline->head; while(curr) { struct curl_llist_element *next = curr->next; - struct SessionHandle *data = (struct SessionHandle *) curr->ptr; + struct Curl_easy *data = (struct Curl_easy *) curr->ptr; #ifdef DEBUGBUILD /* debug-only code */ if(data->magic != CURLEASY_MAGIC_NUMBER) { @@ -2929,8 +3002,8 @@ static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke) * Returns the pointer to the oldest idle connection, or NULL if none was * found. */ -static struct connectdata * -find_oldest_idle_connection(struct SessionHandle *data) +struct connectdata * +Curl_oldest_idle_connection(struct Curl_easy *data) { struct conncache *bc = data->state.conn_cache; struct curl_hash_iterator iter; @@ -2982,7 +3055,7 @@ find_oldest_idle_connection(struct SessionHandle *data) * found. */ static struct connectdata * -find_oldest_idle_connection_in_bundle(struct SessionHandle *data, +find_oldest_idle_connection_in_bundle(struct Curl_easy *data, struct connectbundle *bundle) { struct curl_llist_element *curr; @@ -3022,7 +3095,7 @@ find_oldest_idle_connection_in_bundle(struct SessionHandle *data, * Returns TRUE if the connection actually was dead and disconnected. */ static bool disconnect_if_dead(struct connectdata *conn, - struct SessionHandle *data) + struct Curl_easy *data) { size_t pipeLen = conn->send_pipe->size + conn->recv_pipe->size; if(!pipeLen && !conn->inuse) { @@ -3056,7 +3129,7 @@ static bool disconnect_if_dead(struct connectdata *conn, static int call_disconnect_if_dead(struct connectdata *conn, void *param) { - struct SessionHandle* data = (struct SessionHandle*)param; + struct Curl_easy* data = (struct Curl_easy*)param; disconnect_if_dead(conn, data); return 0; /* continue iteration */ } @@ -3066,7 +3139,7 @@ static int call_disconnect_if_dead(struct connectdata *conn, * closes and removes them. * The cleanup is done at most once per second. */ -static void prune_dead_connections(struct SessionHandle *data) +static void prune_dead_connections(struct Curl_easy *data) { struct timeval now = Curl_tvnow(); long elapsed = Curl_tvdiff(now, data->state.conn_cache->last_cleanup); @@ -3098,7 +3171,7 @@ static size_t max_pipeline_length(struct Curl_multi *multi) * the pipelining strategy wants to open a new connection instead of reusing. */ static bool -ConnectionExists(struct SessionHandle *data, +ConnectionExists(struct Curl_easy *data, struct connectdata *needle, struct connectdata **usethis, bool *force_reuse, @@ -3106,13 +3179,19 @@ ConnectionExists(struct SessionHandle *data, { struct connectdata *check; struct connectdata *chosen = 0; + bool foundPendingCandidate = FALSE; bool canPipeline = IsPipeliningPossible(data, needle); + struct connectbundle *bundle; + #ifdef USE_NTLM - bool wantNTLMhttp = ((data->state.authhost.want & CURLAUTH_NTLM) || - (data->state.authhost.want & CURLAUTH_NTLM_WB)) && - (needle->handler->protocol & PROTO_FAMILY_HTTP) ? TRUE : FALSE; + bool wantNTLMhttp = ((data->state.authhost.want & + (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && + (needle->handler->protocol & PROTO_FAMILY_HTTP)); + bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd && + ((data->state.authproxy.want & + (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && + (needle->handler->protocol & PROTO_FAMILY_HTTP))); #endif - struct connectbundle *bundle; *force_reuse = FALSE; *waitpipe = FALSE; @@ -3131,9 +3210,19 @@ ConnectionExists(struct SessionHandle *data, max_pipeline_length(data->multi):0; size_t best_pipe_len = max_pipe_len; struct curl_llist_element *curr; + const char *hostname; - infof(data, "Found bundle for host %s: %p\n", - needle->host.name, (void *)bundle); + if(needle->bits.conn_to_host) + hostname = needle->conn_to_host.name; + else + hostname = needle->host.name; + + infof(data, "Found bundle for host %s: %p [%s]\n", + hostname, (void *)bundle, + (bundle->multiuse== BUNDLE_PIPELINING? + "can pipeline": + (bundle->multiuse== BUNDLE_MULTIPLEX? + "can multiplex":"serially"))); /* We can't pipe if we don't know anything about the server */ if(canPipeline) { @@ -3147,19 +3236,27 @@ ConnectionExists(struct SessionHandle *data, infof(data, "Server doesn't support multi-use (yet)\n"); canPipeline = FALSE; } + if((bundle->multiuse == BUNDLE_PIPELINING) && + !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) { + /* not asked for, switch off */ + infof(data, "Could pipeline, but not asked to!\n"); + canPipeline = FALSE; + } + else if((bundle->multiuse == BUNDLE_MULTIPLEX) && + !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) { + infof(data, "Could multiplex, but not asked to!\n"); + canPipeline = FALSE; + } } curr = bundle->conn_list->head; while(curr) { bool match = FALSE; -#if defined(USE_NTLM) - bool credentialsMatch = FALSE; -#endif size_t pipeLen; /* - * Note that if we use a HTTP proxy, we check connections to that - * proxy and not to the actual remote server. + * Note that if we use a HTTP proxy in normal mode (no tunneling), we + * check connections to that proxy and not to the actual remote server. */ check = curr->ptr; curr = curr->next; @@ -3173,8 +3270,8 @@ ConnectionExists(struct SessionHandle *data, if(!check->bits.multiplex) { /* If not multiplexing, make sure the pipe has only GET requests */ - struct SessionHandle* sh = gethandleathead(check->send_pipe); - struct SessionHandle* rh = gethandleathead(check->recv_pipe); + struct Curl_easy* sh = gethandleathead(check->send_pipe); + struct Curl_easy* rh = gethandleathead(check->recv_pipe); if(sh) { if(!IsPipeliningPossible(sh, check)) continue; @@ -3205,6 +3302,8 @@ ConnectionExists(struct SessionHandle *data, if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) || check->bits.close) { + if(!check->bits.close) + foundPendingCandidate = TRUE; /* Don't pick a connection that hasn't connected yet or that is going to get closed. */ infof(data, "Connection #%ld isn't open enough, can't reuse\n", @@ -3223,7 +3322,8 @@ ConnectionExists(struct SessionHandle *data, if((needle->handler->flags&PROTOPT_SSL) != (check->handler->flags&PROTOPT_SSL)) /* don't do mixed SSL and non-SSL connections */ - if(!(needle->handler->protocol & check->handler->protocol)) + if(get_protocol_family(check->handler->protocol) != + needle->handler->protocol || !check->tls_upgraded) /* except protocols that have been upgraded via TLS */ continue; @@ -3237,6 +3337,25 @@ ConnectionExists(struct SessionHandle *data, /* don't do mixed proxy and non-proxy connections */ continue; + if(needle->bits.proxy && + (needle->proxytype != check->proxytype || + needle->bits.httpproxy != check->bits.httpproxy || + needle->bits.tunnel_proxy != check->bits.tunnel_proxy || + !Curl_raw_equal(needle->proxy.name, check->proxy.name) || + needle->port != check->port)) + /* don't mix connections that use different proxies */ + continue; + + if(needle->bits.conn_to_host != check->bits.conn_to_host) + /* don't mix connections that use the "connect to host" feature and + * connections that don't use this feature */ + continue; + + if(needle->bits.conn_to_port != check->bits.conn_to_port) + /* don't mix connections that use the "connect to port" feature and + * connections that don't use this feature */ + continue; + if(!canPipeline && check->inuse) /* this request can't be pipelined but the checked connection is already in use so we skip it */ @@ -3262,37 +3381,33 @@ ConnectionExists(struct SessionHandle *data, continue; } - if((!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) -#ifdef USE_NTLM - || (wantNTLMhttp || check->ntlm.state != NTLMSTATE_NONE) -#endif - ) { - /* This protocol requires credentials per connection or is HTTP+NTLM, + if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) { + /* This protocol requires credentials per connection, so verify that we're using the same name and password as well */ if(!strequal(needle->user, check->user) || !strequal(needle->passwd, check->passwd)) { /* one of them was different */ continue; } -#if defined(USE_NTLM) - credentialsMatch = TRUE; -#endif } - if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL || - (needle->bits.httpproxy && check->bits.httpproxy && - needle->bits.tunnel_proxy && check->bits.tunnel_proxy && - Curl_raw_equal(needle->proxy.name, check->proxy.name) && - (needle->port == check->port))) { + if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) || + (needle->bits.httpproxy && needle->bits.tunnel_proxy)) { /* The requested connection does not use a HTTP proxy or it uses SSL or - it is a non-SSL protocol tunneled over the same http proxy name and - port number or it is a non-SSL protocol which is allowed to be - upgraded via TLS */ - + it is a non-SSL protocol tunneled over the same HTTP proxy name and + port number */ if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) || - needle->handler->protocol & check->handler->protocol) && + (get_protocol_family(check->handler->protocol) == + needle->handler->protocol && check->tls_upgraded)) && + (!needle->bits.conn_to_host || Curl_raw_equal( + needle->conn_to_host.name, check->conn_to_host.name)) && + (!needle->bits.conn_to_port || + needle->conn_to_port == check->conn_to_port) && Curl_raw_equal(needle->host.name, check->host.name) && needle->remote_port == check->remote_port) { + /* The schemes match or the the protocol family is the same and the + previous connection was TLS upgraded, and the hostname and host + port match */ if(needle->handler->flags & PROTOPT_SSL) { /* This is a SSL connection so verify that we're using the same SSL options as well */ @@ -3305,6 +3420,7 @@ ConnectionExists(struct SessionHandle *data, continue; } else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) { + foundPendingCandidate = TRUE; DEBUGF(infof(data, "Connection #%ld has not started SSL connect, " "can't reuse\n", @@ -3315,16 +3431,10 @@ ConnectionExists(struct SessionHandle *data, match = TRUE; } } - else { /* The requested needle connection is using a proxy, - is the checked one using the same host, port and type? */ - if(check->bits.proxy && - (needle->proxytype == check->proxytype) && - (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) && - Curl_raw_equal(needle->proxy.name, check->proxy.name) && - needle->port == check->port) { - /* This is the same proxy connection, use it! */ - match = TRUE; - } + else { + /* The requested connection is using the same HTTP proxy in normal + mode (no tunneling) */ + match = TRUE; } if(match) { @@ -3335,20 +3445,47 @@ ConnectionExists(struct SessionHandle *data, possible. (Especially we must not reuse the same connection if partway through a handshake!) */ if(wantNTLMhttp) { - if(credentialsMatch && check->ntlm.state != NTLMSTATE_NONE) { - chosen = check; + if(!strequal(needle->user, check->user) || + !strequal(needle->passwd, check->passwd)) + continue; + } + else if(check->ntlm.state != NTLMSTATE_NONE) { + /* Connection is using NTLM auth but we don't want NTLM */ + continue; + } + + /* Same for Proxy NTLM authentication */ + if(wantProxyNTLMhttp) { + /* Both check->proxyuser and check->proxypasswd can be NULL */ + if(!check->proxyuser || !check->proxypasswd) + continue; + if(!strequal(needle->proxyuser, check->proxyuser) || + !strequal(needle->proxypasswd, check->proxypasswd)) + continue; + } + else if(check->proxyntlm.state != NTLMSTATE_NONE) { + /* Proxy connection is using NTLM auth but we don't want NTLM */ + continue; + } + + if(wantNTLMhttp || wantProxyNTLMhttp) { + /* Credentials are already checked, we can use this connection */ + chosen = check; + + if((wantNTLMhttp && + (check->ntlm.state != NTLMSTATE_NONE)) || + (wantProxyNTLMhttp && + (check->proxyntlm.state != NTLMSTATE_NONE))) { /* We must use this connection, no other */ *force_reuse = TRUE; break; } - else if(credentialsMatch) - /* this is a backup choice */ - chosen = check; + + /* Continue look up for a better connection */ continue; } #endif - if(canPipeline) { /* We can pipeline if we want to. Let's continue looking for the optimal connection to use, i.e the shortest pipe that is not @@ -3413,39 +3550,13 @@ ConnectionExists(struct SessionHandle *data, return TRUE; /* yes, we found one to use! */ } - return FALSE; /* no matching connecting exists */ -} - -/* Mark the connection as 'idle', or close it if the cache is full. - Returns TRUE if the connection is kept, or FALSE if it was closed. */ -static bool -ConnectionDone(struct SessionHandle *data, struct connectdata *conn) -{ - /* data->multi->maxconnects can be negative, deal with it. */ - size_t maxconnects = - (data->multi->maxconnects < 0) ? data->multi->num_easy * 4: - data->multi->maxconnects; - struct connectdata *conn_candidate = NULL; - - /* Mark the current connection as 'unused' */ - conn->inuse = FALSE; - - if(maxconnects > 0 && - data->state.conn_cache->num_connections > maxconnects) { - infof(data, "Connection cache is full, closing the oldest one.\n"); - - conn_candidate = find_oldest_idle_connection(data); - - if(conn_candidate) { - /* Set the connection's owner correctly */ - conn_candidate->data = data; - - /* the winner gets the honour of being disconnected */ - (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE); - } + if(foundPendingCandidate && data->set.pipewait) { + infof(data, + "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n"); + *waitpipe = TRUE; } - return (conn_candidate == conn) ? FALSE : TRUE; + return FALSE; /* no matching connecting exists */ } /* after a TCP connection to the proxy has been verified, this function does @@ -3467,16 +3578,27 @@ CURLcode Curl_connected_proxy(struct connectdata *conn, case CURLPROXY_SOCKS5: case CURLPROXY_SOCKS5_HOSTNAME: return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd, - conn->host.name, conn->remote_port, + conn->bits.conn_to_host ? conn->conn_to_host.name : + conn->host.name, + conn->bits.conn_to_port ? conn->conn_to_port : + conn->remote_port, FIRSTSOCKET, conn); case CURLPROXY_SOCKS4: - return Curl_SOCKS4(conn->proxyuser, conn->host.name, - conn->remote_port, FIRSTSOCKET, conn, FALSE); + return Curl_SOCKS4(conn->proxyuser, + conn->bits.conn_to_host ? conn->conn_to_host.name : + conn->host.name, + conn->bits.conn_to_port ? conn->conn_to_port : + conn->remote_port, + FIRSTSOCKET, conn, FALSE); case CURLPROXY_SOCKS4A: - return Curl_SOCKS4(conn->proxyuser, conn->host.name, - conn->remote_port, FIRSTSOCKET, conn, TRUE); + return Curl_SOCKS4(conn->proxyuser, + conn->bits.conn_to_host ? conn->conn_to_host.name : + conn->host.name, + conn->bits.conn_to_port ? conn->conn_to_port : + conn->remote_port, + FIRSTSOCKET, conn, TRUE); #endif /* CURL_DISABLE_PROXY */ case CURLPROXY_HTTP: @@ -3634,7 +3756,7 @@ static bool is_ASCII_name(const char *hostname) /* * Check if characters in hostname is allowed in Top Level Domain. */ -static bool tld_check_name(struct SessionHandle *data, +static bool tld_check_name(struct Curl_easy *data, const char *ace_hostname) { size_t err_pos; @@ -3651,17 +3773,16 @@ static bool tld_check_name(struct SessionHandle *data, if(rc != IDNA_SUCCESS) return FALSE; + /* Warning: err_pos receives "the decoded character offset rather than the + byte position in the string." And as of libidn 1.32 that character offset + is for UTF-8, even if the passed in string is another locale. */ rc = tld_check_lz(uc_name, &err_pos, NULL); #ifndef CURL_DISABLE_VERBOSE_STRINGS #ifdef HAVE_TLD_STRERROR if(rc != TLD_SUCCESS) tld_errmsg = tld_strerror((Tld_rc)rc); #endif - if(rc == TLD_INVALID) - infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n", - tld_errmsg, err_pos, uc_name[err_pos], - uc_name[err_pos] & 255); - else if(rc != TLD_SUCCESS) + if(rc != TLD_SUCCESS) infof(data, "WARNING: TLD check for %s failed; %s\n", uc_name, tld_errmsg); #endif /* CURL_DISABLE_VERBOSE_STRINGS */ @@ -3677,7 +3798,7 @@ static bool tld_check_name(struct SessionHandle *data, /* * Perform any necessary IDN conversion of hostname */ -static void fix_hostname(struct SessionHandle *data, +static void fix_hostname(struct Curl_easy *data, struct connectdata *conn, struct hostname *host) { size_t len; @@ -3698,49 +3819,64 @@ static void fix_hostname(struct SessionHandle *data, there's no use for it */ host->name[len-1]=0; + /* Check name for non-ASCII and convert hostname to ACE form if we can */ if(!is_ASCII_name(host->name)) { #ifdef USE_LIBIDN - /************************************************************* - * Check name for non-ASCII and convert hostname to ACE form. - *************************************************************/ - if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) { - char *ace_hostname = NULL; - int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0); - infof (data, "Input domain encoded as `%s'\n", - stringprep_locale_charset ()); - if(rc != IDNA_SUCCESS) - infof(data, "Failed to convert %s to ACE; %s\n", - host->name, Curl_idn_strerror(conn, rc)); - else { - /* tld_check_name() displays a warning if the host name contains - "illegal" characters for this TLD */ - (void)tld_check_name(data, ace_hostname); - - host->encalloc = ace_hostname; - /* change the name pointer to point to the encoded hostname */ - host->name = host->encalloc; + if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) { + char *ace_hostname = NULL; + + int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0); + infof(data, "Input domain encoded as `%s'\n", + stringprep_locale_charset()); + if(rc == IDNA_SUCCESS) { + /* tld_check_name() displays a warning if the host name contains + "illegal" characters for this TLD */ + (void)tld_check_name(data, ace_hostname); + + host->encalloc = ace_hostname; + /* change the name pointer to point to the encoded hostname */ + host->name = host->encalloc; + } + else + infof(data, "Failed to convert %s to ACE; %s\n", host->name, + Curl_idn_strerror(conn, rc)); } - } #elif defined(USE_WIN32_IDN) - /************************************************************* - * Check name for non-ASCII and convert hostname to ACE form. - *************************************************************/ char *ace_hostname = NULL; - int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname); - if(rc == 0) - infof(data, "Failed to convert %s to ACE;\n", - host->name); - else { + + if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) { host->encalloc = ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } + else + infof(data, "Failed to convert %s to ACE;\n", host->name); #else infof(data, "IDN support not present, can't parse Unicode domains\n"); #endif } } +/* + * Frees data allocated by fix_hostname() + */ +static void free_fixed_hostname(struct hostname *host) +{ +#if defined(USE_LIBIDN) + if(host->encalloc) { + idn_free(host->encalloc); /* must be freed with idn_free() since this was + allocated by libidn */ + host->encalloc = NULL; + } +#elif defined(USE_WIN32_IDN) + free(host->encalloc); /* must be freed withidn_free() since this was + allocated by curl_win32_idn_to_ascii */ + host->encalloc = NULL; +#else + (void)host; +#endif +} + static void llist_dtor(void *user, void *element) { (void)user; @@ -3751,7 +3887,7 @@ static void llist_dtor(void *user, void *element) /* * Allocate and initialize a new connectdata object. */ -static struct connectdata *allocate_conn(struct SessionHandle *data) +static struct connectdata *allocate_conn(struct Curl_easy *data) { struct connectdata *conn = calloc(1, sizeof(struct connectdata)); if(!conn) @@ -3770,6 +3906,10 @@ static struct connectdata *allocate_conn(struct SessionHandle *data) conn->connection_id = -1; /* no ID */ conn->port = -1; /* unknown at this point */ conn->remote_port = -1; /* unknown */ +#if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD) + conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */ + conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */ +#endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */ /* Default protocol-independent behavior doesn't support persistent connections, so we set this to force-close. Protocols that support @@ -3780,7 +3920,7 @@ static struct connectdata *allocate_conn(struct SessionHandle *data) conn->created = Curl_tvnow(); conn->data = data; /* Setup the association between this connection - and the SessionHandle */ + and the Curl_easy */ conn->proxytype = data->set.proxytype; /* type */ @@ -3796,17 +3936,18 @@ static struct connectdata *allocate_conn(struct SessionHandle *data) /* note that these two proxy bits are now just on what looks to be requested, they may be altered down the road */ conn->bits.proxy = (data->set.str[STRING_PROXY] && - *data->set.str[STRING_PROXY])?TRUE:FALSE; + *data->set.str[STRING_PROXY]) ? TRUE : FALSE; conn->bits.httpproxy = (conn->bits.proxy && (conn->proxytype == CURLPROXY_HTTP || - conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE; - conn->bits.proxy_user_passwd = - (NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE; + conn->proxytype == CURLPROXY_HTTP_1_0)) ? + TRUE : FALSE; + conn->bits.proxy_user_passwd = (data->set.str[STRING_PROXYUSERNAME]) ? + TRUE : FALSE; conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy; #endif /* CURL_DISABLE_PROXY */ - conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE; + conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE; conn->bits.ftp_use_epsv = data->set.ftp_use_epsv; conn->bits.ftp_use_eprt = data->set.ftp_use_eprt; @@ -3851,7 +3992,7 @@ static struct connectdata *allocate_conn(struct SessionHandle *data) conn->localport = data->set.localport; /* the close socket stuff needs to be copied to the connection struct as - it may live on without (this specific) SessionHandle */ + it may live on without (this specific) Curl_easy */ conn->fclosesocket = data->set.fclosesocket; conn->closesocket_client = data->set.closesocket_client; @@ -3870,7 +4011,7 @@ static struct connectdata *allocate_conn(struct SessionHandle *data) return NULL; } -static CURLcode findprotocol(struct SessionHandle *data, +static CURLcode findprotocol(struct Curl_easy *data, struct connectdata *conn, const char *protostr) { @@ -3915,7 +4056,7 @@ static CURLcode findprotocol(struct SessionHandle *data, /* * Parse URL and fill in the relevant members of the connection struct. */ -static CURLcode parseurlandfillconn(struct SessionHandle *data, +static CURLcode parseurlandfillconn(struct Curl_easy *data, struct connectdata *conn, bool *prot_missing, char **userp, char **passwdp, @@ -4000,12 +4141,17 @@ static CURLcode parseurlandfillconn(struct SessionHandle *data, } else { /* clear path */ + char slashbuf[4]; path[0]=0; - if(2 > sscanf(data->change.url, - "%15[^\n:]://%[^\n/?]%[^\n]", - protobuf, - conn->host.name, path)) { + rc = sscanf(data->change.url, + "%15[^\n:]:%3[/]%[^\n/?]%[^\n]", + protobuf, slashbuf, conn->host.name, path); + if(2 == rc) { + failf(data, "Bad URL"); + return CURLE_URL_MALFORMAT; + } + if(3 > rc) { /* * The URL was badly formatted, let's try the browser-style _without_ @@ -4028,33 +4174,51 @@ static CURLcode parseurlandfillconn(struct SessionHandle *data, } /* - * Since there was no protocol part specified, we guess what protocol it - * is based on the first letters of the server name. + * Since there was no protocol part specified in the URL use the + * user-specified default protocol. If we weren't given a default make a + * guess by matching some protocols against the host's outermost + * sub-domain name. Finally if there was no match use HTTP. */ - /* Note: if you add a new protocol, please update the list in - * lib/version.c too! */ - - if(checkprefix("FTP.", conn->host.name)) - protop = "ftp"; - else if(checkprefix("DICT.", conn->host.name)) - protop = "DICT"; - else if(checkprefix("LDAP.", conn->host.name)) - protop = "LDAP"; - else if(checkprefix("IMAP.", conn->host.name)) - protop = "IMAP"; - else if(checkprefix("SMTP.", conn->host.name)) - protop = "smtp"; - else if(checkprefix("POP3.", conn->host.name)) - protop = "pop3"; - else { - protop = "http"; + protop = data->set.str[STRING_DEFAULT_PROTOCOL]; + if(!protop) { + /* Note: if you add a new protocol, please update the list in + * lib/version.c too! */ + if(checkprefix("FTP.", conn->host.name)) + protop = "ftp"; + else if(checkprefix("DICT.", conn->host.name)) + protop = "DICT"; + else if(checkprefix("LDAP.", conn->host.name)) + protop = "LDAP"; + else if(checkprefix("IMAP.", conn->host.name)) + protop = "IMAP"; + else if(checkprefix("SMTP.", conn->host.name)) + protop = "smtp"; + else if(checkprefix("POP3.", conn->host.name)) + protop = "pop3"; + else + protop = "http"; } *prot_missing = TRUE; /* not given in URL */ } - else + else { + size_t s = strlen(slashbuf); protop = protobuf; + if(s != 2) { + infof(data, "Unwillingly accepted illegal URL using %d slash%s!\n", + s, s>1?"es":""); + + if(data->change.url_alloc) + free(data->change.url); + /* repair the URL to use two slashes */ + data->change.url = aprintf("%s://%s%s", + protobuf, conn->host.name, path); + if(!data->change.url) + return CURLE_OUT_OF_MEMORY; + data->change.url_alloc = TRUE; + } + } } /* We search for '?' in the host name (but only on the right side of a @@ -4260,7 +4424,7 @@ static CURLcode parseurlandfillconn(struct SessionHandle *data, * If we're doing a resumed transfer, we need to setup our stuff * properly. */ -static CURLcode setup_range(struct SessionHandle *data) +static CURLcode setup_range(struct Curl_easy *data) { struct UrlState *s = &data->state; s->resume_from = data->set.set_resume_from; @@ -4273,7 +4437,7 @@ static CURLcode setup_range(struct SessionHandle *data) else s->range = strdup(data->set.str[STRING_SET_RANGE]); - s->rangestringalloc = (s->range)?TRUE:FALSE; + s->rangestringalloc = (s->range) ? TRUE : FALSE; if(!s->range) return CURLE_OUT_OF_MEMORY; @@ -4292,7 +4456,7 @@ static CURLcode setup_range(struct SessionHandle *data) * setup_connection_internals() - * * Setup connection internals specific to the requested protocol in the - * SessionHandle. This is inited and setup before the connection is made but + * Curl_easy. This is inited and setup before the connection is made but * is about the particular protocol that is to be used. * * This MUST get called after proxy magic has been figured out. @@ -4301,7 +4465,7 @@ static CURLcode setup_connection_internals(struct connectdata *conn) { const struct Curl_handler * p; CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; /* in some case in the multi state-machine, we go back to the CONNECT state and then a second (or third or...) call to this function will be made @@ -4332,20 +4496,15 @@ static CURLcode setup_connection_internals(struct connectdata *conn) was very likely already set to the proxy port */ conn->port = p->defport; - /* only if remote_port was not already parsed off the URL we use the - default port number */ - if(conn->remote_port < 0) - conn->remote_port = (unsigned short)conn->given->defport; - return CURLE_OK; } /* * Curl_free_request_state() should free temp data that was allocated in the - * SessionHandle for this single request. + * Curl_easy for this single request. */ -void Curl_free_request_state(struct SessionHandle *data) +void Curl_free_request_state(struct Curl_easy *data) { Curl_safefree(data->req.protop); Curl_safefree(data->req.newurl); @@ -4519,7 +4678,7 @@ static char *detect_proxy(struct connectdata *conn) * host name, so that we can re-use an existing connection * that may exist registered to the same proxy host. */ -static CURLcode parse_proxy(struct SessionHandle *data, +static CURLcode parse_proxy(struct Curl_easy *data, struct connectdata *conn, char *proxy) { char *prox_portno; @@ -4611,7 +4770,7 @@ static CURLcode parse_proxy(struct SessionHandle *data, if(strncmp("%25", ptr, 3)) infof(data, "Please URL encode %% as %%25, see RFC 6874.\n"); ptr++; - /* Allow unresered characters as defined in RFC 3986 */ + /* Allow unreserved characters as defined in RFC 3986 */ while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') || (*ptr == '.') || (*ptr == '_') || (*ptr == '~'))) ptr++; @@ -4631,10 +4790,24 @@ static CURLcode parse_proxy(struct SessionHandle *data, /* Get port number off proxy.server.com:1080 */ prox_portno = strchr(portptr, ':'); if(prox_portno) { + char *endp = NULL; + long port = 0; *prox_portno = 0x0; /* cut off number from host name */ prox_portno ++; /* now set the local port number */ - conn->port = strtol(prox_portno, NULL, 10); + port = strtol(prox_portno, &endp, 10); + if((endp && *endp && (*endp != '/') && (*endp != ' ')) || + (port < 0) || (port > 65535)) { + /* meant to detect for example invalid IPv6 numerical addresses without + brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only + because we then allow "URL style" with the number followed by a + slash, used in curl test cases already. Space is also an acceptable + terminating symbol. */ + infof(data, "No valid port number in proxy string (%s)\n", + prox_portno); + } + else + conn->port = port; } else { if(proxyptr[0]=='/') @@ -4647,7 +4820,7 @@ static CURLcode parse_proxy(struct SessionHandle *data, a slash so we strip everything from the first slash */ atsign = strchr(proxyptr, '/'); if(atsign) - *atsign = 0x0; /* cut off path part from host name */ + *atsign = '\0'; /* cut off path part from host name */ if(data->set.proxyport) /* None given in the proxy string, then get the default one if it is @@ -4668,7 +4841,7 @@ static CURLcode parse_proxy(struct SessionHandle *data, /* * Extract the user and password from the authentication string */ -static CURLcode parse_proxy_auth(struct SessionHandle *data, +static CURLcode parse_proxy_auth(struct Curl_easy *data, struct connectdata *conn) { char proxyuser[MAX_CURL_USER_LENGTH]=""; @@ -4713,7 +4886,7 @@ static CURLcode parse_proxy_auth(struct SessionHandle *data, * options - non-zero length if defined * conn->host.name - remove user name and password */ -static CURLcode parse_url_login(struct SessionHandle *data, +static CURLcode parse_url_login(struct Curl_easy *data, struct connectdata *conn, char **user, char **passwd, char **options) { @@ -4952,7 +5125,7 @@ static CURLcode parse_login_details(const char *login, const size_t len, * * The port number embedded in the URL is replaced, if necessary. *************************************************************/ -static CURLcode parse_remote_port(struct SessionHandle *data, +static CURLcode parse_remote_port(struct Curl_easy *data, struct connectdata *conn) { char *portptr; @@ -5051,6 +5224,12 @@ static CURLcode parse_remote_port(struct SessionHandle *data, use the default port. Firefox and Chrome both do that. */ *portptr = '\0'; } + + /* only if remote_port was not already parsed off the URL we use the + default port number */ + if(conn->remote_port < 0) + conn->remote_port = (unsigned short)conn->given->defport; + return CURLE_OK; } @@ -5058,7 +5237,7 @@ static CURLcode parse_remote_port(struct SessionHandle *data, * Override the login details from the URL with that in the CURLOPT_USERPWD * option or a .netrc file, if applicable. */ -static CURLcode override_login(struct SessionHandle *data, +static CURLcode override_login(struct Curl_easy *data, struct connectdata *conn, char **userp, char **passwdp, char **optionsp) { @@ -5093,7 +5272,7 @@ static CURLcode override_login(struct SessionHandle *data, DOT_CHAR "netrc file; using defaults\n", conn->host.name); } - else if(ret < 0 ) { + else if(ret < 0) { return CURLE_OUT_OF_MEMORY; } else { @@ -5156,10 +5335,218 @@ static CURLcode set_login(struct connectdata *conn, return result; } +/* + * Parses a "host:port" string to connect to. + * The hostname and the port may be empty; in this case, NULL is returned for + * the hostname and -1 for the port. + */ +static CURLcode parse_connect_to_host_port(struct Curl_easy *data, + const char *host, + char **hostname_result, + int *port_result) +{ + char *host_dup; + char *hostptr; + char *host_portno; + char *portptr; + int port = -1; + + *hostname_result = NULL; + *port_result = -1; + + if(!host || !*host) + return CURLE_OK; + + host_dup = strdup(host); + if(!host_dup) + return CURLE_OUT_OF_MEMORY; + + hostptr = host_dup; + + /* start scanning for port number at this point */ + portptr = hostptr; + + /* detect and extract RFC6874-style IPv6-addresses */ + if(*hostptr == '[') { + char *ptr = ++hostptr; /* advance beyond the initial bracket */ + while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.'))) + ptr++; + if(*ptr == '%') { + /* There might be a zone identifier */ + if(strncmp("%25", ptr, 3)) + infof(data, "Please URL encode %% as %%25, see RFC 6874.\n"); + ptr++; + /* Allow unreserved characters as defined in RFC 3986 */ + while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') || + (*ptr == '.') || (*ptr == '_') || (*ptr == '~'))) + ptr++; + } + if(*ptr == ']') + /* yeps, it ended nicely with a bracket as well */ + *ptr++ = '\0'; + else + infof(data, "Invalid IPv6 address format\n"); + portptr = ptr; + /* Note that if this didn't end with a bracket, we still advanced the + * hostptr first, but I can't see anything wrong with that as no host + * name nor a numeric can legally start with a bracket. + */ + } + + /* Get port number off server.com:1080 */ + host_portno = strchr(portptr, ':'); + if(host_portno) { + char *endp = NULL; + *host_portno = '\0'; /* cut off number from host name */ + host_portno++; + if(*host_portno) { + long portparse = strtol(host_portno, &endp, 10); + if((endp && *endp) || (portparse < 0) || (portparse > 65535)) { + infof(data, "No valid port number in connect to host string (%s)\n", + host_portno); + hostptr = NULL; + port = -1; + } + else + port = (int)portparse; /* we know it will fit */ + } + } + + /* now, clone the cleaned host name */ + if(hostptr) { + *hostname_result = strdup(hostptr); + if(!*hostname_result) { + free(host_dup); + return CURLE_OUT_OF_MEMORY; + } + } + + *port_result = port; + + free(host_dup); + return CURLE_OK; +} + +/* + * Parses one "connect to" string in the form: + * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT". + */ +static CURLcode parse_connect_to_string(struct Curl_easy *data, + struct connectdata *conn, + const char *conn_to_host, + char **host_result, + int *port_result) +{ + CURLcode result = CURLE_OK; + const char *ptr = conn_to_host; + int host_match = FALSE; + int port_match = FALSE; + + if(*ptr == ':') { + /* an empty hostname always matches */ + host_match = TRUE; + ptr++; + } + else { + /* check whether the URL's hostname matches */ + size_t hostname_to_match_len; + char *hostname_to_match = aprintf("%s%s%s", + conn->bits.ipv6_ip ? "[" : "", + conn->host.name, + conn->bits.ipv6_ip ? "]" : ""); + if(!hostname_to_match) + return CURLE_OUT_OF_MEMORY; + hostname_to_match_len = strlen(hostname_to_match); + host_match = curl_strnequal(ptr, hostname_to_match, hostname_to_match_len); + free(hostname_to_match); + ptr += hostname_to_match_len; + + host_match = host_match && *ptr == ':'; + ptr++; + } + + if(host_match) { + if(*ptr == ':') { + /* an empty port always matches */ + port_match = TRUE; + ptr++; + } + else { + /* check whether the URL's port matches */ + char *ptr_next = strchr(ptr, ':'); + if(ptr_next) { + char *endp = NULL; + long port_to_match = strtol(ptr, &endp, 10); + if((endp == ptr_next) && (port_to_match == conn->remote_port)) { + port_match = TRUE; + ptr = ptr_next + 1; + } + } + } + } + + if(host_match && port_match) { + /* parse the hostname and port to connect to */ + result = parse_connect_to_host_port(data, ptr, host_result, port_result); + } + + return result; +} + +/* + * Processes all strings in the "connect to" slist, and uses the "connect + * to host" and "connect to port" of the first string that matches. + */ +static CURLcode parse_connect_to_slist(struct Curl_easy *data, + struct connectdata *conn, + struct curl_slist *conn_to_host) +{ + CURLcode result = CURLE_OK; + char *host = NULL; + int port = 0; + + while(conn_to_host && !host) { + result = parse_connect_to_string(data, conn, conn_to_host->data, + &host, &port); + if(result) + return result; + + if(host && *host) { + bool ipv6host; + conn->conn_to_host.rawalloc = host; + conn->conn_to_host.name = host; + conn->bits.conn_to_host = TRUE; + + ipv6host = strchr(host, ':') != NULL; + infof(data, "Connecting to hostname: %s%s%s\n", + ipv6host ? "[" : "", host, ipv6host ? "]" : ""); + } + else { + /* no "connect to host" */ + conn->bits.conn_to_host = FALSE; + free(host); + } + + if(port >= 0) { + conn->conn_to_port = port; + conn->bits.conn_to_port = TRUE; + infof(data, "Connecting to port: %d\n", port); + } + else { + /* no "connect to port" */ + conn->bits.conn_to_port = FALSE; + } + + conn_to_host = conn_to_host->next; + } + + return result; +} + /************************************************************* * Resolve the address of the server or proxy *************************************************************/ -static CURLcode resolve_server(struct SessionHandle *data, +static CURLcode resolve_server(struct Curl_easy *data, struct connectdata *conn, bool *async) { @@ -5180,9 +5567,6 @@ static CURLcode resolve_server(struct SessionHandle *data, int rc; struct Curl_dns_entry *hostaddr; - /* set a pointer to the hostname we display */ - fix_hostname(data, conn, &conn->host); - #ifdef USE_UNIX_SOCKETS if(data->set.str[STRING_UNIX_SOCKET_PATH]) { /* Unix domain sockets are local. The host gets ignored, just use the @@ -5210,12 +5594,21 @@ static CURLcode resolve_server(struct SessionHandle *data, else #endif if(!conn->proxy.name || !*conn->proxy.name) { + struct hostname *connhost; + if(conn->bits.conn_to_host) + connhost = &conn->conn_to_host; + else + connhost = &conn->host; + /* If not connecting via a proxy, extract the port from the URL, if it is * there, thus overriding any defaults that might have been set above. */ - conn->port = conn->remote_port; /* it is the same port */ + if(conn->bits.conn_to_port) + conn->port = conn->conn_to_port; + else + conn->port = conn->remote_port; /* it is the same port */ /* Resolve target host right on */ - rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port, + rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port, &hostaddr, timeout_ms); if(rc == CURLRESOLV_PENDING) *async = TRUE; @@ -5224,7 +5617,7 @@ static CURLcode resolve_server(struct SessionHandle *data, result = CURLE_OPERATION_TIMEDOUT; else if(!hostaddr) { - failf(data, "Couldn't resolve host '%s'", conn->host.dispname); + failf(data, "Couldn't resolve host '%s'", connhost->dispname); result = CURLE_COULDNT_RESOLVE_HOST; /* don't return yet, we need to clean up the timeout first */ } @@ -5232,9 +5625,6 @@ static CURLcode resolve_server(struct SessionHandle *data, else { /* This is a proxy that hasn't been resolved yet. */ - /* IDN-fix the proxy name */ - fix_hostname(data, conn, &conn->proxy); - /* resolve proxy */ rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port, &hostaddr, timeout_ms); @@ -5266,6 +5656,7 @@ static CURLcode resolve_server(struct SessionHandle *data, static void reuse_conn(struct connectdata *old_conn, struct connectdata *conn) { + free_fixed_hostname(&old_conn->proxy); free(old_conn->proxy.rawalloc); /* free the SSL config struct from this connection struct as this was @@ -5300,12 +5691,22 @@ static void reuse_conn(struct connectdata *old_conn, /* host can change, when doing keepalive with a proxy or if the case is different this time etc */ + free_fixed_hostname(&conn->host); + free_fixed_hostname(&conn->conn_to_host); Curl_safefree(conn->host.rawalloc); + Curl_safefree(conn->conn_to_host.rawalloc); conn->host=old_conn->host; + conn->bits.conn_to_host = old_conn->bits.conn_to_host; + conn->conn_to_host = old_conn->conn_to_host; + conn->bits.conn_to_port = old_conn->bits.conn_to_port; + conn->conn_to_port = old_conn->conn_to_port; /* persist connection info in session handle */ Curl_persistconninfo(conn); + conn_reset_all_postponed_data(old_conn); /* free buffers */ + conn_reset_all_postponed_data(conn); /* reset unprocessed data */ + /* re-use init */ conn->bits.reuse = TRUE; /* yes, we're re-using here */ @@ -5340,7 +5741,7 @@ static void reuse_conn(struct connectdata *old_conn, * *NOTE* this function assigns the conn->data pointer! */ -static CURLcode create_conn(struct SessionHandle *data, +static CURLcode create_conn(struct Curl_easy *data, struct connectdata **in_connect, bool *async) { @@ -5448,6 +5849,7 @@ static CURLcode create_conn(struct SessionHandle *data, we're gonna follow a Location: later or... then we need the protocol part added so that we have a valid URL. */ char *reurl; + char *ch_lower; reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url); @@ -5456,6 +5858,10 @@ static CURLcode create_conn(struct SessionHandle *data, goto out; } + /* Change protocol prefix to lower-case */ + for(ch_lower = reurl; *ch_lower != ':'; ch_lower++) + *ch_lower = (char)TOLOWER(*ch_lower); + if(data->change.url_alloc) { Curl_safefree(data->change.url); data->change.url_alloc = FALSE; @@ -5484,8 +5890,8 @@ static CURLcode create_conn(struct SessionHandle *data, } if(data->set.str[STRING_BEARER]) { - conn->xoauth2_bearer = strdup(data->set.str[STRING_BEARER]); - if(!conn->xoauth2_bearer) { + conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]); + if(!conn->oauth_bearer) { result = CURLE_OUT_OF_MEMORY; goto out; } @@ -5605,6 +6011,48 @@ static CURLcode create_conn(struct SessionHandle *data, goto out; /************************************************************* + * Process the "connect to" linked list of hostname/port mappings. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + result = parse_connect_to_slist(data, conn, data->set.connect_to); + if(result) + goto out; + + /************************************************************* + * IDN-fix the hostnames + *************************************************************/ + fix_hostname(data, conn, &conn->host); + if(conn->bits.conn_to_host) + fix_hostname(data, conn, &conn->conn_to_host); + if(conn->proxy.name && *conn->proxy.name) + fix_hostname(data, conn, &conn->proxy); + + /************************************************************* + * Check whether the host and the "connect to host" are equal. + * Do this after the hostnames have been IDN-fixed . + *************************************************************/ + if(conn->bits.conn_to_host && + Curl_raw_equal(conn->conn_to_host.name, conn->host.name)) { + conn->bits.conn_to_host = FALSE; + } + + /************************************************************* + * Check whether the port and the "connect to port" are equal. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) { + conn->bits.conn_to_port = FALSE; + } + + /************************************************************* + * If the "connect to" feature is used with an HTTP proxy, + * we set the tunnel_proxy bit. + *************************************************************/ + if((conn->bits.conn_to_host || conn->bits.conn_to_port) && + conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; + + /************************************************************* * Setup internals depending on protocol. Needs to be done after * we figured out what/if proxy to use. *************************************************************/ @@ -5617,6 +6065,8 @@ static CURLcode create_conn(struct SessionHandle *data, conn->recv[SECONDARYSOCKET] = Curl_recv_plain; conn->send[SECONDARYSOCKET] = Curl_send_plain; + conn->bits.tcp_fastopen = data->set.tcp_fastopen; + /*********************************************************************** * file: is a special case in that it doesn't need a network connection ***********************************************************************/ @@ -5663,7 +6113,7 @@ static CURLcode create_conn(struct SessionHandle *data, strings in the session handle strings array! Keep in mind that the pointers in the master copy are pointing to strings - that will be freed as part of the SessionHandle struct, but all cloned + that will be freed as part of the Curl_easy struct, but all cloned copies will be separately allocated. */ data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH]; @@ -5673,6 +6123,7 @@ static CURLcode create_conn(struct SessionHandle *data, data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST]; + data->set.ssl.clientcert = data->set.str[STRING_CERT]; #ifdef USE_TLS_SRP data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME]; data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD]; @@ -5732,9 +6183,6 @@ static CURLcode create_conn(struct SessionHandle *data, conn = conn_temp; *in_connect = conn; - /* set a pointer to the hostname we display */ - fix_hostname(data, conn, &conn->host); - infof(data, "Re-using existing connection! (#%ld) with %s %s\n", conn->connection_id, conn->bits.proxy?"proxy":"host", @@ -5746,6 +6194,15 @@ static CURLcode create_conn(struct SessionHandle *data, connections we are allowed to open. */ struct connectbundle *bundle = NULL; + if(conn->handler->flags & PROTOPT_ALPN_NPN) { + /* The protocol wants it, so set the bits if enabled in the easy handle + (default) */ + if(data->set.ssl_enable_alpn) + conn->bits.tls_enable_alpn = TRUE; + if(data->set.ssl_enable_npn) + conn->bits.tls_enable_npn = TRUE; + } + if(waitpipe) /* There is a connection that *might* become usable for pipelining "soon", and we wait for that */ @@ -5778,7 +6235,7 @@ static CURLcode create_conn(struct SessionHandle *data, struct connectdata *conn_candidate; /* The cache is full. Let's see if we can kill a connection. */ - conn_candidate = find_oldest_idle_connection(data); + conn_candidate = Curl_oldest_idle_connection(data); if(conn_candidate) { /* Set the connection's owner correctly, then kill it */ @@ -5816,12 +6273,14 @@ static CURLcode create_conn(struct SessionHandle *data, data->state.authhost.done) { infof(data, "NTLM picked AND auth done set, clear picked!\n"); data->state.authhost.picked = CURLAUTH_NONE; + data->state.authhost.done = FALSE; } if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && data->state.authproxy.done) { infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n"); data->state.authproxy.picked = CURLAUTH_NONE; + data->state.authproxy.done = FALSE; } #endif } @@ -5874,7 +6333,7 @@ CURLcode Curl_setup_conn(struct connectdata *conn, bool *protocol_done) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; Curl_pgrsTime(data, TIMER_NAMELOOKUP); @@ -5948,7 +6407,7 @@ CURLcode Curl_setup_conn(struct connectdata *conn, return result; } -CURLcode Curl_connect(struct SessionHandle *data, +CURLcode Curl_connect(struct Curl_easy *data, struct connectdata **in_connect, bool *asyncp, bool *protocol_done) @@ -5988,140 +6447,17 @@ CURLcode Curl_connect(struct SessionHandle *data, return result; } -CURLcode Curl_done(struct connectdata **connp, - CURLcode status, /* an error if this is called after an - error was detected */ - bool premature) -{ - CURLcode result; - struct connectdata *conn; - struct SessionHandle *data; - - DEBUGASSERT(*connp); - - conn = *connp; - data = conn->data; - - DEBUGF(infof(data, "Curl_done\n")); - - if(data->state.done) - /* Stop if Curl_done() has already been called */ - return CURLE_OK; - - Curl_getoff_all_pipelines(data, conn); - - /* Cleanup possible redirect junk */ - free(data->req.newurl); - data->req.newurl = NULL; - free(data->req.location); - data->req.location = NULL; - - switch(status) { - case CURLE_ABORTED_BY_CALLBACK: - case CURLE_READ_ERROR: - case CURLE_WRITE_ERROR: - /* When we're aborted due to a callback return code it basically have to - be counted as premature as there is trouble ahead if we don't. We have - many callbacks and protocols work differently, we could potentially do - this more fine-grained in the future. */ - premature = TRUE; - default: - break; - } - - /* this calls the protocol-specific function pointer previously set */ - if(conn->handler->done) - result = conn->handler->done(conn, status, premature); - else - result = status; - - if(!result && Curl_pgrsDone(conn)) - result = CURLE_ABORTED_BY_CALLBACK; - - if((conn->send_pipe->size + conn->recv_pipe->size != 0 && - !data->set.reuse_forbid && - !conn->bits.close)) { - /* Stop if pipeline is not empty and we do not have to close - connection. */ - DEBUGF(infof(data, "Connection still in use, no more Curl_done now!\n")); - return CURLE_OK; - } - - data->state.done = TRUE; /* called just now! */ - Curl_resolver_cancel(conn); - - if(conn->dns_entry) { - Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ - conn->dns_entry = NULL; - } - - /* if the transfer was completed in a paused state there can be buffered - data left to write and then kill */ - free(data->state.tempwrite); - data->state.tempwrite = NULL; - - /* if data->set.reuse_forbid is TRUE, it means the libcurl client has - forced us to close this connection. This is ignored for requests taking - place in a NTLM authentication handshake - - if conn->bits.close is TRUE, it means that the connection should be - closed in spite of all our efforts to be nice, due to protocol - restrictions in our or the server's end - - if premature is TRUE, it means this connection was said to be DONE before - the entire request operation is complete and thus we can't know in what - state it is for re-using, so we're forced to close it. In a perfect world - we can add code that keep track of if we really must close it here or not, - but currently we have no such detail knowledge. - */ - - if((data->set.reuse_forbid -#if defined(USE_NTLM) - && !(conn->ntlm.state == NTLMSTATE_TYPE2 || - conn->proxyntlm.state == NTLMSTATE_TYPE2) -#endif - ) || conn->bits.close || premature) { - CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */ - - /* If we had an error already, make sure we return that one. But - if we got a new error, return that. */ - if(!result && res2) - result = res2; - } - else { - /* the connection is no longer in use */ - if(ConnectionDone(data, conn)) { - /* remember the most recently used connection */ - data->state.lastconnect = conn; - - infof(data, "Connection #%ld to host %s left intact\n", - conn->connection_id, - conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname); - } - else - data->state.lastconnect = NULL; - } - - *connp = NULL; /* to make the caller of this function better detect that - this was either closed or handed over to the connection - cache here, and therefore cannot be used from this point on - */ - Curl_free_request_state(data); - - return result; -} - /* * Curl_init_do() inits the readwrite session. This is inited each time (in * the DO function before the protocol-specific DO functions are invoked) for - * a transfer, sometimes multiple times on the same SessionHandle. Make sure + * a transfer, sometimes multiple times on the same Curl_easy. Make sure * nothing in here depends on stuff that are setup dynamically for the * transfer. * * Allow this function to get called with 'conn' set to NULL. */ -CURLcode Curl_init_do(struct SessionHandle *data, struct connectdata *conn) +CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn) { struct SingleRequest *k = &data->req; @@ -6129,7 +6465,7 @@ CURLcode Curl_init_do(struct SessionHandle *data, struct connectdata *conn) conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to * use */ - data->state.done = FALSE; /* Curl_done() is not called yet */ + data->state.done = FALSE; /* *_done() is not called yet */ data->state.expect100header = FALSE; if(data->set.opt_no_body) @@ -6163,80 +6499,111 @@ CURLcode Curl_init_do(struct SessionHandle *data, struct connectdata *conn) } /* - * do_complete is called when the DO actions are complete. - * - * We init chunking and trailer bits to their default values here immediately - * before receiving any header data for the current request in the pipeline. - */ -static void do_complete(struct connectdata *conn) -{ - conn->data->req.chunk=FALSE; - conn->data->req.maxfd = (conn->sockfd>conn->writesockfd? - conn->sockfd:conn->writesockfd)+1; - Curl_pgrsTime(conn->data, TIMER_PRETRANSFER); -} +* get_protocol_family() +* +* This is used to return the protocol family for a given protocol. +* +* Parameters: +* +* protocol [in] - A single bit protocol identifier such as HTTP or HTTPS. +* +* Returns the family as a single bit protocol identifier. +*/ -CURLcode Curl_do(struct connectdata **connp, bool *done) +unsigned int get_protocol_family(unsigned int protocol) { - CURLcode result=CURLE_OK; - struct connectdata *conn = *connp; - struct SessionHandle *data = conn->data; + unsigned int family; - if(conn->handler->do_it) { - /* generic protocol-specific function pointer set in curl_connect() */ - result = conn->handler->do_it(conn, done); + switch(protocol) { + case CURLPROTO_HTTP: + case CURLPROTO_HTTPS: + family = CURLPROTO_HTTP; + break; - /* This was formerly done in transfer.c, but we better do it here */ - if((CURLE_SEND_ERROR == result) && conn->bits.reuse) { - /* - * If the connection is using an easy handle, call reconnect - * to re-establish the connection. Otherwise, let the multi logic - * figure out how to re-establish the connection. - */ - if(!data->multi) { - result = Curl_reconnect_request(connp); - - if(!result) { - /* ... finally back to actually retry the DO phase */ - conn = *connp; /* re-assign conn since Curl_reconnect_request - creates a new connection */ - result = conn->handler->do_it(conn, done); - } - } - else - return result; - } + case CURLPROTO_FTP: + case CURLPROTO_FTPS: + family = CURLPROTO_FTP; + break; - if(!result && *done) - /* do_complete must be called after the protocol-specific DO function */ - do_complete(conn); - } - return result; -} + case CURLPROTO_SCP: + family = CURLPROTO_SCP; + break; -/* - * Curl_do_more() is called during the DO_MORE multi state. It is basically a - * second stage DO state which (wrongly) was introduced to support FTP's - * second connection. - * - * TODO: A future libcurl should be able to work away this state. - * - * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to - * DOING state there's more work to do! - */ + case CURLPROTO_SFTP: + family = CURLPROTO_SFTP; + break; -CURLcode Curl_do_more(struct connectdata *conn, int *complete) -{ - CURLcode result=CURLE_OK; + case CURLPROTO_TELNET: + family = CURLPROTO_TELNET; + break; - *complete = 0; + case CURLPROTO_LDAP: + case CURLPROTO_LDAPS: + family = CURLPROTO_LDAP; + break; - if(conn->handler->do_more) - result = conn->handler->do_more(conn, complete); + case CURLPROTO_DICT: + family = CURLPROTO_DICT; + break; - if(!result && (*complete == 1)) - /* do_complete must be called after the protocol-specific DO function */ - do_complete(conn); + case CURLPROTO_FILE: + family = CURLPROTO_FILE; + break; - return result; + case CURLPROTO_TFTP: + family = CURLPROTO_TFTP; + break; + + case CURLPROTO_IMAP: + case CURLPROTO_IMAPS: + family = CURLPROTO_IMAP; + break; + + case CURLPROTO_POP3: + case CURLPROTO_POP3S: + family = CURLPROTO_POP3; + break; + + case CURLPROTO_SMTP: + case CURLPROTO_SMTPS: + family = CURLPROTO_SMTP; + break; + + case CURLPROTO_RTSP: + family = CURLPROTO_RTSP; + break; + + case CURLPROTO_RTMP: + case CURLPROTO_RTMPS: + family = CURLPROTO_RTMP; + break; + + case CURLPROTO_RTMPT: + case CURLPROTO_RTMPTS: + family = CURLPROTO_RTMPT; + break; + + case CURLPROTO_RTMPE: + family = CURLPROTO_RTMPE; + break; + + case CURLPROTO_RTMPTE: + family = CURLPROTO_RTMPTE; + break; + + case CURLPROTO_GOPHER: + family = CURLPROTO_GOPHER; + break; + + case CURLPROTO_SMB: + case CURLPROTO_SMBS: + family = CURLPROTO_SMB; + break; + + default: + family = 0; + break; + } + + return family; } diff --git a/Utilities/cmcurl/lib/url.h b/Utilities/cmcurl/lib/url.h index f9667cb..90d9db3 100644 --- a/Utilities/cmcurl/lib/url.h +++ b/Utilities/cmcurl/lib/url.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -27,26 +27,23 @@ * Prototypes for library-wide functions provided by url.c */ -CURLcode Curl_init_do(struct SessionHandle *data, struct connectdata *conn); -CURLcode Curl_open(struct SessionHandle **curl); +CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn); +CURLcode Curl_open(struct Curl_easy **curl); CURLcode Curl_init_userdefined(struct UserDefined *set); -CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, +CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option, va_list arg); -CURLcode Curl_dupset(struct SessionHandle * dst, struct SessionHandle * src); -void Curl_freeset(struct SessionHandle * data); -CURLcode Curl_close(struct SessionHandle *data); /* opposite of curl_open() */ -CURLcode Curl_connect(struct SessionHandle *, struct connectdata **, +CURLcode Curl_dupset(struct Curl_easy * dst, struct Curl_easy * src); +void Curl_freeset(struct Curl_easy * data); +CURLcode Curl_close(struct Curl_easy *data); /* opposite of curl_open() */ +CURLcode Curl_connect(struct Curl_easy *, struct connectdata **, bool *async, bool *protocol_connect); -CURLcode Curl_do(struct connectdata **, bool *done); -CURLcode Curl_do_more(struct connectdata *, int *completed); -CURLcode Curl_done(struct connectdata **, CURLcode, bool premature); CURLcode Curl_disconnect(struct connectdata *, bool dead_connection); CURLcode Curl_protocol_connect(struct connectdata *conn, bool *done); CURLcode Curl_protocol_connecting(struct connectdata *conn, bool *done); CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done); CURLcode Curl_setup_conn(struct connectdata *conn, bool *protocol_done); -void Curl_free_request_state(struct SessionHandle *data); +void Curl_free_request_state(struct Curl_easy *data); int Curl_protocol_getsock(struct connectdata *conn, curl_socket_t *socks, @@ -55,24 +52,21 @@ int Curl_doing_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); -bool Curl_isPipeliningEnabled(const struct SessionHandle *handle); -CURLcode Curl_addHandleToPipeline(struct SessionHandle *handle, +bool Curl_isPipeliningEnabled(const struct Curl_easy *handle); +CURLcode Curl_addHandleToPipeline(struct Curl_easy *handle, struct curl_llist *pipeline); -int Curl_removeHandleFromPipeline(struct SessionHandle *handle, +int Curl_removeHandleFromPipeline(struct Curl_easy *handle, struct curl_llist *pipeline); +struct connectdata * +Curl_oldest_idle_connection(struct Curl_easy *data); /* remove the specified connection from all (possible) pipelines and related queues */ -void Curl_getoff_all_pipelines(struct SessionHandle *data, +void Curl_getoff_all_pipelines(struct Curl_easy *data, struct connectdata *conn); -void Curl_close_connections(struct SessionHandle *data); +void Curl_close_connections(struct Curl_easy *data); #define CURL_DEFAULT_PROXY_PORT 1080 /* default proxy port unless specified */ -#define CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE "rcmd" /* default socks5 gssapi - service */ -#define CURL_DEFAULT_PROXY_SERVICE_NAME "HTTP" /* default negotiate proxy - service */ -#define CURL_DEFAULT_SERVICE_NAME "HTTP" /* default negotiate service */ CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex); diff --git a/Utilities/cmcurl/lib/urldata.h b/Utilities/cmcurl/lib/urldata.h index b1c2056..3cf7ed9 100644 --- a/Utilities/cmcurl/lib/urldata.h +++ b/Utilities/cmcurl/lib/urldata.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -93,7 +93,15 @@ #include <gnutls/gnutls.h> #endif -#ifdef USE_POLARSSL +#ifdef USE_MBEDTLS + +#include <mbedtls/ssl.h> +#include <mbedtls/version.h> +#include <mbedtls/entropy.h> +#include <mbedtls/ctr_drbg.h> + +#elif defined USE_POLARSSL + #include <polarssl/ssl.h> #include <polarssl/version.h> #if POLARSSL_VERSION_NUMBER<0x01010000 @@ -102,6 +110,7 @@ #include <polarssl/entropy.h> #include <polarssl/ctr_drbg.h> #endif /* POLARSSL_VERSION_NUMBER<0x01010000 */ + #endif /* USE_POLARSSL */ #ifdef USE_CYASSL @@ -199,14 +208,13 @@ #define CURLEASY_MAGIC_NUMBER 0xc0dedbadU #define GOOD_EASY_HANDLE(x) \ - ((x) && (((struct SessionHandle *)(x))->magic == CURLEASY_MAGIC_NUMBER)) + ((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER)) /* Some convenience macros to get the larger/smaller value out of two given. We prefix with CURL to prevent name collisions. */ #define CURLMAX(x,y) ((x)>(y)?(x):(y)) #define CURLMIN(x,y) ((x)<(y)?(x):(y)) - #ifdef HAVE_GSSAPI /* Types needed for krb5-ftp connections */ struct krb5buffer { @@ -233,7 +241,6 @@ struct curl_schannel_cred { CredHandle cred_handle; TimeStamp time_stamp; int refcount; - bool cached; }; struct curl_schannel_ctxt { @@ -265,61 +272,57 @@ struct ssl_connect_data { current state of the connection. */ bool use; ssl_connection_state state; -#ifdef USE_OPENSSL + ssl_connect_state connecting_state; +#if defined(USE_OPENSSL) /* these ones requires specific SSL-types */ SSL_CTX* ctx; SSL* handle; X509* server_cert; - ssl_connect_state connecting_state; -#endif /* USE_OPENSSL */ -#ifdef USE_GNUTLS +#elif defined(USE_GNUTLS) gnutls_session_t session; gnutls_certificate_credentials_t cred; #ifdef USE_TLS_SRP gnutls_srp_client_credentials_t srp_client_cred; #endif - ssl_connect_state connecting_state; -#endif /* USE_GNUTLS */ -#ifdef USE_POLARSSL +#elif defined(USE_MBEDTLS) + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_entropy_context entropy; + mbedtls_ssl_context ssl; + int server_fd; + mbedtls_x509_crt cacert; + mbedtls_x509_crt clicert; + mbedtls_x509_crl crl; + mbedtls_pk_context pk; + mbedtls_ssl_config config; + const char *protocols[3]; +#elif defined(USE_POLARSSL) ctr_drbg_context ctr_drbg; entropy_context entropy; ssl_context ssl; - ssl_session ssn; int server_fd; x509_crt cacert; x509_crt clicert; x509_crl crl; rsa_context rsa; - ssl_connect_state connecting_state; -#endif /* USE_POLARSSL */ -#ifdef USE_CYASSL +#elif defined(USE_CYASSL) SSL_CTX* ctx; SSL* handle; - ssl_connect_state connecting_state; -#endif /* USE_CYASSL */ -#ifdef USE_NSS +#elif defined(USE_NSS) PRFileDesc *handle; char *client_nickname; - struct SessionHandle *data; + struct Curl_easy *data; struct curl_llist *obj_list; PK11GenericObject *obj_clicert; - ssl_connect_state connecting_state; -#endif /* USE_NSS */ -#ifdef USE_GSKIT +#elif defined(USE_GSKIT) gsk_handle handle; int iocport; - ssl_connect_state connecting_state; -#endif -#ifdef USE_AXTLS +#elif defined(USE_AXTLS) SSL_CTX* ssl_ctx; SSL* ssl; - ssl_connect_state connecting_state; -#endif /* USE_AXTLS */ -#ifdef USE_SCHANNEL +#elif defined(USE_SCHANNEL) struct curl_schannel_cred *cred; struct curl_schannel_ctxt *ctxt; SecPkgContext_StreamSizes stream_sizes; - ssl_connect_state connecting_state; size_t encdata_length, decdata_length; size_t encdata_offset, decdata_offset; unsigned char *encdata_buffer, *decdata_buffer; @@ -327,14 +330,14 @@ struct ssl_connect_data { CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */ bool recv_sspi_close_notify; /* true if connection closed by close_notify */ bool recv_connection_closed; /* true if connection closed, regardless how */ -#endif /* USE_SCHANNEL */ -#ifdef USE_DARWINSSL +#elif defined(USE_DARWINSSL) SSLContextRef ssl_ctx; curl_socket_t ssl_sockfd; - ssl_connect_state connecting_state; bool ssl_direction; /* true if writing, false if reading */ size_t ssl_write_buffered_length; -#endif /* USE_DARWINSSL */ +#elif defined(USE_SSL) +#error "SSL backend specific information missing from ssl_connect_data" +#endif }; struct ssl_config_data { @@ -348,6 +351,7 @@ struct ssl_config_data { char *CAfile; /* certificate to verify peer against */ const char *CRLfile; /* CRL to check certificate revocation */ const char *issuercert;/* optional issuer certificate filename */ + char *clientcert; char *random_file; /* path to file containing "random" data */ char *egdsocket; /* path to file containing the EGD daemon socket */ char *cipher_list; /* list of ciphers to use */ @@ -368,10 +372,12 @@ struct ssl_config_data { /* information stored about one single SSL session */ struct curl_ssl_session { char *name; /* host name for which this ID was used */ + char *conn_to_host; /* host name for the connection (may be NULL) */ void *sessionid; /* as returned from the SSL layer */ size_t idsize; /* if known, otherwise 0 */ long age; /* just a number, the higher the more recent */ - int remote_port; /* remote port to connect to */ + int remote_port; /* remote port */ + int conn_to_port; /* remote port for the connection (may be -1) */ struct ssl_config_data ssl_config; /* setup for this session */ }; @@ -457,7 +463,7 @@ struct negotiatedata { #ifdef HAVE_GSSAPI OM_uint32 status; gss_ctx_id_t context; - gss_name_t server_name; + gss_name_t spn; gss_buffer_desc output_token; #else #ifdef USE_WINDOWS_SSPI @@ -466,7 +472,7 @@ struct negotiatedata { CtxtHandle *context; SEC_WINNT_AUTH_IDENTITY identity; SEC_WINNT_AUTH_IDENTITY *p_identity; - TCHAR *server_name; + TCHAR *spn; size_t token_max; BYTE *output_token; size_t output_token_length; @@ -483,6 +489,10 @@ struct ConnectBits { /* always modify bits.close with the connclose() and connkeep() macros! */ bool close; /* if set, we close the connection after this request */ bool reuse; /* if set, this is a re-used connection */ + bool conn_to_host; /* if set, this connection has a "connect to host" + that overrides the host in the URL */ + bool conn_to_port; /* if set, this connection has a "connect to port" + that overrides the port in the URL (remote port) */ bool proxy; /* if set, this transfer is done through a proxy - any type */ bool httpproxy; /* if set, this transfer is done through a http proxy */ bool user_passwd; /* do we use user+password for this connection? */ @@ -531,6 +541,10 @@ struct ConnectBits { connection */ bool type_set; /* type= was used in the URL */ bool multiplex; /* connection is multiplexed */ + + bool tcp_fastopen; /* use TCP Fast Open */ + bool tls_enable_npn; /* TLS NPN extension? */ + bool tls_enable_alpn; /* TLS ALPN extension? */ }; struct hostname { @@ -604,9 +618,9 @@ enum upgrade101 { }; /* - * Request specific data in the easy handle (SessionHandle). Previously, + * Request specific data in the easy handle (Curl_easy). Previously, * these members were on the connectdata struct but since a conn struct may - * now be shared between different SessionHandles, we store connection-specific + * now be shared between different Curl_easys, we store connection-specific * data here. This struct only keeps stuff that's interesting for *this* * request, as it will be cleared between multiple ones */ @@ -777,7 +791,7 @@ struct Curl_handler { /* If used, this function gets called from transfer.c:readwrite_data() to allow the protocol to do extra reads/writes */ - CURLcode (*readwrite)(struct SessionHandle *data, struct connectdata *conn, + CURLcode (*readwrite)(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *readmore); long defport; /* Default port. */ @@ -802,7 +816,7 @@ struct Curl_handler { url query strings (?foo=bar) ! */ #define PROTOPT_CREDSPERREQUEST (1<<7) /* requires login credentials per request instead of per connection */ - +#define PROTOPT_ALPN_NPN (1<<8) /* set ALPN and/or NPN for this */ /* return the count of bytes sent, or -1 on error */ typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */ @@ -818,15 +832,29 @@ typedef ssize_t (Curl_recv)(struct connectdata *conn, /* connection data */ size_t len, /* max amount to read */ CURLcode *err); /* error to return */ +#ifdef USE_RECV_BEFORE_SEND_WORKAROUND +struct postponed_data { + char *buffer; /* Temporal store for received data during + sending, must be freed */ + size_t allocated_size; /* Size of temporal store */ + size_t recv_size; /* Size of received data during sending */ + size_t recv_processed; /* Size of processed part of postponed data */ +#ifdef DEBUGBUILD + curl_socket_t bindsock;/* Structure must be bound to specific socket, + used only for DEBUGASSERT */ +#endif /* DEBUGBUILD */ +}; +#endif /* USE_RECV_BEFORE_SEND_WORKAROUND */ + /* * The connectdata struct contains all fields and variables that should be * unique for an entire connection. */ struct connectdata { - /* 'data' is the CURRENT SessionHandle using this connection -- take great + /* 'data' is the CURRENT Curl_easy using this connection -- take great caution that this might very well vary between different times this connection is used! */ - struct SessionHandle *data; + struct Curl_easy *data; /* chunk is for HTTP chunked encoding, but is in the general connectdata struct only because we can do just about any protocol through a HTTP proxy @@ -867,10 +895,14 @@ struct connectdata { int socktype; /* SOCK_STREAM or SOCK_DGRAM */ struct hostname host; + struct hostname conn_to_host; /* the host to connect to. valid only if + bits.conn_to_host is set */ struct hostname proxy; long port; /* which port to use locally */ - int remote_port; /* what remote port to connect to, not the proxy port! */ + int remote_port; /* the remote port, not the proxy port! */ + int conn_to_port; /* the remote port to connect to. valid only if + bits.conn_to_port is set */ /* 'primary_ip' and 'primary_port' get filled with peer's numerical ip address and port number whenever an outgoing connection is @@ -893,7 +925,7 @@ struct connectdata { char *passwd; /* password string, allocated */ char *options; /* options string, allocated */ - char *xoauth2_bearer; /* bearer token for xoauth2, allocated */ + char *oauth_bearer; /* bearer token for OAuth 2.0, allocated */ char *proxyuser; /* proxy user name string, allocated */ char *proxypasswd; /* proxy password string, allocated */ @@ -912,8 +944,12 @@ struct connectdata { Curl_recv *recv[2]; Curl_send *send[2]; +#ifdef USE_RECV_BEFORE_SEND_WORKAROUND + struct postponed_data postponed[2]; /* two buffers for two sockets */ +#endif /* USE_RECV_BEFORE_SEND_WORKAROUND */ struct ssl_connect_data ssl[2]; /* this is for ssl-stuff */ struct ssl_config_data ssl_config; + bool tls_upgraded; struct ConnectBits bits; /* various state-flags for this connection */ @@ -929,7 +965,7 @@ struct connectdata { const struct Curl_handler *handler; /* Connection's protocol handler */ const struct Curl_handler *given; /* The protocol first given */ - long ip_version; /* copied from the SessionHandle at creation time */ + long ip_version; /* copied from the Curl_easy at creation time */ /**** curl_get() phase fields */ @@ -1172,7 +1208,7 @@ typedef enum { /* * Values that are generated, temporary or calculated internally for a * "session handle" must be defined within the 'struct UrlState'. This struct - * will be used within the SessionHandle struct. When the 'SessionHandle' + * will be used within the Curl_easy struct. When the 'Curl_easy' * struct is cloned, this data MUST NOT be copied. * * Remember that any "state" information goes globally for the curl handle. @@ -1218,11 +1254,13 @@ struct UrlState { bytes / second */ bool this_is_a_follow; /* this is a followed Location: request */ - char *first_host; /* if set, this should be the host name that we will + char *first_host; /* host name of the first (not followed) request. + if set, this should be the host name that we will sent authorization to, no else. Used to make Location: following not keep sending user+password... This is strdup() data. */ + int first_remote_port; /* remote port of the first (not followed) request */ struct curl_ssl_session *session; /* array of 'max_ssl_sessions' size */ long sessionage; /* number of the most recent session */ char *tempwrite; /* allocated buffer to keep data in when a write @@ -1306,12 +1344,19 @@ struct UrlState { curl_off_t infilesize; /* size of file to upload, -1 means unknown. Copied from set.filesize at start of operation */ - int drain; /* Increased when this stream has data to read, even if its - socket not necessarily is readable. Decreased when - checked. */ - bool done; /* set to FALSE when Curl_do() is called and set to TRUE when - Curl_done() is called, to prevent Curl_done() to get invoked - twice when the multi interface is used. */ + size_t drain; /* Increased when this stream has data to read, even if its + socket is not necessarily is readable. Decreased when + checked. */ + bool done; /* set to FALSE when Curl_init_do() is called and set to TRUE + when multi_done() is called, to prevent multi_done() to get + invoked twice when the multi interface is used. */ + + curl_read_callback fread_func; /* read callback/function */ + void *in; /* CURLOPT_READDATA */ + + struct Curl_easy *stream_depends_on; + bool stream_depends_e; /* set or don't set the Exclusive bit */ + int stream_weight; }; @@ -1350,6 +1395,7 @@ enum dupstring { STRING_COOKIE, /* HTTP cookie string to send */ STRING_COOKIEJAR, /* dump all cookies to this file */ STRING_CUSTOMREQUEST, /* HTTP/FTP/RTSP request/method to use */ + STRING_DEFAULT_PROTOCOL, /* Protocol to use when the URL doesn't specify */ STRING_DEVICE, /* local network interface/address to use */ STRING_ENCODING, /* Accept-Encoding string */ STRING_FTP_ACCOUNT, /* ftp account data */ @@ -1391,8 +1437,10 @@ enum dupstring { STRING_SSH_KNOWNHOSTS, /* file name of knownhosts file */ #endif #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) - STRING_SOCKS5_GSSAPI_SERVICE, /* GSSAPI service name */ STRING_PROXY_SERVICE_NAME, /* Proxy service name */ +#endif +#if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \ + defined(USE_SPNEGO) STRING_SERVICE_NAME, /* Service name */ #endif STRING_MAIL_FROM, @@ -1427,7 +1475,7 @@ struct UserDefined { proxy string features a ":[port]" that one will override this. */ void *out; /* CURLOPT_WRITEDATA */ - void *in; /* CURLOPT_READDATA */ + void *in_set; /* CURLOPT_READDATA */ void *writeheader; /* write the header to this if non-NULL */ void *rtp_out; /* write RTP to this if non-NULL */ long use_port; /* which port to use (when not using default) */ @@ -1452,7 +1500,7 @@ struct UserDefined { curl_write_callback fwrite_func; /* function that stores the output */ curl_write_callback fwrite_header; /* function that stores headers */ curl_write_callback fwrite_rtp; /* function that stores interleaved RTP */ - curl_read_callback fread_func; /* function that reads the input */ + curl_read_callback fread_func_set; /* function that reads the input */ int is_fread_set; /* boolean, has read callback been set to non-NULL? */ int is_fwrite_set; /* boolean, has write callback been set to non-NULL? */ curl_progress_callback fprogress; /* OLD and deprecated progress callback */ @@ -1484,7 +1532,8 @@ struct UserDefined { long connecttimeout; /* in milliseconds, 0 means no timeout */ long accepttimeout; /* in milliseconds, 0 means no timeout */ long server_response_timeout; /* in milliseconds, 0 means no timeout */ - long tftp_blksize ; /* in bytes, 0 means use default */ + long tftp_blksize; /* in bytes, 0 means use default */ + bool tftp_no_options; /* do not send TFTP options requests */ curl_off_t filesize; /* size of file to upload, -1 means unknown */ long low_speed_limit; /* bytes/second */ long low_speed_time; /* number of seconds */ @@ -1509,6 +1558,8 @@ struct UserDefined { struct curl_slist *telnet_options; /* linked list of telnet options */ struct curl_slist *resolve; /* list of names to add/remove from DNS cache */ + struct curl_slist *connect_to; /* list of host:port mappings to override + the hostname and port to connect to */ curl_TimeCond timecondition; /* kind of time/date comparison */ time_t timevalue; /* what time to compare with */ Curl_HttpReq httpreq; /* what kind of HTTP request (if any) is this */ @@ -1556,7 +1607,6 @@ struct UserDefined { bool http_set_referer; /* is a custom referer used */ bool http_auto_referer; /* set "correct" referer when following location: */ bool opt_no_body; /* as set with CURLOPT_NOBODY */ - bool set_port; /* custom port number used */ bool upload; /* upload request */ enum CURL_NETRC_OPTION use_netrc; /* defined in include/curl.h */ @@ -1596,7 +1646,7 @@ struct UserDefined { long allowed_protocols; long redir_protocols; #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) - long socks5_gssapi_nec; /* flag to support nec socks5 server */ + bool socks5_gssapi_nec; /* Flag to support NEC SOCKS5 server */ #endif struct curl_slist *mail_rcpt; /* linked list of mail recipients */ bool sasl_ir; /* Enable/disable SASL initial response */ @@ -1618,15 +1668,20 @@ struct UserDefined { bool tcp_keepalive; /* use TCP keepalives */ long tcp_keepidle; /* seconds in idle before sending keepalive probe */ long tcp_keepintvl; /* seconds between TCP keepalive probes */ + bool tcp_fastopen; /* use TCP Fast Open */ size_t maxconnects; /* Max idle connections in the connection cache */ - bool ssl_enable_npn; /* TLS NPN extension? */ - bool ssl_enable_alpn; /* TLS ALPN extension? */ + bool ssl_enable_npn; /* TLS NPN extension? */ + bool ssl_enable_alpn; /* TLS ALPN extension? */ bool path_as_is; /* allow dotdots? */ bool pipewait; /* wait for pipe/multiplex status before starting a new connection */ long expect_100_timeout; /* in milliseconds */ + + struct Curl_easy *stream_depends_on; + bool stream_depends_e; /* set or don't set the Exclusive bit */ + int stream_weight; }; struct Names { @@ -1649,10 +1704,10 @@ struct Names { * 'struct UrlState' instead. */ -struct SessionHandle { +struct Curl_easy { /* first, two fields for the linked list of these */ - struct SessionHandle *next; - struct SessionHandle *prev; + struct Curl_easy *next; + struct Curl_easy *prev; struct connectdata *easy_conn; /* the "unit's" connection */ diff --git a/Utilities/cmcurl/lib/vauth/cleartext.c b/Utilities/cmcurl/lib/vauth/cleartext.c new file mode 100644 index 0000000..4e906bc --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/cleartext.c @@ -0,0 +1,157 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC4616 PLAIN authentication + * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include <curl/curl.h> +#include "urldata.h" + +#include "vauth/vauth.h" +#include "curl_base64.h" +#include "curl_md5.h" +#include "warnless.h" +#include "strtok.h" +#include "strequal.h" +#include "rawstr.h" +#include "sendf.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_plain_message() + * + * This is used to generate an already encoded PLAIN message ready + * for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name. + * passdwp [in] - The user's password. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + char **outptr, size_t *outlen) +{ + CURLcode result; + char *plainauth; + size_t ulen; + size_t plen; + + ulen = strlen(userp); + plen = strlen(passwdp); + + plainauth = malloc(2 * ulen + plen + 2); + if(!plainauth) { + *outlen = 0; + *outptr = NULL; + return CURLE_OUT_OF_MEMORY; + } + + /* Calculate the reply */ + memcpy(plainauth, userp, ulen); + plainauth[ulen] = '\0'; + memcpy(plainauth + ulen + 1, userp, ulen); + plainauth[2 * ulen + 1] = '\0'; + memcpy(plainauth + 2 * ulen + 2, passwdp, plen); + + /* Base64 encode the reply */ + result = Curl_base64_encode(data, plainauth, 2 * ulen + plen + 2, outptr, + outlen); + free(plainauth); + + return result; +} + +/* + * Curl_auth_create_login_message() + * + * This is used to generate an already encoded LOGIN message containing the + * user name or password ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * valuep [in] - The user name or user's password. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_login_message(struct Curl_easy *data, + const char *valuep, char **outptr, + size_t *outlen) +{ + size_t vlen = strlen(valuep); + + if(!vlen) { + /* Calculate an empty reply */ + *outptr = strdup("="); + if(*outptr) { + *outlen = (size_t) 1; + return CURLE_OK; + } + + *outlen = 0; + return CURLE_OUT_OF_MEMORY; + } + + /* Base64 encode the value */ + return Curl_base64_encode(data, valuep, vlen, outptr, outlen); +} + +/* + * Curl_auth_create_external_message() + * + * This is used to generate an already encoded EXTERNAL message containing + * the user name ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * user [in] - The user name. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_external_message(struct Curl_easy *data, + const char *user, char **outptr, + size_t *outlen) +{ + /* This is the same formatting as the login message */ + return Curl_auth_create_login_message(data, user, outptr, outlen); +} diff --git a/Utilities/cmcurl/lib/vauth/cram.c b/Utilities/cmcurl/lib/vauth/cram.c new file mode 100644 index 0000000..3074a16 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/cram.c @@ -0,0 +1,138 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC2195 CRAM-MD5 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_CRYPTO_AUTH) + +#include <curl/curl.h> +#include "urldata.h" + +#include "vauth/vauth.h" +#include "curl_base64.h" +#include "curl_hmac.h" +#include "curl_md5.h" +#include "warnless.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_decode_cram_md5_message() + * + * This is used to decode an already encoded CRAM-MD5 challenge message. + * + * Parameters: + * + * chlg64 [in] - The base64 encoded challenge message. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_cram_md5_message(const char *chlg64, char **outptr, + size_t *outlen) +{ + CURLcode result = CURLE_OK; + size_t chlg64len = strlen(chlg64); + + *outptr = NULL; + *outlen = 0; + + /* Decode the challenge if necessary */ + if(chlg64len && *chlg64 != '=') + result = Curl_base64_decode(chlg64, (unsigned char **) outptr, outlen); + + return result; +} + +/* + * Curl_auth_create_cram_md5_message() + * + * This is used to generate an already encoded CRAM-MD5 response message ready + * for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg [in] - The challenge. + * userp [in] - The user name. + * passdwp [in] - The user's password. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_cram_md5_message(struct Curl_easy *data, + const char *chlg, + const char *userp, + const char *passwdp, + char **outptr, size_t *outlen) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + HMAC_context *ctxt; + unsigned char digest[MD5_DIGEST_LEN]; + char *response; + + if(chlg) + chlglen = strlen(chlg); + + /* Compute the digest using the password as the key */ + ctxt = Curl_HMAC_init(Curl_HMAC_MD5, + (const unsigned char *) passwdp, + curlx_uztoui(strlen(passwdp))); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + /* Update the digest with the given challenge */ + if(chlglen > 0) + Curl_HMAC_update(ctxt, (const unsigned char *) chlg, + curlx_uztoui(chlglen)); + + /* Finalise the digest */ + Curl_HMAC_final(ctxt, digest); + + /* Generate the response */ + response = aprintf( + "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + userp, digest[0], digest[1], digest[2], digest[3], digest[4], + digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], + digest[11], digest[12], digest[13], digest[14], digest[15]); + if(!response) + return CURLE_OUT_OF_MEMORY; + + /* Base64 encode the response */ + result = Curl_base64_encode(data, response, 0, outptr, outlen); + + free(response); + + return result; +} + +#endif /* !CURL_DISABLE_CRYPTO_AUTH */ diff --git a/Utilities/cmcurl/lib/vauth/digest.c b/Utilities/cmcurl/lib/vauth/digest.c new file mode 100644 index 0000000..26ea7b5 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/digest.c @@ -0,0 +1,883 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC2831 DIGEST-MD5 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_CRYPTO_AUTH) + +#include <curl/curl.h> + +#include "vauth/vauth.h" +#include "vauth/digest.h" +#include "urldata.h" +#include "curl_base64.h" +#include "curl_hmac.h" +#include "curl_md5.h" +#include "vtls/vtls.h" +#include "warnless.h" +#include "strtok.h" +#include "rawstr.h" +#include "non-ascii.h" /* included for Curl_convert_... prototypes */ +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +#if !defined(USE_WINDOWS_SSPI) +#define DIGEST_QOP_VALUE_AUTH (1 << 0) +#define DIGEST_QOP_VALUE_AUTH_INT (1 << 1) +#define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2) + +#define DIGEST_QOP_VALUE_STRING_AUTH "auth" +#define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int" +#define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf" + +/* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines. + It converts digest text to ASCII so the MD5 will be correct for + what ultimately goes over the network. +*/ +#define CURL_OUTPUT_DIGEST_CONV(a, b) \ + result = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \ + if(result) { \ + free(b); \ + return result; \ + } +#endif /* !USE_WINDOWS_SSPI */ + +bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, + const char **endptr) +{ + int c; + bool starts_with_quote = FALSE; + bool escape = FALSE; + + for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--);) + *value++ = *str++; + *value = 0; + + if('=' != *str++) + /* eek, no match */ + return FALSE; + + if('\"' == *str) { + /* This starts with a quote so it must end with one as well! */ + str++; + starts_with_quote = TRUE; + } + + for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) { + switch(*str) { + case '\\': + if(!escape) { + /* possibly the start of an escaped quote */ + escape = TRUE; + *content++ = '\\'; /* Even though this is an escape character, we still + store it as-is in the target buffer */ + continue; + } + break; + + case ',': + if(!starts_with_quote) { + /* This signals the end of the content if we didn't get a starting + quote and then we do "sloppy" parsing */ + c = 0; /* the end */ + continue; + } + break; + + case '\r': + case '\n': + /* end of string */ + c = 0; + continue; + + case '\"': + if(!escape && starts_with_quote) { + /* end of string */ + c = 0; + continue; + } + break; + } + + escape = FALSE; + *content++ = *str; + } + + *content = 0; + *endptr = str; + + return TRUE; +} + +#if !defined(USE_WINDOWS_SSPI) +/* Convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/ +static void auth_digest_md5_to_ascii(unsigned char *source, /* 16 bytes */ + unsigned char *dest) /* 33 bytes */ +{ + int i; + for(i = 0; i < 16; i++) + snprintf((char *) &dest[i * 2], 3, "%02x", source[i]); +} + +/* Perform quoted-string escaping as described in RFC2616 and its errata */ +static char *auth_digest_string_quoted(const char *source) +{ + char *dest, *d; + const char *s = source; + size_t n = 1; /* null terminator */ + + /* Calculate size needed */ + while(*s) { + ++n; + if(*s == '"' || *s == '\\') { + ++n; + } + ++s; + } + + dest = malloc(n); + if(dest) { + s = source; + d = dest; + while(*s) { + if(*s == '"' || *s == '\\') { + *d++ = '\\'; + } + *d++ = *s++; + } + *d = 0; + } + + return dest; +} + +/* Retrieves the value for a corresponding key from the challenge string + * returns TRUE if the key could be found, FALSE if it does not exists + */ +static bool auth_digest_get_key_value(const char *chlg, + const char *key, + char *value, + size_t max_val_len, + char end_char) +{ + char *find_pos; + size_t i; + + find_pos = strstr(chlg, key); + if(!find_pos) + return FALSE; + + find_pos += strlen(key); + + for(i = 0; *find_pos && *find_pos != end_char && i < max_val_len - 1; ++i) + value[i] = *find_pos++; + value[i] = '\0'; + + return TRUE; +} + +static CURLcode auth_digest_get_qop_values(const char *options, int *value) +{ + char *tmp; + char *token; + char *tok_buf; + + /* Initialise the output */ + *value = 0; + + /* Tokenise the list of qop values. Use a temporary clone of the buffer since + strtok_r() ruins it. */ + tmp = strdup(options); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = strtok_r(tmp, ",", &tok_buf); + while(token != NULL) { + if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH)) + *value |= DIGEST_QOP_VALUE_AUTH; + else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) + *value |= DIGEST_QOP_VALUE_AUTH_INT; + else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF)) + *value |= DIGEST_QOP_VALUE_AUTH_CONF; + + token = strtok_r(NULL, ",", &tok_buf); + } + + free(tmp); + + return CURLE_OK; +} + +/* + * auth_decode_digest_md5_message() + * + * This is used internally to decode an already encoded DIGEST-MD5 challenge + * message into the seperate attributes. + * + * Parameters: + * + * chlg64 [in] - The base64 encoded challenge message. + * nonce [in/out] - The buffer where the nonce will be stored. + * nlen [in] - The length of the nonce buffer. + * realm [in/out] - The buffer where the realm will be stored. + * rlen [in] - The length of the realm buffer. + * alg [in/out] - The buffer where the algorithm will be stored. + * alen [in] - The length of the algorithm buffer. + * qop [in/out] - The buffer where the qop-options will be stored. + * qlen [in] - The length of the qop buffer. + * + * Returns CURLE_OK on success. + */ +static CURLcode auth_decode_digest_md5_message(const char *chlg64, + char *nonce, size_t nlen, + char *realm, size_t rlen, + char *alg, size_t alen, + char *qop, size_t qlen) +{ + CURLcode result = CURLE_OK; + unsigned char *chlg = NULL; + size_t chlglen = 0; + size_t chlg64len = strlen(chlg64); + + /* Decode the base-64 encoded challenge message */ + if(chlg64len && *chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) + return CURLE_BAD_CONTENT_ENCODING; + + /* Retrieve nonce string from the challenge */ + if(!auth_digest_get_key_value((char *) chlg, "nonce=\"", nonce, nlen, + '\"')) { + free(chlg); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Retrieve realm string from the challenge */ + if(!auth_digest_get_key_value((char *) chlg, "realm=\"", realm, rlen, + '\"')) { + /* Challenge does not have a realm, set empty string [RFC2831] page 6 */ + strcpy(realm, ""); + } + + /* Retrieve algorithm string from the challenge */ + if(!auth_digest_get_key_value((char *) chlg, "algorithm=", alg, alen, ',')) { + free(chlg); + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Retrieve qop-options string from the challenge */ + if(!auth_digest_get_key_value((char *) chlg, "qop=\"", qop, qlen, '\"')) { + free(chlg); + return CURLE_BAD_CONTENT_ENCODING; + } + + free(chlg); + + return CURLE_OK; +} + +/* + * Curl_auth_create_digest_md5_message() + * + * This is used to generate an already encoded DIGEST-MD5 response message + * ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg64 [in] - The base64 encoded challenge message. + * userp [in] - The user name. + * passdwp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const char *chlg64, + const char *userp, + const char *passwdp, + const char *service, + char **outptr, size_t *outlen) +{ + CURLcode result = CURLE_OK; + size_t i; + MD5_context *ctxt; + char *response = NULL; + unsigned char digest[MD5_DIGEST_LEN]; + char HA1_hex[2 * MD5_DIGEST_LEN + 1]; + char HA2_hex[2 * MD5_DIGEST_LEN + 1]; + char resp_hash_hex[2 * MD5_DIGEST_LEN + 1]; + char nonce[64]; + char realm[128]; + char algorithm[64]; + char qop_options[64]; + int qop_values; + char cnonce[33]; + unsigned int entropy[4]; + char nonceCount[] = "00000001"; + char method[] = "AUTHENTICATE"; + char qop[] = DIGEST_QOP_VALUE_STRING_AUTH; + char *spn = NULL; + + /* Decode the challange message */ + result = auth_decode_digest_md5_message(chlg64, nonce, sizeof(nonce), + realm, sizeof(realm), + algorithm, sizeof(algorithm), + qop_options, sizeof(qop_options)); + if(result) + return result; + + /* We only support md5 sessions */ + if(strcmp(algorithm, "md5-sess") != 0) + return CURLE_BAD_CONTENT_ENCODING; + + /* Get the qop-values from the qop-options */ + result = auth_digest_get_qop_values(qop_options, &qop_values); + if(result) + return result; + + /* We only support auth quality-of-protection */ + if(!(qop_values & DIGEST_QOP_VALUE_AUTH)) + return CURLE_BAD_CONTENT_ENCODING; + + /* Generate 16 bytes of random data */ + entropy[0] = Curl_rand(data); + entropy[1] = Curl_rand(data); + entropy[2] = Curl_rand(data); + entropy[3] = Curl_rand(data); + + /* Convert the random data into a 32 byte hex string */ + snprintf(cnonce, sizeof(cnonce), "%08x%08x%08x%08x", + entropy[0], entropy[1], entropy[2], entropy[3]); + + /* So far so good, now calculate A1 and H(A1) according to RFC 2831 */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *) userp, + curlx_uztoui(strlen(userp))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) realm, + curlx_uztoui(strlen(realm))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) passwdp, + curlx_uztoui(strlen(passwdp))); + Curl_MD5_final(ctxt, digest); + + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) + return CURLE_OUT_OF_MEMORY; + + Curl_MD5_update(ctxt, (const unsigned char *) digest, MD5_DIGEST_LEN); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) nonce, + curlx_uztoui(strlen(nonce))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) cnonce, + curlx_uztoui(strlen(cnonce))); + Curl_MD5_final(ctxt, digest); + + /* Convert calculated 16 octet hex into 32 bytes string */ + for(i = 0; i < MD5_DIGEST_LEN; i++) + snprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]); + + /* Generate our SPN */ + spn = Curl_auth_build_spn(service, realm, NULL); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Calculate H(A2) */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) { + free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + Curl_MD5_update(ctxt, (const unsigned char *) method, + curlx_uztoui(strlen(method))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) spn, + curlx_uztoui(strlen(spn))); + Curl_MD5_final(ctxt, digest); + + for(i = 0; i < MD5_DIGEST_LEN; i++) + snprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]); + + /* Now calculate the response hash */ + ctxt = Curl_MD5_init(Curl_DIGEST_MD5); + if(!ctxt) { + free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + Curl_MD5_update(ctxt, (const unsigned char *) HA1_hex, 2 * MD5_DIGEST_LEN); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) nonce, + curlx_uztoui(strlen(nonce))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + + Curl_MD5_update(ctxt, (const unsigned char *) nonceCount, + curlx_uztoui(strlen(nonceCount))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) cnonce, + curlx_uztoui(strlen(cnonce))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + Curl_MD5_update(ctxt, (const unsigned char *) qop, + curlx_uztoui(strlen(qop))); + Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); + + Curl_MD5_update(ctxt, (const unsigned char *) HA2_hex, 2 * MD5_DIGEST_LEN); + Curl_MD5_final(ctxt, digest); + + for(i = 0; i < MD5_DIGEST_LEN; i++) + snprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]); + + /* Generate the response */ + response = aprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\"," + "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\",response=%s," + "qop=%s", + userp, realm, nonce, + cnonce, nonceCount, spn, resp_hash_hex, qop); + free(spn); + if(!response) + return CURLE_OUT_OF_MEMORY; + + /* Base64 encode the response */ + result = Curl_base64_encode(data, response, 0, outptr, outlen); + + free(response); + + return result; +} + +/* + * Curl_auth_decode_digest_http_message() + * + * This is used to decode a HTTP DIGEST challenge message into the seperate + * attributes. + * + * Parameters: + * + * chlg [in] - The challenge message. + * digest [in/out] - The digest data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest) +{ + bool before = FALSE; /* got a nonce before */ + bool foundAuth = FALSE; + bool foundAuthInt = FALSE; + char *token = NULL; + char *tmp = NULL; + + /* If we already have received a nonce, keep that in mind */ + if(digest->nonce) + before = TRUE; + + /* Clean up any former leftovers and initialise to defaults */ + Curl_auth_digest_cleanup(digest); + + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + /* Pass all additional spaces here */ + while(*chlg && ISSPACE(*chlg)) + chlg++; + + /* Extract a value=content pair */ + if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { + if(Curl_raw_equal(value, "nonce")) { + free(digest->nonce); + digest->nonce = strdup(content); + if(!digest->nonce) + return CURLE_OUT_OF_MEMORY; + } + else if(Curl_raw_equal(value, "stale")) { + if(Curl_raw_equal(content, "true")) { + digest->stale = TRUE; + digest->nc = 1; /* we make a new nonce now */ + } + } + else if(Curl_raw_equal(value, "realm")) { + free(digest->realm); + digest->realm = strdup(content); + if(!digest->realm) + return CURLE_OUT_OF_MEMORY; + } + else if(Curl_raw_equal(value, "opaque")) { + free(digest->opaque); + digest->opaque = strdup(content); + if(!digest->opaque) + return CURLE_OUT_OF_MEMORY; + } + else if(Curl_raw_equal(value, "qop")) { + char *tok_buf; + /* Tokenize the list and choose auth if possible, use a temporary + clone of the buffer since strtok_r() ruins it */ + tmp = strdup(content); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = strtok_r(tmp, ",", &tok_buf); + while(token != NULL) { + if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH)) { + foundAuth = TRUE; + } + else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) { + foundAuthInt = TRUE; + } + token = strtok_r(NULL, ",", &tok_buf); + } + + free(tmp); + + /* Select only auth or auth-int. Otherwise, ignore */ + if(foundAuth) { + free(digest->qop); + digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH); + if(!digest->qop) + return CURLE_OUT_OF_MEMORY; + } + else if(foundAuthInt) { + free(digest->qop); + digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT); + if(!digest->qop) + return CURLE_OUT_OF_MEMORY; + } + } + else if(Curl_raw_equal(value, "algorithm")) { + free(digest->algorithm); + digest->algorithm = strdup(content); + if(!digest->algorithm) + return CURLE_OUT_OF_MEMORY; + + if(Curl_raw_equal(content, "MD5-sess")) + digest->algo = CURLDIGESTALGO_MD5SESS; + else if(Curl_raw_equal(content, "MD5")) + digest->algo = CURLDIGESTALGO_MD5; + else + return CURLE_BAD_CONTENT_ENCODING; + } + else { + /* Unknown specifier, ignore it! */ + } + } + else + break; /* We're done here */ + + /* Pass all additional spaces here */ + while(*chlg && ISSPACE(*chlg)) + chlg++; + + /* Allow the list to be comma-separated */ + if(',' == *chlg) + chlg++; + } + + /* We had a nonce since before, and we got another one now without + 'stale=true'. This means we provided bad credentials in the previous + request */ + if(before && !digest->stale) + return CURLE_BAD_CONTENT_ENCODING; + + /* We got this header without a nonce, that's a bad Digest line! */ + if(!digest->nonce) + return CURLE_BAD_CONTENT_ENCODING; + + return CURLE_OK; +} + +/* + * Curl_auth_create_digest_http_message() + * + * This is used to generate a HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name. + * passdwp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen) +{ + CURLcode result; + unsigned char md5buf[16]; /* 16 bytes/128 bits */ + unsigned char request_digest[33]; + unsigned char *md5this; + unsigned char ha1[33]; /* 32 digits and 1 zero byte */ + unsigned char ha2[33]; /* 32 digits and 1 zero byte */ + char cnoncebuf[33]; + char *cnonce = NULL; + size_t cnonce_sz = 0; + char *userp_quoted; + char *response = NULL; + char *tmp = NULL; + + if(!digest->nc) + digest->nc = 1; + + if(!digest->cnonce) { + snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x", + Curl_rand(data), Curl_rand(data), + Curl_rand(data), Curl_rand(data)); + + result = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf), + &cnonce, &cnonce_sz); + if(result) + return result; + + digest->cnonce = cnonce; + } + + /* + If the algorithm is "MD5" or unspecified (which then defaults to MD5): + + A1 = unq(username-value) ":" unq(realm-value) ":" passwd + + If the algorithm is "MD5-sess" then: + + A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) ":" + unq(nonce-value) ":" unq(cnonce-value) + */ + + md5this = (unsigned char *) + aprintf("%s:%s:%s", userp, digest->realm, passwdp); + if(!md5this) + return CURLE_OUT_OF_MEMORY; + + CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ + Curl_md5it(md5buf, md5this); + free(md5this); + auth_digest_md5_to_ascii(md5buf, ha1); + + if(digest->algo == CURLDIGESTALGO_MD5SESS) { + /* nonce and cnonce are OUTSIDE the hash */ + tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + CURL_OUTPUT_DIGEST_CONV(data, tmp); /* Convert on non-ASCII machines */ + Curl_md5it(md5buf, (unsigned char *) tmp); + free(tmp); + auth_digest_md5_to_ascii(md5buf, ha1); + } + + /* + If the "qop" directive's value is "auth" or is unspecified, then A2 is: + + A2 = Method ":" digest-uri-value + + If the "qop" value is "auth-int", then A2 is: + + A2 = Method ":" digest-uri-value ":" H(entity-body) + + (The "Method" value is the HTTP request method as specified in section + 5.1.1 of RFC 2616) + */ + + md5this = (unsigned char *) aprintf("%s:%s", request, uripath); + + if(digest->qop && Curl_raw_equal(digest->qop, "auth-int")) { + /* We don't support auth-int for PUT or POST at the moment. + TODO: replace md5 of empty string with entity-body for PUT/POST */ + unsigned char *md5this2 = (unsigned char *) + aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e"); + free(md5this); + md5this = md5this2; + } + + if(!md5this) + return CURLE_OUT_OF_MEMORY; + + CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ + Curl_md5it(md5buf, md5this); + free(md5this); + auth_digest_md5_to_ascii(md5buf, ha2); + + if(digest->qop) { + md5this = (unsigned char *) aprintf("%s:%s:%08x:%s:%s:%s", + ha1, + digest->nonce, + digest->nc, + digest->cnonce, + digest->qop, + ha2); + } + else { + md5this = (unsigned char *) aprintf("%s:%s:%s", + ha1, + digest->nonce, + ha2); + } + + if(!md5this) + return CURLE_OUT_OF_MEMORY; + + CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ + Curl_md5it(md5buf, md5this); + free(md5this); + auth_digest_md5_to_ascii(md5buf, request_digest); + + /* For test case 64 (snooped from a Mozilla 1.3a request) + + Authorization: Digest username="testuser", realm="testrealm", \ + nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" + + Digest parameters are all quoted strings. Username which is provided by + the user will need double quotes and backslashes within it escaped. For + the other fields, this shouldn't be an issue. realm, nonce, and opaque + are copied as is from the server, escapes and all. cnonce is generated + with web-safe characters. uri is already percent encoded. nc is 8 hex + characters. algorithm and qop with standard values only contain web-safe + characters. + */ + userp_quoted = auth_digest_string_quoted(userp); + if(!userp_quoted) + return CURLE_OUT_OF_MEMORY; + + if(digest->qop) { + response = aprintf("username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"%s\", " + "cnonce=\"%s\", " + "nc=%08x, " + "qop=%s, " + "response=\"%s\"", + userp_quoted, + digest->realm, + digest->nonce, + uripath, + digest->cnonce, + digest->nc, + digest->qop, + request_digest); + + if(Curl_raw_equal(digest->qop, "auth")) + digest->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 + padded which tells to the server how many times you are + using the same nonce in the qop=auth mode */ + } + else { + response = aprintf("username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"%s\", " + "response=\"%s\"", + userp_quoted, + digest->realm, + digest->nonce, + uripath, + request_digest); + } + free(userp_quoted); + if(!response) + return CURLE_OUT_OF_MEMORY; + + /* Add the optional fields */ + if(digest->opaque) { + /* Append the opaque */ + tmp = aprintf("%s, opaque=\"%s\"", response, digest->opaque); + free(response); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + response = tmp; + } + + if(digest->algorithm) { + /* Append the algorithm */ + tmp = aprintf("%s, algorithm=\"%s\"", response, digest->algorithm); + free(response); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + response = tmp; + } + + /* Return the output */ + *outptr = response; + *outlen = strlen(response); + + return CURLE_OK; +} + +/* + * Curl_auth_digest_cleanup() + * + * This is used to clean up the digest specific data. + * + * Parameters: + * + * digest [in/out] - The digest data struct being cleaned up. + * + */ +void Curl_auth_digest_cleanup(struct digestdata *digest) +{ + Curl_safefree(digest->nonce); + Curl_safefree(digest->cnonce); + Curl_safefree(digest->realm); + Curl_safefree(digest->opaque); + Curl_safefree(digest->qop); + Curl_safefree(digest->algorithm); + + digest->nc = 0; + digest->algo = CURLDIGESTALGO_MD5; /* default algorithm */ + digest->stale = FALSE; /* default means normal, not stale */ +} +#endif /* !USE_WINDOWS_SSPI */ + +#endif /* CURL_DISABLE_CRYPTO_AUTH */ diff --git a/Utilities/cmcurl/lib/vauth/digest.h b/Utilities/cmcurl/lib/vauth/digest.h new file mode 100644 index 0000000..5722dce --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/digest.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_DIGEST_H +#define HEADER_CURL_DIGEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include <curl/curl.h> + +#if !defined(CURL_DISABLE_CRYPTO_AUTH) + +#define DIGEST_MAX_VALUE_LENGTH 256 +#define DIGEST_MAX_CONTENT_LENGTH 1024 + +enum { + CURLDIGESTALGO_MD5, + CURLDIGESTALGO_MD5SESS +}; + +/* This is used to extract the realm from a challenge message */ +bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, + const char **endptr); + +#endif + +#endif /* HEADER_CURL_DIGEST_H */ diff --git a/Utilities/cmcurl/lib/vauth/digest_sspi.c b/Utilities/cmcurl/lib/vauth/digest_sspi.c new file mode 100644 index 0000000..6a7315e --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/digest_sspi.c @@ -0,0 +1,533 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>. + * Copyright (C) 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC2831 DIGEST-MD5 authentication + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_CRYPTO_AUTH) + +#include <curl/curl.h> + +#include "vauth/vauth.h" +#include "vauth/digest.h" +#include "urldata.h" +#include "curl_base64.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" +#include "strdup.h" +#include "rawstr.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_digest_md5_message() + * + * This is used to generate an already encoded DIGEST-MD5 response message + * ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg64 [in] - The base64 encoded challenge message. + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const char *chlg64, + const char *userp, + const char *passwdp, + const char *service, + char **outptr, size_t *outlen) +{ + CURLcode result = CURLE_OK; + TCHAR *spn = NULL; + size_t chlglen = 0; + size_t token_max = 0; + unsigned char *input_token = NULL; + unsigned char *output_token = NULL; + CredHandle credentials; + CtxtHandle context; + PSecPkgInfo SecurityPackage; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + /* Decode the base-64 encoded challenge message */ + if(strlen(chlg64) && *chlg64 != '=') { + result = Curl_base64_decode(chlg64, &input_token, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!input_token) { + infof(data, "DIGEST-MD5 handshake failure (empty challenge message)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Query the security package for DigestSSP */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + if(status != SEC_E_OK) { + free(input_token); + + return CURLE_NOT_BUILT_IN; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our response buffer */ + output_token = malloc(token_max); + if(!output_token) { + free(input_token); + + return CURLE_OUT_OF_MEMORY; + } + + /* Generate our SPN */ + spn = Curl_auth_build_spn(service, data->easy_conn->host.name, NULL); + if(!spn) { + free(output_token); + free(input_token); + + return CURLE_OUT_OF_MEMORY; + } + + if(userp && *userp) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(userp, passwdp, &identity); + if(result) { + free(spn); + free(output_token); + free(input_token); + + return result; + } + + /* Allow proper cleanup of the identity structure */ + p_identity = &identity; + } + else + /* Use the current Windows user */ + p_identity = NULL; + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT(SP_NAME_DIGEST), + SECPKG_CRED_OUTBOUND, NULL, + p_identity, NULL, NULL, + &credentials, &expiry); + + if(status != SEC_E_OK) { + Curl_sspi_free_identity(p_identity); + free(spn); + free(output_token); + free(input_token); + + return CURLE_LOGIN_DENIED; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = input_token; + chlg_buf.cbBuffer = curlx_uztoul(chlglen); + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = output_token; + resp_buf.cbBuffer = curlx_uztoul(token_max); + + /* Generate our response message */ + status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, spn, + 0, 0, 0, &chlg_desc, 0, + &context, &resp_desc, &attrs, + &expiry); + + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { + s_pSecFn->FreeCredentialsHandle(&credentials); + Curl_sspi_free_identity(p_identity); + free(spn); + free(output_token); + free(input_token); + + return CURLE_RECV_ERROR; + } + + /* Base64 encode the response */ + result = Curl_base64_encode(data, (char *) output_token, resp_buf.cbBuffer, + outptr, outlen); + + /* Free our handles */ + s_pSecFn->DeleteSecurityContext(&context); + s_pSecFn->FreeCredentialsHandle(&credentials); + + /* Free the identity structure */ + Curl_sspi_free_identity(p_identity); + + /* Free the SPN */ + free(spn); + + /* Free the response buffer */ + free(output_token); + + /* Free the decoded challenge message */ + free(input_token); + + return result; +} + +/* + * Curl_override_sspi_http_realm() + * + * This is used to populate the domain in a SSPI identity structure + * The realm is extracted from the challenge message and used as the + * domain if it is not already explicitly set. + * + * Parameters: + * + * chlg [in] - The challenge message. + * identity [in/out] - The identity structure. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_override_sspi_http_realm(const char *chlg, + SEC_WINNT_AUTH_IDENTITY *identity) +{ + xcharp_u domain, dup_domain; + + /* If domain is blank or unset, check challenge message for realm */ + if(!identity->Domain || !identity->DomainLength) { + for(;;) { + char value[DIGEST_MAX_VALUE_LENGTH]; + char content[DIGEST_MAX_CONTENT_LENGTH]; + + /* Pass all additional spaces here */ + while(*chlg && ISSPACE(*chlg)) + chlg++; + + /* Extract a value=content pair */ + if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { + if(Curl_raw_equal(value, "realm")) { + + /* Setup identity's domain and length */ + domain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *) content); + if(!domain.tchar_ptr) + return CURLE_OUT_OF_MEMORY; + + dup_domain.tchar_ptr = _tcsdup(domain.tchar_ptr); + if(!dup_domain.tchar_ptr) { + Curl_unicodefree(domain.tchar_ptr); + return CURLE_OUT_OF_MEMORY; + } + + free(identity->Domain); + identity->Domain = dup_domain.tbyte_ptr; + identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr)); + dup_domain.tchar_ptr = NULL; + + Curl_unicodefree(domain.tchar_ptr); + } + else { + /* Unknown specifier, ignore it! */ + } + } + else + break; /* We're done here */ + + /* Pass all additional spaces here */ + while(*chlg && ISSPACE(*chlg)) + chlg++; + + /* Allow the list to be comma-separated */ + if(',' == *chlg) + chlg++; + } + } + + return CURLE_OK; +} + +/* + * Curl_auth_decode_digest_http_message() + * + * This is used to decode a HTTP DIGEST challenge message into the seperate + * attributes. + * + * Parameters: + * + * chlg [in] - The challenge message. + * digest [in/out] - The digest data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest) +{ + size_t chlglen = strlen(chlg); + + /* We had an input token before and we got another one now. This means we + provided bad credentials in the previous request. */ + if(digest->input_token) + return CURLE_BAD_CONTENT_ENCODING; + + /* Simply store the challenge for use later */ + digest->input_token = (BYTE *) Curl_memdup(chlg, chlglen); + if(!digest->input_token) + return CURLE_OUT_OF_MEMORY; + + digest->input_token_len = chlglen; + + return CURLE_OK; +} + +/* + * Curl_auth_create_digest_http_message() + * + * This is used to generate a HTTP DIGEST response message ready for sending + * to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * request [in] - The HTTP request. + * uripath [in] - The path of the HTTP uri. + * digest [in/out] - The digest data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uripath, + struct digestdata *digest, + char **outptr, size_t *outlen) +{ + size_t token_max; + CredHandle credentials; + CtxtHandle context; + char *resp; + BYTE *output_token; + PSecPkgInfo SecurityPackage; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY *p_identity; + SecBuffer chlg_buf[3]; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + TCHAR *spn; + + (void) data; + + /* Query the security package for DigestSSP */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + if(status != SEC_E_OK) + return CURLE_NOT_BUILT_IN; + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + if(userp && *userp) { + /* Populate our identity structure */ + if(Curl_create_sspi_identity(userp, passwdp, &identity)) + return CURLE_OUT_OF_MEMORY; + + /* Populate our identity domain */ + if(Curl_override_sspi_http_realm((const char*) digest->input_token, + &identity)) + return CURLE_OUT_OF_MEMORY; + + /* Allow proper cleanup of the identity structure */ + p_identity = &identity; + } + else + /* Use the current Windows user */ + p_identity = NULL; + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT(SP_NAME_DIGEST), + SECPKG_CRED_OUTBOUND, NULL, + p_identity, NULL, NULL, + &credentials, &expiry); + if(status != SEC_E_OK) { + Curl_sspi_free_identity(p_identity); + + return CURLE_LOGIN_DENIED; + } + + /* Allocate the output buffer according to the max token size as indicated + by the security package */ + output_token = malloc(token_max); + if(!output_token) { + s_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + + return CURLE_OUT_OF_MEMORY; + } + + /* Setup the challenge "input" security buffer if present */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 3; + chlg_desc.pBuffers = chlg_buf; + chlg_buf[0].BufferType = SECBUFFER_TOKEN; + chlg_buf[0].pvBuffer = digest->input_token; + chlg_buf[0].cbBuffer = curlx_uztoul(digest->input_token_len); + chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[1].pvBuffer = (void *) request; + chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *) request)); + chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; + chlg_buf[2].pvBuffer = NULL; + chlg_buf[2].cbBuffer = 0; + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = output_token; + resp_buf.cbBuffer = curlx_uztoul(token_max); + + spn = Curl_convert_UTF8_to_tchar((char *) uripath); + if(!spn) { + s_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + free(output_token); + + return CURLE_OUT_OF_MEMORY; + } + + /* Generate our reponse message */ + status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, + spn, + ISC_REQ_USE_HTTP_STYLE, 0, 0, + &chlg_desc, 0, &context, + &resp_desc, &attrs, &expiry); + Curl_unicodefree(spn); + + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { + s_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + free(output_token); + + return CURLE_OUT_OF_MEMORY; + } + + resp = malloc(resp_buf.cbBuffer + 1); + if(!resp) { + s_pSecFn->DeleteSecurityContext(&context); + s_pSecFn->FreeCredentialsHandle(&credentials); + + Curl_sspi_free_identity(p_identity); + free(output_token); + + return CURLE_OUT_OF_MEMORY; + } + + /* Copy the generated reponse */ + memcpy(resp, resp_buf.pvBuffer, resp_buf.cbBuffer); + resp[resp_buf.cbBuffer] = 0x00; + + /* Return the response */ + *outptr = resp; + *outlen = resp_buf.cbBuffer; + + /* Free our handles */ + s_pSecFn->DeleteSecurityContext(&context); + s_pSecFn->FreeCredentialsHandle(&credentials); + + /* Free the identity structure */ + Curl_sspi_free_identity(p_identity); + + /* Free the response buffer */ + free(output_token); + + return CURLE_OK; +} + +/* + * Curl_auth_digest_cleanup() + * + * This is used to clean up the digest specific data. + * + * Parameters: + * + * digest [in/out] - The digest data struct being cleaned up. + * + */ +void Curl_auth_digest_cleanup(struct digestdata *digest) +{ + /* Free the input token */ + Curl_safefree(digest->input_token); + + /* Reset any variables */ + digest->input_token_len = 0; +} + +#endif /* USE_WINDOWS_SSPI && !CURL_DISABLE_CRYPTO_AUTH */ diff --git a/Utilities/cmcurl/lib/curl_sasl_gssapi.c b/Utilities/cmcurl/lib/vauth/krb5_gssapi.c index 5fc0e58..31c8c7d 100644 --- a/Utilities/cmcurl/lib/curl_sasl_gssapi.c +++ b/Utilities/cmcurl/lib/vauth/krb5_gssapi.c @@ -5,12 +5,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2014 - 2015, Steve Holme, <steve_holme@hotmail.com>. + * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>. * Copyright (C) 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -29,6 +29,7 @@ #include <curl/curl.h> +#include "vauth/vauth.h" #include "curl_sasl.h" #include "urldata.h" #include "curl_base64.h" @@ -41,25 +42,7 @@ #include "memdebug.h" /* -* Curl_sasl_build_gssapi_spn() -* -* This is used to build a SPN string in the format service@host. -* -* Parameters: -* -* serivce [in] - The service type such as www, smtp, pop or imap. -* host [in] - The host name or realm. -* -* Returns a pointer to the newly allocated SPN. -*/ -char *Curl_sasl_build_gssapi_spn(const char *service, const char *host) -{ - /* Generate and return our SPN */ - return aprintf("%s@%s", service, host); -} - -/* - * Curl_sasl_create_gssapi_user_message() + * Curl_auth_create_gssapi_user_message() * * This is used to generate an already encoded GSSAPI (Kerberos V5) user token * message ready for sending to the recipient. @@ -69,22 +52,24 @@ char *Curl_sasl_build_gssapi_spn(const char *service, const char *host) * data [in] - The session handle. * userp [in] - The user name. * passdwp [in] - The user's password. - * service [in] - The service type such as www, smtp, pop or imap. - * mutual_auth [in] - Flag specifying whether or not mutual authentication + * service [in] - The service type such as http, smtp, pop or imap. + * host [in[ - The host name. + * mutual_auth [in] - Flag specifing whether or not mutual authentication * is enabled. * chlg64 [in] - Pointer to the optional base64 encoded challenge * message. - * krb5 [in/out] - The gssapi data struct being used and modified. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ -CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, + const char *host, const bool mutual_auth, const char *chlg64, struct kerberos5data *krb5, @@ -93,9 +78,9 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, CURLcode result = CURLE_OK; size_t chlglen = 0; unsigned char *chlg = NULL; - OM_uint32 gss_status; - OM_uint32 gss_major_status; - OM_uint32 gss_minor_status; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; @@ -103,10 +88,9 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, (void) userp; (void) passwdp; - if(krb5->context == GSS_C_NO_CONTEXT) { + if(!krb5->spn) { /* Generate our SPN */ - char *spn = Curl_sasl_build_gssapi_spn(service, - data->easy_conn->host.name); + char *spn = Curl_auth_build_spn(service, NULL, host); if(!spn) return CURLE_OUT_OF_MEMORY; @@ -115,10 +99,11 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, spn_token.length = strlen(spn); /* Import the SPN */ - gss_major_status = gss_import_name(&gss_minor_status, &spn_token, - GSS_C_NT_HOSTBASED_SERVICE, &krb5->spn); - if(GSS_ERROR(gss_major_status)) { - Curl_gss_log_error(data, gss_minor_status, "gss_import_name() failed: "); + major_status = gss_import_name(&minor_status, &spn_token, + GSS_C_NT_HOSTBASED_SERVICE, &krb5->spn); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_import_name() failed: ", + major_status, minor_status); free(spn); @@ -127,9 +112,10 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, free(spn); } - else { + + if(chlg64 && *chlg64) { /* Decode the base-64 encoded challenge message */ - if(strlen(chlg64) && *chlg64 != '=') { + if(*chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; @@ -147,25 +133,26 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, input_token.length = chlglen; } - gss_major_status = Curl_gss_init_sec_context(data, - &gss_minor_status, - &krb5->context, - krb5->spn, - &Curl_krb5_mech_oid, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - &output_token, - mutual_auth, - NULL); - + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &krb5->context, + krb5->spn, + &Curl_krb5_mech_oid, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + &output_token, + mutual_auth, + NULL); + + /* Free the decoded challenge as it is not required anymore */ free(input_token.value); - if(GSS_ERROR(gss_major_status)) { + if(GSS_ERROR(major_status)) { if(output_token.value) - gss_release_buffer(&gss_status, &output_token); + gss_release_buffer(&unused_status, &output_token); - Curl_gss_log_error(data, gss_minor_status, - "gss_init_sec_context() failed: "); + Curl_gss_log_error(data, "gss_init_sec_context() failed: ", + major_status, minor_status); return CURLE_RECV_ERROR; } @@ -175,14 +162,19 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, result = Curl_base64_encode(data, (char *) output_token.value, output_token.length, outptr, outlen); - gss_release_buffer(&gss_status, &output_token); + gss_release_buffer(&unused_status, &output_token); + } + else if(mutual_auth) { + *outptr = strdup(""); + if(!*outptr) + result = CURLE_OUT_OF_MEMORY; } return result; } /* - * Curl_sasl_create_gssapi_security_message() + * Curl_auth_create_gssapi_security_message() * * This is used to generate an already encoded GSSAPI (Kerberos V5) security * token message ready for sending to the recipient. @@ -191,14 +183,14 @@ CURLcode Curl_sasl_create_gssapi_user_message(struct SessionHandle *data, * * data [in] - The session handle. * chlg64 [in] - Pointer to the optional base64 encoded challenge message. - * krb5 [in/out] - The gssapi data struct being used and modified. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ -CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, const char *chlg64, struct kerberos5data *krb5, char **outptr, @@ -209,9 +201,9 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, size_t messagelen = 0; unsigned char *chlg = NULL; unsigned char *message = NULL; - OM_uint32 gss_status; - OM_uint32 gss_major_status; - OM_uint32 gss_minor_status; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; unsigned int indata = 0; @@ -237,12 +229,12 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, } /* Get the fully qualified username back from the context */ - gss_major_status = gss_inquire_context(&gss_minor_status, krb5->context, - &username, NULL, NULL, NULL, NULL, - NULL, NULL); - if(GSS_ERROR(gss_major_status)) { - Curl_gss_log_error(data, gss_minor_status, - "gss_inquire_context() failed: "); + major_status = gss_inquire_context(&minor_status, krb5->context, + &username, NULL, NULL, NULL, NULL, + NULL, NULL); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_inquire_context() failed: ", + major_status, minor_status); free(chlg); @@ -250,10 +242,11 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, } /* Convert the username from internal format to a displayable token */ - gss_major_status = gss_display_name(&gss_minor_status, username, - &username_token, NULL); - if(GSS_ERROR(gss_major_status)) { - Curl_gss_log_error(data, gss_minor_status, "gss_display_name() failed: "); + major_status = gss_display_name(&minor_status, username, + &username_token, NULL); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_display_name() failed: ", + major_status, minor_status); free(chlg); @@ -265,12 +258,13 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, input_token.length = chlglen; /* Decrypt the inbound challenge and obtain the qop */ - gss_major_status = gss_unwrap(&gss_minor_status, krb5->context, &input_token, - &output_token, NULL, &qop); - if(GSS_ERROR(gss_major_status)) { - Curl_gss_log_error(data, gss_minor_status, "gss_unwrap() failed: "); + major_status = gss_unwrap(&minor_status, krb5->context, &input_token, + &output_token, NULL, &qop); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_unwrap() failed: ", + major_status, minor_status); - gss_release_buffer(&gss_status, &username_token); + gss_release_buffer(&unused_status, &username_token); free(chlg); return CURLE_BAD_CONTENT_ENCODING; @@ -280,7 +274,7 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, if(output_token.length != 4) { infof(data, "GSSAPI handshake failure (invalid security data)\n"); - gss_release_buffer(&gss_status, &username_token); + gss_release_buffer(&unused_status, &username_token); free(chlg); return CURLE_BAD_CONTENT_ENCODING; @@ -288,7 +282,7 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, /* Copy the data out and free the challenge as it is not required anymore */ memcpy(&indata, output_token.value, 4); - gss_release_buffer(&gss_status, &output_token); + gss_release_buffer(&unused_status, &output_token); free(chlg); /* Extract the security layer */ @@ -296,7 +290,7 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, if(!(sec_layer & GSSAUTH_P_NONE)) { infof(data, "GSSAPI handshake failure (invalid security layer)\n"); - gss_release_buffer(&gss_status, &username_token); + gss_release_buffer(&unused_status, &username_token); return CURLE_BAD_CONTENT_ENCODING; } @@ -314,14 +308,14 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, messagelen = sizeof(outdata) + username_token.length + 1; message = malloc(messagelen); if(!message) { - gss_release_buffer(&gss_status, &username_token); + gss_release_buffer(&unused_status, &username_token); return CURLE_OUT_OF_MEMORY; } /* Populate the message with the security layer, client supported receive message size and authorization identity including the 0x00 based - terminator. Note: Dispite RFC4752 Section 3.1 stating "The authorization + terminator. Note: Despite RFC4752 Section 3.1 stating "The authorization identity is not terminated with the zero-valued (%x00) octet." it seems necessary to include it. */ outdata = htonl(max_size) | sec_layer; @@ -331,18 +325,19 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, message[messagelen - 1] = '\0'; /* Free the username token as it is not required anymore */ - gss_release_buffer(&gss_status, &username_token); + gss_release_buffer(&unused_status, &username_token); /* Setup the "authentication data" security buffer */ input_token.value = message; input_token.length = messagelen; /* Encrypt the data */ - gss_major_status = gss_wrap(&gss_minor_status, krb5->context, 0, - GSS_C_QOP_DEFAULT, &input_token, NULL, - &output_token); - if(GSS_ERROR(gss_major_status)) { - Curl_gss_log_error(data, gss_minor_status, "gss_wrap() failed: "); + major_status = gss_wrap(&minor_status, krb5->context, 0, + GSS_C_QOP_DEFAULT, &input_token, NULL, + &output_token); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_wrap() failed: ", + major_status, minor_status); free(message); @@ -354,7 +349,7 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, output_token.length, outptr, outlen); /* Free the output buffer */ - gss_release_buffer(&gss_status, &output_token); + gss_release_buffer(&unused_status, &output_token); /* Free the message buffer */ free(message); @@ -363,16 +358,16 @@ CURLcode Curl_sasl_create_gssapi_security_message(struct SessionHandle *data, } /* - * Curl_sasl_gssapi_cleanup() + * Curl_auth_gssapi_cleanup() * - * This is used to clean up the gssapi specific data. + * This is used to clean up the GSSAPI (Kerberos V5) specific data. * * Parameters: * - * krb5 [in/out] - The kerberos 5 data struct being cleaned up. + * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. * */ -void Curl_sasl_gssapi_cleanup(struct kerberos5data *krb5) +void Curl_auth_gssapi_cleanup(struct kerberos5data *krb5) { OM_uint32 minor_status; diff --git a/Utilities/cmcurl/lib/vauth/krb5_sspi.c b/Utilities/cmcurl/lib/vauth/krb5_sspi.c new file mode 100644 index 0000000..08774f6 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/krb5_sspi.c @@ -0,0 +1,496 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_KERBEROS5) + +#include <curl/curl.h> + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_base64.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_gssapi_user_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) user token + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * mutual_auth [in] - Flag specifing whether or not mutual authentication + * is enabled. + * chlg64 [in] - The optional base64 encoded challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + const bool mutual_auth, + const char *chlg64, + struct kerberos5data *krb5, + char **outptr, size_t *outlen) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + CtxtHandle context; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + if(!krb5->spn) { + /* Generate our SPN */ + krb5->spn = Curl_auth_build_spn(service, host, NULL); + if(!krb5->spn) + return CURLE_OUT_OF_MEMORY; + } + + if(!krb5->output_token) { + /* Query the security package for Kerberos */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_KERBEROS), + &SecurityPackage); + if(status != SEC_E_OK) { + return CURLE_NOT_BUILT_IN; + } + + krb5->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our response buffer */ + krb5->output_token = malloc(krb5->token_max); + if(!krb5->output_token) + return CURLE_OUT_OF_MEMORY; + } + + if(!krb5->credentials) { + /* Do we have credientials to use or are we using single sign-on? */ + if(userp && *userp) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(userp, passwdp, &krb5->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + krb5->p_identity = &krb5->identity; + } + else + /* Use the current Windows user */ + krb5->p_identity = NULL; + + /* Allocate our credentials handle */ + krb5->credentials = malloc(sizeof(CredHandle)); + if(!krb5->credentials) + return CURLE_OUT_OF_MEMORY; + + memset(krb5->credentials, 0, sizeof(CredHandle)); + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) + TEXT(SP_NAME_KERBEROS), + SECPKG_CRED_OUTBOUND, NULL, + krb5->p_identity, NULL, NULL, + krb5->credentials, &expiry); + if(status != SEC_E_OK) + return CURLE_LOGIN_DENIED; + + /* Allocate our new context handle */ + krb5->context = malloc(sizeof(CtxtHandle)); + if(!krb5->context) + return CURLE_OUT_OF_MEMORY; + + memset(krb5->context, 0, sizeof(CtxtHandle)); + } + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "GSSAPI handshake failure (empty challenge message)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = chlg; + chlg_buf.cbBuffer = curlx_uztoul(chlglen); + } + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = krb5->output_token; + resp_buf.cbBuffer = curlx_uztoul(krb5->token_max); + + /* Generate our challenge-response message */ + status = s_pSecFn->InitializeSecurityContext(krb5->credentials, + chlg ? krb5->context : NULL, + krb5->spn, + (mutual_auth ? + ISC_REQ_MUTUAL_AUTH : 0), + 0, SECURITY_NATIVE_DREP, + chlg ? &chlg_desc : NULL, 0, + &context, + &resp_desc, &attrs, + &expiry); + + /* Free the decoded challenge as it is not required anymore */ + free(chlg); + + if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { + return CURLE_RECV_ERROR; + } + + if(memcmp(&context, krb5->context, sizeof(context))) { + s_pSecFn->DeleteSecurityContext(krb5->context); + + memcpy(krb5->context, &context, sizeof(context)); + } + + if(resp_buf.cbBuffer) { + /* Base64 encode the response */ + result = Curl_base64_encode(data, (char *) resp_buf.pvBuffer, + resp_buf.cbBuffer, outptr, outlen); + } + else if(mutual_auth) { + *outptr = strdup(""); + if(!*outptr) + result = CURLE_OUT_OF_MEMORY; + } + + return result; +} + +/* + * Curl_auth_create_gssapi_security_message() + * + * This is used to generate an already encoded GSSAPI (Kerberos V5) security + * token message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * chlg64 [in] - The optional base64 encoded challenge message. + * krb5 [in/out] - The Kerberos 5 data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *chlg64, + struct kerberos5data *krb5, + char **outptr, + size_t *outlen) +{ + CURLcode result = CURLE_OK; + size_t offset = 0; + size_t chlglen = 0; + size_t messagelen = 0; + size_t appdatalen = 0; + unsigned char *chlg = NULL; + unsigned char *trailer = NULL; + unsigned char *message = NULL; + unsigned char *padding = NULL; + unsigned char *appdata = NULL; + SecBuffer input_buf[2]; + SecBuffer wrap_buf[3]; + SecBufferDesc input_desc; + SecBufferDesc wrap_desc; + unsigned long indata = 0; + unsigned long outdata = 0; + unsigned long qop = 0; + unsigned long sec_layer = 0; + unsigned long max_size = 0; + SecPkgContext_Sizes sizes; + SecPkgCredentials_Names names; + SECURITY_STATUS status; + char *user_name; + + /* Decode the base-64 encoded input message */ + if(strlen(chlg64) && *chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "GSSAPI handshake failure (empty security message)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Get our response size information */ + status = s_pSecFn->QueryContextAttributes(krb5->context, + SECPKG_ATTR_SIZES, + &sizes); + if(status != SEC_E_OK) { + free(chlg); + + return CURLE_OUT_OF_MEMORY; + } + + /* Get the fully qualified username back from the context */ + status = s_pSecFn->QueryCredentialsAttributes(krb5->credentials, + SECPKG_CRED_ATTR_NAMES, + &names); + if(status != SEC_E_OK) { + free(chlg); + + return CURLE_RECV_ERROR; + } + + /* Setup the "input" security buffer */ + input_desc.ulVersion = SECBUFFER_VERSION; + input_desc.cBuffers = 2; + input_desc.pBuffers = input_buf; + input_buf[0].BufferType = SECBUFFER_STREAM; + input_buf[0].pvBuffer = chlg; + input_buf[0].cbBuffer = curlx_uztoul(chlglen); + input_buf[1].BufferType = SECBUFFER_DATA; + input_buf[1].pvBuffer = NULL; + input_buf[1].cbBuffer = 0; + + /* Decrypt the inbound challenge and obtain the qop */ + status = s_pSecFn->DecryptMessage(krb5->context, &input_desc, 0, &qop); + if(status != SEC_E_OK) { + infof(data, "GSSAPI handshake failure (empty security message)\n"); + + free(chlg); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ + if(input_buf[1].cbBuffer != 4) { + infof(data, "GSSAPI handshake failure (invalid security data)\n"); + + free(chlg); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Copy the data out and free the challenge as it is not required anymore */ + memcpy(&indata, input_buf[1].pvBuffer, 4); + s_pSecFn->FreeContextBuffer(input_buf[1].pvBuffer); + free(chlg); + + /* Extract the security layer */ + sec_layer = indata & 0x000000FF; + if(!(sec_layer & KERB_WRAP_NO_ENCRYPT)) { + infof(data, "GSSAPI handshake failure (invalid security layer)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Extract the maximum message size the server can receive */ + max_size = ntohl(indata & 0xFFFFFF00); + if(max_size > 0) { + /* The server has told us it supports a maximum receive buffer, however, as + we don't require one unless we are encrypting data, we tell the server + our receive buffer is zero. */ + max_size = 0; + } + + /* Allocate the trailer */ + trailer = malloc(sizes.cbSecurityTrailer); + if(!trailer) + return CURLE_OUT_OF_MEMORY; + + /* Convert the user name to UTF8 when operating with Unicode */ + user_name = Curl_convert_tchar_to_UTF8(names.sUserName); + if(!user_name) { + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Allocate our message */ + messagelen = sizeof(outdata) + strlen(user_name) + 1; + message = malloc(messagelen); + if(!message) { + free(trailer); + Curl_unicodefree(user_name); + + return CURLE_OUT_OF_MEMORY; + } + + /* Populate the message with the security layer, client supported receive + message size and authorization identity including the 0x00 based + terminator. Note: Despite RFC4752 Section 3.1 stating "The authorization + identity is not terminated with the zero-valued (%x00) octet." it seems + necessary to include it. */ + outdata = htonl(max_size) | sec_layer; + memcpy(message, &outdata, sizeof(outdata)); + strcpy((char *) message + sizeof(outdata), user_name); + Curl_unicodefree(user_name); + + /* Allocate the padding */ + padding = malloc(sizes.cbBlockSize); + if(!padding) { + free(message); + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Setup the "authentication data" security buffer */ + wrap_desc.ulVersion = SECBUFFER_VERSION; + wrap_desc.cBuffers = 3; + wrap_desc.pBuffers = wrap_buf; + wrap_buf[0].BufferType = SECBUFFER_TOKEN; + wrap_buf[0].pvBuffer = trailer; + wrap_buf[0].cbBuffer = sizes.cbSecurityTrailer; + wrap_buf[1].BufferType = SECBUFFER_DATA; + wrap_buf[1].pvBuffer = message; + wrap_buf[1].cbBuffer = curlx_uztoul(messagelen); + wrap_buf[2].BufferType = SECBUFFER_PADDING; + wrap_buf[2].pvBuffer = padding; + wrap_buf[2].cbBuffer = sizes.cbBlockSize; + + /* Encrypt the data */ + status = s_pSecFn->EncryptMessage(krb5->context, KERB_WRAP_NO_ENCRYPT, + &wrap_desc, 0); + if(status != SEC_E_OK) { + free(padding); + free(message); + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Allocate the encryption (wrap) buffer */ + appdatalen = wrap_buf[0].cbBuffer + wrap_buf[1].cbBuffer + + wrap_buf[2].cbBuffer; + appdata = malloc(appdatalen); + if(!appdata) { + free(padding); + free(message); + free(trailer); + + return CURLE_OUT_OF_MEMORY; + } + + /* Populate the encryption buffer */ + memcpy(appdata, wrap_buf[0].pvBuffer, wrap_buf[0].cbBuffer); + offset += wrap_buf[0].cbBuffer; + memcpy(appdata + offset, wrap_buf[1].pvBuffer, wrap_buf[1].cbBuffer); + offset += wrap_buf[1].cbBuffer; + memcpy(appdata + offset, wrap_buf[2].pvBuffer, wrap_buf[2].cbBuffer); + + /* Base64 encode the response */ + result = Curl_base64_encode(data, (char *) appdata, appdatalen, outptr, + outlen); + + /* Free all of our local buffers */ + free(appdata); + free(padding); + free(message); + free(trailer); + + return result; +} + +/* + * Curl_auth_gssapi_cleanup() + * + * This is used to clean up the GSSAPI (Kerberos V5) specific data. + * + * Parameters: + * + * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. + * + */ +void Curl_auth_gssapi_cleanup(struct kerberos5data *krb5) +{ + /* Free our security context */ + if(krb5->context) { + s_pSecFn->DeleteSecurityContext(krb5->context); + free(krb5->context); + krb5->context = NULL; + } + + /* Free our credentials handle */ + if(krb5->credentials) { + s_pSecFn->FreeCredentialsHandle(krb5->credentials); + free(krb5->credentials); + krb5->credentials = NULL; + } + + /* Free our identity */ + Curl_sspi_free_identity(krb5->p_identity); + krb5->p_identity = NULL; + + /* Free the SPN and output token */ + Curl_safefree(krb5->spn); + Curl_safefree(krb5->output_token); + + /* Reset any variables */ + krb5->token_max = 0; +} + +#endif /* USE_WINDOWS_SSPI && USE_KERBEROS5*/ diff --git a/Utilities/cmcurl/lib/curl_ntlm_msgs.c b/Utilities/cmcurl/lib/vauth/ntlm.c index 7f07dec..c85fe42 100644 --- a/Utilities/cmcurl/lib/curl_ntlm_msgs.c +++ b/Utilities/cmcurl/lib/vauth/ntlm.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,7 +28,7 @@ * NTLM details: * * http://davenport.sourceforge.net/ntlm.html - * http://www.innovation.ch/java/ntlm.html + * https://www.innovation.ch/java/ntlm.html */ #define DEBUG_ME 0 @@ -49,8 +49,8 @@ #endif #define BUILDING_CURL_NTLM_MSGS_C -#include "curl_ntlm_msgs.h" -#include "curl_sasl.h" +#include "vauth/vauth.h" +#include "vauth/ntlm.h" #include "curl_endian.h" #include "curl_printf.h" @@ -138,7 +138,9 @@ static void ntlm_print_flags(FILE *handle, unsigned long flags) static void ntlm_print_hex(FILE *handle, const char *buf, size_t len) { const char *p = buf; - (void)handle; + + (void) handle; + fprintf(stderr, "0x"); while(len-- > 0) fprintf(stderr, "%02.2x", (unsigned int)*p++); @@ -150,7 +152,7 @@ static void ntlm_print_hex(FILE *handle, const char *buf, size_t len) /* * ntlm_decode_type2_target() * - * This is used to decode the "target info" in the ntlm type-2 message + * This is used to decode the "target info" in the NTLM type-2 message * received. * * Parameters: @@ -158,11 +160,11 @@ static void ntlm_print_hex(FILE *handle, const char *buf, size_t len) * data [in] - The session handle. * buffer [in] - The decoded type-2 message. * size [in] - The input buffer size, at least 32 bytes. - * ntlm [in/out] - The ntlm data struct being used and modified. + * ntlm [in/out] - The NTLM data struct being used and modified. * * Returns CURLE_OK on success. */ -static CURLcode ntlm_decode_type2_target(struct SessionHandle *data, +static CURLcode ntlm_decode_type2_target(struct Curl_easy *data, unsigned char *buffer, size_t size, struct ntlmdata *ntlm) @@ -170,6 +172,10 @@ static CURLcode ntlm_decode_type2_target(struct SessionHandle *data, unsigned short target_info_len = 0; unsigned int target_info_offset = 0; +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + if(size >= 48) { target_info_len = Curl_read16_le(&buffer[40]); target_info_offset = Curl_read32_le(&buffer[44]); @@ -211,7 +217,7 @@ static CURLcode ntlm_decode_type2_target(struct SessionHandle *data, */ /* - * Curl_sasl_decode_ntlm_type2_message() + * Curl_auth_decode_ntlm_type2_message() * * This is used to decode an already encoded NTLM type-2 message. The message * is first decoded from a base64 string into a raw NTLM message and checked @@ -222,11 +228,11 @@ static CURLcode ntlm_decode_type2_target(struct SessionHandle *data, * * data [in] - The session handle. * type2msg [in] - The base64 encoded type-2 message. - * ntlm [in/out] - The ntlm data struct being used and modified. + * ntlm [in/out] - The NTLM data struct being used and modified. * * Returns CURLE_OK on success. */ -CURLcode Curl_sasl_decode_ntlm_type2_message(struct SessionHandle *data, +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, const char *type2msg, struct ntlmdata *ntlm) { @@ -323,7 +329,7 @@ static void unicodecpy(unsigned char *dest, const char *src, size_t length) } /* - * Curl_sasl_create_ntlm_type1_message() + * Curl_auth_create_ntlm_type1_message() * * This is used to generate an already encoded NTLM type-1 message ready for * sending to the recipient using the appropriate compile time crypto API. @@ -332,14 +338,14 @@ static void unicodecpy(unsigned char *dest, const char *src, size_t length) * * userp [in] - The user name in the format User or Domain\User. * passdwp [in] - The user's password. - * ntlm [in/out] - The ntlm data struct being used and modified. + * ntlm [in/out] - The NTLM data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ -CURLcode Curl_sasl_create_ntlm_type1_message(const char *userp, +CURLcode Curl_auth_create_ntlm_type1_message(const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen) @@ -372,7 +378,7 @@ CURLcode Curl_sasl_create_ntlm_type1_message(const char *userp, (void)passwdp; /* Clean up any former leftovers and initialise to defaults */ - Curl_sasl_ntlm_cleanup(ntlm); + Curl_auth_ntlm_cleanup(ntlm); #if USE_NTRESPONSES && USE_NTLM2SESSION #define NTLM2FLAG NTLMFLAG_NEGOTIATE_NTLM2_KEY @@ -442,7 +448,7 @@ CURLcode Curl_sasl_create_ntlm_type1_message(const char *userp, } /* - * Curl_sasl_create_ntlm_type3_message() + * Curl_auth_create_ntlm_type3_message() * * This is used to generate an already encoded NTLM type-3 message ready for * sending to the recipient using the appropriate compile time crypto API. @@ -452,14 +458,14 @@ CURLcode Curl_sasl_create_ntlm_type1_message(const char *userp, * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passdwp [in] - The user's password. - * ntlm [in/out] - The ntlm data struct being used and modified. + * ntlm [in/out] - The NTLM data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ -CURLcode Curl_sasl_create_ntlm_type3_message(struct SessionHandle *data, +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, const char *userp, const char *passwdp, struct ntlmdata *ntlm, @@ -809,9 +815,28 @@ CURLcode Curl_sasl_create_ntlm_type3_message(struct SessionHandle *data, /* Return with binary blob encoded into base64 */ result = Curl_base64_encode(NULL, (char *)ntlmbuf, size, outptr, outlen); - Curl_sasl_ntlm_cleanup(ntlm); + Curl_auth_ntlm_cleanup(ntlm); return result; } +/* +* Curl_auth_ntlm_cleanup() +* +* This is used to clean up the NTLM specific data. +* +* Parameters: +* +* ntlm [in/out] - The NTLM data struct being cleaned up. +* +*/ +void Curl_auth_ntlm_cleanup(struct ntlmdata *ntlm) +{ + /* Free the target info */ + Curl_safefree(ntlm->target_info); + + /* Reset any variables */ + ntlm->target_info_len = 0; +} + #endif /* USE_NTLM && !USE_WINDOWS_SSPI */ diff --git a/Utilities/cmcurl/lib/curl_ntlm_msgs.h b/Utilities/cmcurl/lib/vauth/ntlm.h index 2a71431..b14e7a5 100644 --- a/Utilities/cmcurl/lib/curl_ntlm_msgs.h +++ b/Utilities/cmcurl/lib/vauth/ntlm.h @@ -1,5 +1,5 @@ -#ifndef HEADER_CURL_NTLM_MSGS_H -#define HEADER_CURL_NTLM_MSGS_H +#ifndef HEADER_CURL_NTLM_H +#define HEADER_CURL_NTLM_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -140,4 +140,4 @@ #endif /* USE_NTLM */ -#endif /* HEADER_CURL_NTLM_MSGS_H */ +#endif /* HEADER_CURL_NTLM_H */ diff --git a/Utilities/cmcurl/lib/vauth/ntlm_sspi.c b/Utilities/cmcurl/lib/vauth/ntlm_sspi.c new file mode 100644 index 0000000..982a9d3 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/ntlm_sspi.c @@ -0,0 +1,314 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_NTLM) + +#include <curl/curl.h> + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_base64.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_ntlm_type1_message() + * + * This is used to generate an already encoded NTLM type-1 message ready for + * sending to the recipient. + * + * Parameters: + * + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * ntlm [in/out] - The NTLM data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type1_message(const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + char **outptr, size_t *outlen) +{ + PSecPkgInfo SecurityPackage; + SecBuffer type_1_buf; + SecBufferDesc type_1_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + /* Clean up any former leftovers and initialise to defaults */ + Curl_auth_ntlm_cleanup(ntlm); + + /* Query the security package for NTLM */ + status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), + &SecurityPackage); + if(status != SEC_E_OK) + return CURLE_NOT_BUILT_IN; + + ntlm->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our output buffer */ + ntlm->output_token = malloc(ntlm->token_max); + if(!ntlm->output_token) + return CURLE_OUT_OF_MEMORY; + + if(userp && *userp) { + CURLcode result; + + /* Populate our identity structure */ + result = Curl_create_sspi_identity(userp, passwdp, &ntlm->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + ntlm->p_identity = &ntlm->identity; + } + else + /* Use the current Windows user */ + ntlm->p_identity = NULL; + + /* Allocate our credentials handle */ + ntlm->credentials = malloc(sizeof(CredHandle)); + if(!ntlm->credentials) + return CURLE_OUT_OF_MEMORY; + + memset(ntlm->credentials, 0, sizeof(CredHandle)); + + /* Acquire our credentials handle */ + status = s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *) TEXT(SP_NAME_NTLM), + SECPKG_CRED_OUTBOUND, NULL, + ntlm->p_identity, NULL, NULL, + ntlm->credentials, &expiry); + if(status != SEC_E_OK) + return CURLE_LOGIN_DENIED; + + /* Allocate our new context handle */ + ntlm->context = malloc(sizeof(CtxtHandle)); + if(!ntlm->context) + return CURLE_OUT_OF_MEMORY; + + memset(ntlm->context, 0, sizeof(CtxtHandle)); + + /* Setup the type-1 "output" security buffer */ + type_1_desc.ulVersion = SECBUFFER_VERSION; + type_1_desc.cBuffers = 1; + type_1_desc.pBuffers = &type_1_buf; + type_1_buf.BufferType = SECBUFFER_TOKEN; + type_1_buf.pvBuffer = ntlm->output_token; + type_1_buf.cbBuffer = curlx_uztoul(ntlm->token_max); + + /* Generate our type-1 message */ + status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, NULL, + (TCHAR *) TEXT(""), + 0, 0, SECURITY_NETWORK_DREP, + NULL, 0, + ntlm->context, &type_1_desc, + &attrs, &expiry); + if(status == SEC_I_COMPLETE_NEEDED || + status == SEC_I_COMPLETE_AND_CONTINUE) + s_pSecFn->CompleteAuthToken(ntlm->context, &type_1_desc); + else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) + return CURLE_RECV_ERROR; + + /* Base64 encode the response */ + return Curl_base64_encode(NULL, (char *) ntlm->output_token, + type_1_buf.cbBuffer, outptr, outlen); +} + +/* + * Curl_auth_decode_ntlm_type2_message() + * + * This is used to decode an already encoded NTLM type-2 message. + * + * Parameters: + * + * data [in] - The session handle. + * type2msg [in] - The base64 encoded type-2 message. + * ntlm [in/out] - The NTLM data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const char *type2msg, + struct ntlmdata *ntlm) +{ + CURLcode result = CURLE_OK; + unsigned char *type2 = NULL; + size_t type2_len = 0; + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + /* Decode the base-64 encoded type-2 message */ + if(strlen(type2msg) && *type2msg != '=') { + result = Curl_base64_decode(type2msg, &type2, &type2_len); + if(result) + return result; + } + + /* Ensure we have a valid type-2 message */ + if(!type2) { + infof(data, "NTLM handshake failure (empty type-2 message)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Simply store the challenge for use later */ + ntlm->input_token = type2; + ntlm->input_token_len = type2_len; + + return result; +} + +/* +* Curl_auth_create_ntlm_type3_message() + * Curl_auth_create_ntlm_type3_message() + * + * This is used to generate an already encoded NTLM type-3 message ready for + * sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * ntlm [in/out] - The NTLM data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + char **outptr, size_t *outlen) +{ + CURLcode result = CURLE_OK; + SecBuffer type_2_buf; + SecBuffer type_3_buf; + SecBufferDesc type_2_desc; + SecBufferDesc type_3_desc; + SECURITY_STATUS status; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + + (void) passwdp; + (void) userp; + + /* Setup the type-2 "input" security buffer */ + type_2_desc.ulVersion = SECBUFFER_VERSION; + type_2_desc.cBuffers = 1; + type_2_desc.pBuffers = &type_2_buf; + type_2_buf.BufferType = SECBUFFER_TOKEN; + type_2_buf.pvBuffer = ntlm->input_token; + type_2_buf.cbBuffer = curlx_uztoul(ntlm->input_token_len); + + /* Setup the type-3 "output" security buffer */ + type_3_desc.ulVersion = SECBUFFER_VERSION; + type_3_desc.cBuffers = 1; + type_3_desc.pBuffers = &type_3_buf; + type_3_buf.BufferType = SECBUFFER_TOKEN; + type_3_buf.pvBuffer = ntlm->output_token; + type_3_buf.cbBuffer = curlx_uztoul(ntlm->token_max); + + /* Generate our type-3 message */ + status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, + ntlm->context, + (TCHAR *) TEXT(""), + 0, 0, SECURITY_NETWORK_DREP, + &type_2_desc, + 0, ntlm->context, + &type_3_desc, + &attrs, &expiry); + if(status != SEC_E_OK) { + infof(data, "NTLM handshake failure (type-3 message): Status=%x\n", + status); + + return CURLE_RECV_ERROR; + } + + /* Base64 encode the response */ + result = Curl_base64_encode(data, (char *) ntlm->output_token, + type_3_buf.cbBuffer, outptr, outlen); + + Curl_auth_ntlm_cleanup(ntlm); + + return result; +} + +/* + * Curl_auth_ntlm_cleanup() + * + * This is used to clean up the NTLM specific data. + * + * Parameters: + * + * ntlm [in/out] - The NTLM data struct being cleaned up. + * + */ +void Curl_auth_ntlm_cleanup(struct ntlmdata *ntlm) +{ + /* Free our security context */ + if(ntlm->context) { + s_pSecFn->DeleteSecurityContext(ntlm->context); + free(ntlm->context); + ntlm->context = NULL; + } + + /* Free our credentials handle */ + if(ntlm->credentials) { + s_pSecFn->FreeCredentialsHandle(ntlm->credentials); + free(ntlm->credentials); + ntlm->credentials = NULL; + } + + /* Free our identity */ + Curl_sspi_free_identity(ntlm->p_identity); + ntlm->p_identity = NULL; + + /* Free the input and output tokens */ + Curl_safefree(ntlm->input_token); + Curl_safefree(ntlm->output_token); + + /* Reset any variables */ + ntlm->token_max = 0; +} + +#endif /* USE_WINDOWS_SSPI && USE_NTLM */ diff --git a/Utilities/cmcurl/lib/vauth/oauth2.c b/Utilities/cmcurl/lib/vauth/oauth2.c new file mode 100644 index 0000000..6288f89 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/oauth2.c @@ -0,0 +1,86 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC6749 OAuth 2.0 Authorization Framework + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include <curl/curl.h> +#include "urldata.h" + +#include "vauth/vauth.h" +#include "curl_base64.h" +#include "warnless.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_create_oauth_bearer_message() + * + * This is used to generate an already encoded OAuth 2.0 message ready for + * sending to the recipient. + * + * Parameters: + * + * data[in] - The session handle. + * user[in] - The user name. + * host[in] - The host name(for OAUTHBEARER). + * port[in] - The port(for OAUTHBEARER when not Port 80). + * bearer[in] - The bearer token. + * outptr[in / out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen[out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_easy *data, + const char *user, + const char *host, + const long port, + const char *bearer, + char **outptr, size_t *outlen) +{ + CURLcode result = CURLE_OK; + char *oauth = NULL; + + /* Generate the message */ + if(host == NULL && (port == 0 || port == 80)) + oauth = aprintf("user=%s\1auth=Bearer %s\1\1", user, bearer); + else if(port == 0 || port == 80) + oauth = aprintf("user=%s\1host=%s\1auth=Bearer %s\1\1", user, host, + bearer); + else + oauth = aprintf("user=%s\1host=%s\1port=%ld\1auth=Bearer %s\1\1", user, + host, port, bearer); + if(!oauth) + return CURLE_OUT_OF_MEMORY; + + /* Base64 encode the reply */ + result = Curl_base64_encode(data, oauth, strlen(oauth), outptr, outlen); + + free(oauth); + + return result; +} diff --git a/Utilities/cmcurl/lib/vauth/spnego_gssapi.c b/Utilities/cmcurl/lib/vauth/spnego_gssapi.c new file mode 100644 index 0000000..b256ee6 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/spnego_gssapi.c @@ -0,0 +1,260 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC4178 Simple and Protected GSS-API Negotiation Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && defined(USE_SPNEGO) + +#include <curl/curl.h> + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_base64.h" +#include "curl_gssapi.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_decode_spnego_message() + * + * This is used to decode an already encoded SPNEGO (Negotiate) challenge + * message. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * chlg64 [in] - The optional base64 encoded challenge message. + * nego [in/out] - The Negotiate data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + const char *user, + const char *password, + const char *service, + const char *host, + const char *chlg64, + struct negotiatedata *nego) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + OM_uint32 major_status; + OM_uint32 minor_status; + OM_uint32 unused_status; + gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + + (void) user; + (void) password; + + if(nego->context && nego->status == GSS_S_COMPLETE) { + /* We finished successfully our part of authentication, but server + * rejected it (since we're again here). Exit with an error since we + * can't invent anything better */ + Curl_auth_spnego_cleanup(nego); + return CURLE_LOGIN_DENIED; + } + + if(!nego->spn) { + /* Generate our SPN */ + char *spn = Curl_auth_build_spn(service, NULL, host); + if(!spn) + return CURLE_OUT_OF_MEMORY; + + /* Populate the SPN structure */ + spn_token.value = spn; + spn_token.length = strlen(spn); + + /* Import the SPN */ + major_status = gss_import_name(&minor_status, &spn_token, + GSS_C_NT_HOSTBASED_SERVICE, + &nego->spn); + if(GSS_ERROR(major_status)) { + Curl_gss_log_error(data, "gss_import_name() failed: ", + major_status, minor_status); + + free(spn); + + return CURLE_OUT_OF_MEMORY; + } + + free(spn); + } + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "SPNEGO handshake failure (empty challenge message)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + input_token.value = chlg; + input_token.length = chlglen; + } + + /* Generate our challenge-response message */ + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &nego->context, + nego->spn, + &Curl_spnego_mech_oid, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + &output_token, + TRUE, + NULL); + + /* Free the decoded challenge as it is not required anymore */ + Curl_safefree(input_token.value); + + nego->status = major_status; + if(GSS_ERROR(major_status)) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + Curl_gss_log_error(data, "gss_init_sec_context() failed: ", + major_status, minor_status); + + return CURLE_OUT_OF_MEMORY; + } + + if(!output_token.value || !output_token.length) { + if(output_token.value) + gss_release_buffer(&unused_status, &output_token); + + return CURLE_OUT_OF_MEMORY; + } + + nego->output_token = output_token; + + return CURLE_OK; +} + +/* + * Curl_auth_create_spnego_message() + * + * This is used to generate an already encoded SPNEGO (Negotiate) response + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * nego [in/out] - The Negotiate data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data, + struct negotiatedata *nego, + char **outptr, size_t *outlen) +{ + CURLcode result; + OM_uint32 minor_status; + + /* Base64 encode the already generated response */ + result = Curl_base64_encode(data, + nego->output_token.value, + nego->output_token.length, + outptr, outlen); + + if(result) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + return result; + } + + if(!*outptr || !*outlen) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + return CURLE_REMOTE_ACCESS_DENIED; + } + + return CURLE_OK; +} + +/* + * Curl_auth_spnego_cleanup() + * + * This is used to clean up the SPNEGO (Negotiate) specific data. + * + * Parameters: + * + * nego [in/out] - The Negotiate data struct being cleaned up. + * + */ +void Curl_auth_spnego_cleanup(struct negotiatedata *nego) +{ + OM_uint32 minor_status; + + /* Free our security context */ + if(nego->context != GSS_C_NO_CONTEXT) { + gss_delete_sec_context(&minor_status, &nego->context, GSS_C_NO_BUFFER); + nego->context = GSS_C_NO_CONTEXT; + } + + /* Free the output token */ + if(nego->output_token.value) { + gss_release_buffer(&minor_status, &nego->output_token); + nego->output_token.value = NULL; + nego->output_token.length = 0; + + } + + /* Free the SPN */ + if(nego->spn != GSS_C_NO_NAME) { + gss_release_name(&minor_status, &nego->spn); + nego->spn = GSS_C_NO_NAME; + } + + /* Reset any variables */ + nego->status = 0; +} + +#endif /* HAVE_GSSAPI && USE_SPNEGO */ diff --git a/Utilities/cmcurl/lib/vauth/spnego_sspi.c b/Utilities/cmcurl/lib/vauth/spnego_sspi.c new file mode 100644 index 0000000..b6176ec --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/spnego_sspi.c @@ -0,0 +1,297 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * RFC4178 Simple and Protected GSS-API Negotiation Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_WINDOWS_SSPI) && defined(USE_SPNEGO) + +#include <curl/curl.h> + +#include "vauth/vauth.h" +#include "urldata.h" +#include "curl_base64.h" +#include "warnless.h" +#include "curl_multibyte.h" +#include "sendf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_decode_spnego_message() + * + * This is used to decode an already encoded SPNEGO (Negotiate) challenge + * message. + * + * Parameters: + * + * data [in] - The session handle. + * userp [in] - The user name in the format User or Domain\User. + * passdwp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * chlg64 [in] - The optional base64 encoded challenge message. + * nego [in/out] - The Negotiate data struct being used and modified. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + const char *user, + const char *password, + const char *service, + const char *host, + const char *chlg64, + struct negotiatedata *nego) +{ + CURLcode result = CURLE_OK; + size_t chlglen = 0; + unsigned char *chlg = NULL; + PSecPkgInfo SecurityPackage; + SecBuffer chlg_buf; + SecBuffer resp_buf; + SecBufferDesc chlg_desc; + SecBufferDesc resp_desc; + unsigned long attrs; + TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ + +#if defined(CURL_DISABLE_VERBOSE_STRINGS) + (void) data; +#endif + + if(nego->context && nego->status == SEC_E_OK) { + /* We finished successfully our part of authentication, but server + * rejected it (since we're again here). Exit with an error since we + * can't invent anything better */ + Curl_auth_spnego_cleanup(nego); + return CURLE_LOGIN_DENIED; + } + + if(!nego->spn) { + /* Generate our SPN */ + nego->spn = Curl_auth_build_spn(service, host, NULL); + if(!nego->spn) + return CURLE_OUT_OF_MEMORY; + } + + if(!nego->output_token) { + /* Query the security package for Negotiate */ + nego->status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_NEGOTIATE), + &SecurityPackage); + if(nego->status != SEC_E_OK) + return CURLE_NOT_BUILT_IN; + + nego->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + s_pSecFn->FreeContextBuffer(SecurityPackage); + + /* Allocate our output buffer */ + nego->output_token = malloc(nego->token_max); + if(!nego->output_token) + return CURLE_OUT_OF_MEMORY; + } + + if(!nego->credentials) { + /* Do we have credientials to use or are we using single sign-on? */ + if(user && *user) { + /* Populate our identity structure */ + result = Curl_create_sspi_identity(user, password, &nego->identity); + if(result) + return result; + + /* Allow proper cleanup of the identity structure */ + nego->p_identity = &nego->identity; + } + else + /* Use the current Windows user */ + nego->p_identity = NULL; + + /* Allocate our credentials handle */ + nego->credentials = malloc(sizeof(CredHandle)); + if(!nego->credentials) + return CURLE_OUT_OF_MEMORY; + + memset(nego->credentials, 0, sizeof(CredHandle)); + + /* Acquire our credentials handle */ + nego->status = + s_pSecFn->AcquireCredentialsHandle(NULL, + (TCHAR *)TEXT(SP_NAME_NEGOTIATE), + SECPKG_CRED_OUTBOUND, NULL, + nego->p_identity, NULL, NULL, + nego->credentials, &expiry); + if(nego->status != SEC_E_OK) + return CURLE_LOGIN_DENIED; + + /* Allocate our new context handle */ + nego->context = malloc(sizeof(CtxtHandle)); + if(!nego->context) + return CURLE_OUT_OF_MEMORY; + + memset(nego->context, 0, sizeof(CtxtHandle)); + } + + if(chlg64 && *chlg64) { + /* Decode the base-64 encoded challenge message */ + if(*chlg64 != '=') { + result = Curl_base64_decode(chlg64, &chlg, &chlglen); + if(result) + return result; + } + + /* Ensure we have a valid challenge message */ + if(!chlg) { + infof(data, "SPNEGO handshake failure (empty challenge message)\n"); + + return CURLE_BAD_CONTENT_ENCODING; + } + + /* Setup the challenge "input" security buffer */ + chlg_desc.ulVersion = SECBUFFER_VERSION; + chlg_desc.cBuffers = 1; + chlg_desc.pBuffers = &chlg_buf; + chlg_buf.BufferType = SECBUFFER_TOKEN; + chlg_buf.pvBuffer = chlg; + chlg_buf.cbBuffer = curlx_uztoul(chlglen); + } + + /* Setup the response "output" security buffer */ + resp_desc.ulVersion = SECBUFFER_VERSION; + resp_desc.cBuffers = 1; + resp_desc.pBuffers = &resp_buf; + resp_buf.BufferType = SECBUFFER_TOKEN; + resp_buf.pvBuffer = nego->output_token; + resp_buf.cbBuffer = curlx_uztoul(nego->token_max); + + /* Generate our challenge-response message */ + nego->status = s_pSecFn->InitializeSecurityContext(nego->credentials, + chlg ? nego->context : + NULL, + nego->spn, + ISC_REQ_CONFIDENTIALITY, + 0, SECURITY_NATIVE_DREP, + chlg ? &chlg_desc : NULL, + 0, nego->context, + &resp_desc, &attrs, + &expiry); + + /* Free the decoded challenge as it is not required anymore */ + free(chlg); + + if(GSS_ERROR(nego->status)) { + return CURLE_OUT_OF_MEMORY; + } + + if(nego->status == SEC_I_COMPLETE_NEEDED || + nego->status == SEC_I_COMPLETE_AND_CONTINUE) { + nego->status = s_pSecFn->CompleteAuthToken(nego->context, &resp_desc); + if(GSS_ERROR(nego->status)) { + return CURLE_RECV_ERROR; + } + } + + nego->output_token_length = resp_buf.cbBuffer; + + return result; +} + +/* + * Curl_auth_create_spnego_message() + * + * This is used to generate an already encoded SPNEGO (Negotiate) response + * message ready for sending to the recipient. + * + * Parameters: + * + * data [in] - The session handle. + * nego [in/out] - The Negotiate data struct being used and modified. + * outptr [in/out] - The address where a pointer to newly allocated memory + * holding the result will be stored upon completion. + * outlen [out] - The length of the output message. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data, + struct negotiatedata *nego, + char **outptr, size_t *outlen) +{ + CURLcode result; + + /* Base64 encode the already generated response */ + result = Curl_base64_encode(data, + (const char*) nego->output_token, + nego->output_token_length, + outptr, outlen); + + if(result) + return result; + + if(!*outptr || !*outlen) + return CURLE_REMOTE_ACCESS_DENIED; + + return CURLE_OK; +} + +/* + * Curl_auth_spnego_cleanup() + * + * This is used to clean up the SPNEGO (Negotiate) specific data. + * + * Parameters: + * + * nego [in/out] - The Negotiate data struct being cleaned up. + * + */ +void Curl_auth_spnego_cleanup(struct negotiatedata *nego) +{ + /* Free our security context */ + if(nego->context) { + s_pSecFn->DeleteSecurityContext(nego->context); + free(nego->context); + nego->context = NULL; + } + + /* Free our credentials handle */ + if(nego->credentials) { + s_pSecFn->FreeCredentialsHandle(nego->credentials); + free(nego->credentials); + nego->credentials = NULL; + } + + /* Free our identity */ + Curl_sspi_free_identity(nego->p_identity); + nego->p_identity = NULL; + + /* Free the SPN and output token */ + Curl_safefree(nego->spn); + Curl_safefree(nego->output_token); + + /* Reset any variables */ + nego->status = 0; + nego->token_max = 0; +} + +#endif /* USE_WINDOWS_SSPI && USE_SPNEGO */ diff --git a/Utilities/cmcurl/lib/vauth/vauth.c b/Utilities/cmcurl/lib/vauth/vauth.c new file mode 100644 index 0000000..702e2d4 --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/vauth.c @@ -0,0 +1,106 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include <curl/curl.h> + +#include "vauth.h" +#include "curl_multibyte.h" +#include "curl_printf.h" + +/* The last #include files should be: */ +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_auth_build_spn() + * + * This is used to build a SPN string in the following formats: + * + * service/host@realm (Not currently used) + * service/host (Not used by GSS-API) + * service@realm (Not used by Windows SSPI) + * + * Parameters: + * + * service [in] - The service type such as http, smtp, pop or imap. + * host [in] - The host name. + * realm [in] - The realm. + * + * Returns a pointer to the newly allocated SPN. + */ +#if !defined(USE_WINDOWS_SSPI) +char *Curl_auth_build_spn(const char *service, const char *host, + const char *realm) +{ + char *spn = NULL; + + /* Generate our SPN */ + if(host && realm) + spn = aprintf("%s/%s@%s", service, host, realm); + else if(host) + spn = aprintf("%s/%s", service, host); + else if(realm) + spn = aprintf("%s@%s", service, realm); + + /* Return our newly allocated SPN */ + return spn; +} +#else +TCHAR *Curl_auth_build_spn(const char *service, const char *host, + const char *realm) +{ + char *utf8_spn = NULL; + TCHAR *tchar_spn = NULL; + + (void) realm; + + /* Note: We could use DsMakeSPN() or DsClientMakeSpnForTargetServer() rather + than doing this ourselves but the first is only available in Windows XP + and Windows Server 2003 and the latter is only available in Windows 2000 + but not Windows95/98/ME or Windows NT4.0 unless the Active Directory + Client Extensions are installed. As such it is far simpler for us to + formulate the SPN instead. */ + + /* Generate our UTF8 based SPN */ + utf8_spn = aprintf("%s/%s", service, host); + if(!utf8_spn) { + return NULL; + } + + /* Allocate our TCHAR based SPN */ + tchar_spn = Curl_convert_UTF8_to_tchar(utf8_spn); + if(!tchar_spn) { + free(utf8_spn); + + return NULL; + } + + /* Release the UTF8 variant when operating with Unicode */ + Curl_unicodefree(utf8_spn); + + /* Return our newly allocated SPN */ + return tchar_spn; +} +#endif /* USE_WINDOWS_SSPI */ + diff --git a/Utilities/cmcurl/lib/vauth/vauth.h b/Utilities/cmcurl/lib/vauth/vauth.h new file mode 100644 index 0000000..38806ee --- /dev/null +++ b/Utilities/cmcurl/lib/vauth/vauth.h @@ -0,0 +1,189 @@ +#ifndef HEADER_CURL_VAUTH_H +#define HEADER_CURL_VAUTH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include <curl/curl.h> + +struct Curl_easy; + +#if !defined(CURL_DISABLE_CRYPTO_AUTH) +struct digestdata; +#endif + +#if defined(USE_NTLM) +struct ntlmdata; +#endif + +#if defined(USE_KERBEROS5) +struct kerberos5data; +#endif + +#if (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) && defined(USE_SPNEGO) +struct negotiatedata; +#endif + +#if defined(USE_WINDOWS_SSPI) +#define GSS_ERROR(status) (status & 0x80000000) +#endif + +/* This is used to build a SPN string */ +#if !defined(USE_WINDOWS_SSPI) +char *Curl_auth_build_spn(const char *service, const char *host, + const char *realm); +#else +TCHAR *Curl_auth_build_spn(const char *service, const char *host, + const char *realm); +#endif + +/* This is used to generate a base64 encoded PLAIN cleartext message */ +CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + char **outptr, size_t *outlen); + +/* This is used to generate a base64 encoded LOGIN cleartext message */ +CURLcode Curl_auth_create_login_message(struct Curl_easy *data, + const char *valuep, char **outptr, + size_t *outlen); + +/* This is used to generate a base64 encoded EXTERNAL cleartext message */ +CURLcode Curl_auth_create_external_message(struct Curl_easy *data, + const char *user, char **outptr, + size_t *outlen); + +#if !defined(CURL_DISABLE_CRYPTO_AUTH) +/* This is used to decode a CRAM-MD5 challenge message */ +CURLcode Curl_auth_decode_cram_md5_message(const char *chlg64, char **outptr, + size_t *outlen); + +/* This is used to generate a CRAM-MD5 response message */ +CURLcode Curl_auth_create_cram_md5_message(struct Curl_easy *data, + const char *chlg, + const char *userp, + const char *passwdp, + char **outptr, size_t *outlen); + +/* This is used to generate a base64 encoded DIGEST-MD5 response message */ +CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, + const char *chlg64, + const char *userp, + const char *passwdp, + const char *service, + char **outptr, size_t *outlen); + +/* This is used to decode a HTTP DIGEST challenge message */ +CURLcode Curl_auth_decode_digest_http_message(const char *chlg, + struct digestdata *digest); + +/* This is used to generate a HTTP DIGEST response message */ +CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const unsigned char *request, + const unsigned char *uri, + struct digestdata *digest, + char **outptr, size_t *outlen); + +/* This is used to clean up the digest specific data */ +void Curl_auth_digest_cleanup(struct digestdata *digest); +#endif /* !CURL_DISABLE_CRYPTO_AUTH */ + +#if defined(USE_NTLM) +/* This is used to generate a base64 encoded NTLM type-1 message */ +CURLcode Curl_auth_create_ntlm_type1_message(const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + char **outptr, + size_t *outlen); + +/* This is used to decode a base64 encoded NTLM type-2 message */ +CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, + const char *type2msg, + struct ntlmdata *ntlm); + +/* This is used to generate a base64 encoded NTLM type-3 message */ +CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + struct ntlmdata *ntlm, + char **outptr, size_t *outlen); + +/* This is used to clean up the NTLM specific data */ +void Curl_auth_ntlm_cleanup(struct ntlmdata *ntlm); +#endif /* USE_NTLM */ + +/* This is used to generate a base64 encoded OAuth 2.0 message */ +CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_easy *data, + const char *user, + const char *host, + const long port, + const char *bearer, + char **outptr, size_t *outlen); +#if defined(USE_KERBEROS5) +/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) user token + message */ +CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, + const char *userp, + const char *passwdp, + const char *service, + const char *host, + const bool mutual, + const char *chlg64, + struct kerberos5data *krb5, + char **outptr, size_t *outlen); + +/* This is used to generate a base64 encoded GSSAPI (Kerberos V5) security + token message */ +CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, + const char *input, + struct kerberos5data *krb5, + char **outptr, + size_t *outlen); + +/* This is used to clean up the GSSAPI specific data */ +void Curl_auth_gssapi_cleanup(struct kerberos5data *krb5); +#endif /* USE_KERBEROS5 */ + +#if defined(USE_SPNEGO) +/* This is used to decode a base64 encoded SPNEGO (Negotiate) challenge + message */ +CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, + const char *user, + const char *passwood, + const char *service, + const char *host, + const char *chlg64, + struct negotiatedata *nego); + +/* This is used to generate a base64 encoded SPNEGO (Negotiate) response + message */ +CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data, + struct negotiatedata *nego, + char **outptr, size_t *outlen); + +/* This is used to clean up the SPNEGO specifiec data */ +void Curl_auth_spnego_cleanup(struct negotiatedata *nego); + +#endif /* USE_SPNEGO */ + +#endif /* HEADER_CURL_VAUTH_H */ diff --git a/Utilities/cmcurl/lib/version.c b/Utilities/cmcurl/lib/version.c index 1727c5a..1292445 100644 --- a/Utilities/cmcurl/lib/version.c +++ b/Utilities/cmcurl/lib/version.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -40,6 +40,10 @@ #include <stringprep.h> #endif +#ifdef USE_LIBPSL +#include <libpsl.h> +#endif + #if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS) #include <iconv.h> #endif @@ -60,13 +64,27 @@ #define CURL_LIBSSH2_VERSION LIBSSH2_VERSION #endif +void Curl_version_init(void); + +/* For thread safety purposes this function is called by global_init so that + the static data in both version functions is initialized. */ +void Curl_version_init(void) +{ + curl_version(); + curl_version_info(CURLVERSION_NOW); +} + char *curl_version(void) { + static bool initialized; static char version[200]; char *ptr = version; size_t len; size_t left = sizeof(version); + if(initialized) + return version; + strcpy(ptr, LIBCURL_NAME "/" LIBCURL_VERSION); len = strlen(ptr); left -= len; @@ -100,6 +118,11 @@ char *curl_version(void) ptr += len; } #endif +#ifdef USE_LIBPSL + len = snprintf(ptr, left, " libpsl/%s", psl_get_version()); + left -= len; + ptr += len; +#endif #ifdef USE_WIN32_IDN len = snprintf(ptr, left, " WinIDN"); left -= len; @@ -151,6 +174,7 @@ char *curl_version(void) } #endif + initialized = true; return version; } @@ -297,6 +321,9 @@ static curl_version_info_data version_info = { #if defined(USE_UNIX_SOCKETS) | CURL_VERSION_UNIX_SOCKETS #endif +#if defined(USE_LIBPSL) + | CURL_VERSION_PSL +#endif , NULL, /* ssl_version */ 0, /* ssl_version_num, this is kept at zero */ @@ -311,12 +338,18 @@ static curl_version_info_data version_info = { curl_version_info_data *curl_version_info(CURLversion stamp) { + static bool initialized; #ifdef USE_LIBSSH2 static char ssh_buffer[80]; #endif - #ifdef USE_SSL static char ssl_buffer[80]; +#endif + + if(initialized) + return &version_info; + +#ifdef USE_SSL Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer)); version_info.ssl_version = ssl_buffer; #endif @@ -358,5 +391,6 @@ curl_version_info_data *curl_version_info(CURLversion stamp) (void)stamp; /* avoid compiler warnings, we don't use this */ + initialized = true; return &version_info; } diff --git a/Utilities/cmcurl/lib/vtls/axtls.c b/Utilities/cmcurl/lib/vtls/axtls.c index 1038432..b6c69ad 100644 --- a/Utilities/cmcurl/lib/vtls/axtls.c +++ b/Utilities/cmcurl/lib/vtls/axtls.c @@ -6,11 +6,11 @@ * \___|\___/|_| \_\_____| * * Copyright (C) 2010, DirecTV, Contact: Eric Hu, <ehu@directv.com>. - * Copyright (C) 2010 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2010 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -137,14 +137,12 @@ static void free_ssl_structs(struct ssl_connect_data *connssl) */ static CURLcode connect_prep(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; SSL_CTX *ssl_ctx; SSL *ssl = NULL; int cert_types[] = {SSL_OBJ_X509_CERT, SSL_OBJ_PKCS12, 0}; int key_types[] = {SSL_OBJ_RSA_KEY, SSL_OBJ_PKCS8, SSL_OBJ_PKCS12, 0}; int i, ssl_fcn_return; - const uint8_t *ssl_sessionid; - size_t ssl_idsize; /* Assuming users will not compile in custom key/cert to axTLS. * Also, even for blocking connects, use axTLS non-blocking feature. @@ -258,14 +256,22 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex) * 2) setting up callbacks. these seem gnutls specific */ - /* In axTLS, handshaking happens inside ssl_client_new. */ - if(!Curl_ssl_getsessionid(conn, (void **) &ssl_sessionid, &ssl_idsize)) { - /* we got a session id, use it! */ - infof (data, "SSL re-using session ID\n"); - ssl = ssl_client_new(ssl_ctx, conn->sock[sockindex], - ssl_sessionid, (uint8_t)ssl_idsize); + if(conn->ssl_config.sessionid) { + const uint8_t *ssl_sessionid; + size_t ssl_idsize; + + /* In axTLS, handshaking happens inside ssl_client_new. */ + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, (void **) &ssl_sessionid, &ssl_idsize)) { + /* we got a session id, use it! */ + infof (data, "SSL re-using session ID\n"); + ssl = ssl_client_new(ssl_ctx, conn->sock[sockindex], + ssl_sessionid, (uint8_t)ssl_idsize); + } + Curl_ssl_sessionid_unlock(conn); } - else + + if(!ssl) ssl = ssl_client_new(ssl_ctx, conn->sock[sockindex], NULL, 0); conn->ssl[sockindex].ssl = ssl; @@ -278,10 +284,8 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex) */ static CURLcode connect_finish(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; SSL *ssl = conn->ssl[sockindex].ssl; - const uint8_t *ssl_sessionid; - size_t ssl_idsize; const char *peer_CN; uint32_t dns_altname_index; const char *dns_altname; @@ -379,11 +383,15 @@ static CURLcode connect_finish(struct connectdata *conn, int sockindex) conn->send[sockindex] = axtls_send; /* Put our freshly minted SSL session in cache */ - ssl_idsize = ssl_get_session_id_size(ssl); - ssl_sessionid = ssl_get_session_id(ssl); - if(Curl_ssl_addsessionid(conn, (void *) ssl_sessionid, ssl_idsize) - != CURLE_OK) - infof (data, "failed to add session to cache\n"); + if(conn->ssl_config.sessionid) { + const uint8_t *ssl_sessionid = ssl_get_session_id_size(ssl); + size_t ssl_idsize = ssl_get_session_id(ssl); + Curl_ssl_sessionid_lock(conn); + if(Curl_ssl_addsessionid(conn, (void *) ssl_sessionid, ssl_idsize) + != CURLE_OK) + infof (data, "failed to add session to cache\n"); + Curl_ssl_sessionid_unlock(conn); + } return CURLE_OK; } @@ -464,7 +472,7 @@ Curl_axtls_connect(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode conn_step = connect_prep(conn, sockindex); int ssl_fcn_return; SSL *ssl = conn->ssl[sockindex].ssl; @@ -493,7 +501,7 @@ Curl_axtls_connect(struct connectdata *conn, return map_error_to_curl(ssl_fcn_return); } /* TODO: avoid polling */ - usleep(10000); + Curl_wait_ms(10); } infof (conn->data, "handshake completed successfully\n"); @@ -518,7 +526,7 @@ static ssize_t axtls_send(struct connectdata *conn, infof(conn->data, " axtls_send\n"); - if(rc < 0 ) { + if(rc < 0) { *err = map_error_to_curl(rc); rc = -1; /* generic error code for send failure */ } @@ -554,7 +562,7 @@ int Curl_axtls_shutdown(struct connectdata *conn, int sockindex) */ int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; uint8_t *buf; ssize_t nread; @@ -670,7 +678,7 @@ size_t Curl_axtls_version(char *buffer, size_t size) return snprintf(buffer, size, "axTLS/%s", ssl_version()); } -int Curl_axtls_random(struct SessionHandle *data, +int Curl_axtls_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { diff --git a/Utilities/cmcurl/lib/vtls/axtls.h b/Utilities/cmcurl/lib/vtls/axtls.h index 223ecb8..b16d051 100644 --- a/Utilities/cmcurl/lib/vtls/axtls.h +++ b/Utilities/cmcurl/lib/vtls/axtls.h @@ -12,7 +12,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -42,7 +42,7 @@ void Curl_axtls_session_free(void *ptr); size_t Curl_axtls_version(char *buffer, size_t size); int Curl_axtls_shutdown(struct connectdata *conn, int sockindex); int Curl_axtls_check_cxn(struct connectdata *conn); -int Curl_axtls_random(struct SessionHandle *data, +int Curl_axtls_random(struct Curl_easy *data, unsigned char *entropy, size_t length); diff --git a/Utilities/cmcurl/lib/vtls/cyassl.c b/Utilities/cmcurl/lib/vtls/cyassl.c index 3ded7f1..7994b3e 100644 --- a/Utilities/cmcurl/lib/vtls/cyassl.c +++ b/Utilities/cmcurl/lib/vtls/cyassl.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -33,7 +33,7 @@ #define WOLFSSL_OPTIONS_IGNORE_SYS /* CyaSSL's version.h, which should contain only the version, should come before all other CyaSSL includes and be immediately followed by build config -aka options.h. http://curl.haxx.se/mail/lib-2015-04/0069.html */ +aka options.h. https://curl.haxx.se/mail/lib-2015-04/0069.html */ #include <cyassl/version.h> #if defined(HAVE_CYASSL_OPTIONS_H) && (LIBCYASSL_VERSION_HEX > 0x03004008) #if defined(CYASSL_API) || defined(WOLFSSL_API) @@ -51,7 +51,6 @@ and that's a problem since options.h hasn't been included yet. */ #include "urldata.h" #include "sendf.h" #include "inet_pton.h" -#include "cyassl.h" #include "vtls.h" #include "parsedate.h" #include "connect.h" /* for the connect timeout */ @@ -69,6 +68,8 @@ and that's a problem since options.h hasn't been included yet. */ #include <cyassl/ctaocrypt/random.h> #include <cyassl/ctaocrypt/sha256.h> +#include "cyassl.h" + /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" @@ -77,6 +78,38 @@ and that's a problem since options.h hasn't been included yet. */ #define CYASSL_MAX_ERROR_SZ 80 #endif +/* To determine what functions are available we rely on one or both of: + - the user's options.h generated by CyaSSL/wolfSSL + - the symbols detected by curl's configure + Since they are markedly different from one another, and one or the other may + not be available, we do some checking below to bring things in sync. */ + +/* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */ +#ifndef HAVE_ALPN +#ifdef HAVE_WOLFSSL_USEALPN +#define HAVE_ALPN +#endif +#endif + +/* WOLFSSL_ALLOW_SSLV3 is wolfSSL's build time symbol for enabling SSLv3 in + options.h, but is only seen in >= 3.6.6 since that's when they started + disabling SSLv3 by default. */ +#ifndef WOLFSSL_ALLOW_SSLV3 +#if (LIBCYASSL_VERSION_HEX < 0x03006006) || \ + defined(HAVE_WOLFSSLV3_CLIENT_METHOD) +#define WOLFSSL_ALLOW_SSLV3 +#endif +#endif + +/* HAVE_SUPPORTED_CURVES is wolfSSL's build time symbol for enabling the ECC + supported curve extension in options.h. Note ECC is enabled separately. */ +#ifndef HAVE_SUPPORTED_CURVES +#if defined(HAVE_CYASSL_CTX_USESUPPORTEDCURVE) || \ + defined(HAVE_WOLFSSL_CTX_USESUPPORTEDCURVE) +#define HAVE_SUPPORTED_CURVES +#endif +#endif + static Curl_recv cyassl_recv; static Curl_send cyassl_send; @@ -101,10 +134,9 @@ cyassl_connect_step1(struct connectdata *conn, int sockindex) { char error_buffer[CYASSL_MAX_ERROR_SZ]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data* conssl = &conn->ssl[sockindex]; SSL_METHOD* req_method = NULL; - void* ssl_sessionid = NULL; curl_socket_t sockfd = conn->sock[sockindex]; #ifdef HAVE_SNI bool sni = FALSE; @@ -143,8 +175,13 @@ cyassl_connect_step1(struct connectdata *conn, use_sni(TRUE); break; case CURL_SSLVERSION_SSLv3: +#ifdef WOLFSSL_ALLOW_SSLV3 req_method = SSLv3_client_method(); use_sni(FALSE); +#else + failf(data, "No support for SSLv3"); + return CURLE_NOT_BUILT_IN; +#endif break; case CURL_SSLVERSION_SSLv2: failf(data, "CyaSSL does not support SSLv2"); @@ -273,6 +310,16 @@ cyassl_connect_step1(struct connectdata *conn, } #endif +#ifdef HAVE_SUPPORTED_CURVES + /* CyaSSL/wolfSSL does not send the supported ECC curves ext automatically: + https://github.com/wolfSSL/wolfssl/issues/366 + The supported curves below are those also supported by OpenSSL 1.0.2 and + in the same order. */ + CyaSSL_CTX_UseSupportedCurve(conssl->ctx, 0x17); /* secp256r1 */ + CyaSSL_CTX_UseSupportedCurve(conssl->ctx, 0x19); /* secp521r1 */ + CyaSSL_CTX_UseSupportedCurve(conssl->ctx, 0x18); /* secp384r1 */ +#endif + /* give application a chance to interfere with SSL set up. */ if(data->set.ssl.fsslctx) { CURLcode result = CURLE_OK; @@ -302,16 +349,51 @@ cyassl_connect_step1(struct connectdata *conn, return CURLE_OUT_OF_MEMORY; } - /* Check if there's a cached ID we can/should use here! */ - if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) { - /* we got a session id, use it! */ - if(!SSL_set_session(conssl->handle, ssl_sessionid)) { - failf(data, "SSL: SSL_set_session failed: %s", - ERR_error_string(SSL_get_error(conssl->handle, 0), error_buffer)); +#ifdef HAVE_ALPN + if(conn->bits.tls_enable_alpn) { + char protocols[128]; + *protocols = '\0'; + + /* wolfSSL's ALPN protocol name list format is a comma separated string of + protocols in descending order of preference, eg: "h2,http/1.1" */ + +#ifdef USE_NGHTTP2 + if(data->set.httpversion >= CURL_HTTP_VERSION_2) { + strcpy(protocols + strlen(protocols), NGHTTP2_PROTO_VERSION_ID ","); + infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); + } +#endif + + strcpy(protocols + strlen(protocols), ALPN_HTTP_1_1); + infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); + + if(wolfSSL_UseALPN(conssl->handle, protocols, + (unsigned)strlen(protocols), + WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) { + failf(data, "SSL: failed setting ALPN protocols"); return CURLE_SSL_CONNECT_ERROR; } - /* Informational message */ - infof (data, "SSL re-using session ID\n"); + } +#endif /* HAVE_ALPN */ + + /* Check if there's a cached ID we can/should use here! */ + if(conn->ssl_config.sessionid) { + void *ssl_sessionid = NULL; + + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) { + /* we got a session id, use it! */ + if(!SSL_set_session(conssl->handle, ssl_sessionid)) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "SSL: SSL_set_session failed: %s", + ERR_error_string(SSL_get_error(conssl->handle, 0), + error_buffer)); + return CURLE_SSL_CONNECT_ERROR; + } + /* Informational message */ + infof (data, "SSL re-using session ID\n"); + } + Curl_ssl_sessionid_unlock(conn); } /* pass the raw socket into the SSL layer */ @@ -330,7 +412,7 @@ cyassl_connect_step2(struct connectdata *conn, int sockindex) { int ret = -1; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data* conssl = &conn->ssl[sockindex]; conn->recv[sockindex] = cyassl_recv; @@ -406,6 +488,7 @@ cyassl_connect_step2(struct connectdata *conn, } if(data->set.str[STRING_SSL_PINNEDPUBLICKEY]) { +#ifdef KEEP_PEER_CERT X509 *x509; const char *x509_der; int x509_der_len; @@ -434,14 +517,54 @@ cyassl_connect_step2(struct connectdata *conn, return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } - result = Curl_pin_peer_pubkey(data->set.str[STRING_SSL_PINNEDPUBLICKEY], + result = Curl_pin_peer_pubkey(data, + data->set.str[STRING_SSL_PINNEDPUBLICKEY], (const unsigned char *)pubkey->header, (size_t)(pubkey->end - pubkey->header)); if(result) { failf(data, "SSL: public key does not match pinned public key!"); return result; } +#else + failf(data, "Library lacks pinning support built-in"); + return CURLE_NOT_BUILT_IN; +#endif + } + +#ifdef HAVE_ALPN + if(conn->bits.tls_enable_alpn) { + int rc; + char *protocol = NULL; + unsigned short protocol_len = 0; + + rc = wolfSSL_ALPN_GetProtocol(conssl->handle, &protocol, &protocol_len); + + if(rc == SSL_SUCCESS) { + infof(data, "ALPN, server accepted to use %.*s\n", protocol_len, + protocol); + + if(protocol_len == ALPN_HTTP_1_1_LENGTH && + !memcmp(protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) + conn->negnpn = CURL_HTTP_VERSION_1_1; +#ifdef USE_NGHTTP2 + else if(data->set.httpversion >= CURL_HTTP_VERSION_2 && + protocol_len == NGHTTP2_PROTO_VERSION_ID_LEN && + !memcmp(protocol, NGHTTP2_PROTO_VERSION_ID, + NGHTTP2_PROTO_VERSION_ID_LEN)) + conn->negnpn = CURL_HTTP_VERSION_2; +#endif + else + infof(data, "ALPN, unrecognized protocol %.*s\n", protocol_len, + protocol); + } + else if(rc == SSL_ALPN_NOT_FOUND) + infof(data, "ALPN, server did not agree to a protocol\n"); + else { + failf(data, "ALPN, failure getting protocol, error %d", rc); + return CURLE_SSL_CONNECT_ERROR; + } } +#endif /* HAVE_ALPN */ conssl->connecting_state = ssl_connect_3; infof(data, "SSL connected\n"); @@ -455,32 +578,38 @@ cyassl_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; - void *old_ssl_sessionid=NULL; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - bool incache; - SSL_SESSION *our_ssl_sessionid; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); - our_ssl_sessionid = SSL_get_session(connssl->handle); + if(conn->ssl_config.sessionid) { + bool incache; + SSL_SESSION *our_ssl_sessionid; + void *old_ssl_sessionid = NULL; + + our_ssl_sessionid = SSL_get_session(connssl->handle); - incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)); - if(incache) { - if(old_ssl_sessionid != our_ssl_sessionid) { - infof(data, "old SSL session ID is stale, removing\n"); - Curl_ssl_delsessionid(conn, old_ssl_sessionid); - incache = FALSE; + Curl_ssl_sessionid_lock(conn); + incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)); + if(incache) { + if(old_ssl_sessionid != our_ssl_sessionid) { + infof(data, "old SSL session ID is stale, removing\n"); + Curl_ssl_delsessionid(conn, old_ssl_sessionid); + incache = FALSE; + } } - } - if(!incache) { - result = Curl_ssl_addsessionid(conn, our_ssl_sessionid, - 0 /* unknown size */); - if(result) { - failf(data, "failed to store ssl session"); - return result; + if(!incache) { + result = Curl_ssl_addsessionid(conn, our_ssl_sessionid, + 0 /* unknown size */); + if(result) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "failed to store ssl session"); + return result; + } } + Curl_ssl_sessionid_unlock(conn); } connssl->connecting_state = ssl_connect_done; @@ -625,7 +754,7 @@ cyassl_connect_common(struct connectdata *conn, bool *done) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; @@ -756,7 +885,7 @@ Curl_cyassl_connect(struct connectdata *conn, return CURLE_OK; } -int Curl_cyassl_random(struct SessionHandle *data, +int Curl_cyassl_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { @@ -779,7 +908,7 @@ void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */ Sha256 SHA256pw; (void)unused; InitSha256(&SHA256pw); - Sha256Update(&SHA256pw, tmp, tmplen); + Sha256Update(&SHA256pw, tmp, (word32)tmplen); Sha256Final(&SHA256pw, sha256sum); } diff --git a/Utilities/cmcurl/lib/vtls/cyassl.h b/Utilities/cmcurl/lib/vtls/cyassl.h index 167de74..508dfaa 100644 --- a/Utilities/cmcurl/lib/vtls/cyassl.h +++ b/Utilities/cmcurl/lib/vtls/cyassl.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -25,6 +25,18 @@ #ifdef USE_CYASSL +/* KEEP_PEER_CERT is a product of the presence of build time symbol + OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is + in wolfSSL's settings.h, and the latter two are build time symbols in + options.h. */ +#ifndef KEEP_PEER_CERT +#if defined(HAVE_CYASSL_GET_PEER_CERTIFICATE) || \ + defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \ + (defined(OPENSSL_EXTRA) && !defined(NO_CERTS)) +#define KEEP_PEER_CERT +#endif +#endif + CURLcode Curl_cyassl_connect(struct connectdata *conn, int sockindex); bool Curl_cyassl_data_pending(const struct connectdata* conn, int connindex); int Curl_cyassl_shutdown(struct connectdata* conn, int sockindex); @@ -39,7 +51,7 @@ int Curl_cyassl_init(void); CURLcode Curl_cyassl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done); -int Curl_cyassl_random(struct SessionHandle *data, +int Curl_cyassl_random(struct Curl_easy *data, unsigned char *entropy, size_t length); void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */ @@ -53,6 +65,11 @@ void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */ /* this backend supports CURLOPT_SSL_CTX_* */ #define have_curlssl_ssl_ctx 1 +#ifdef KEEP_PEER_CERT +/* this backend supports CURLOPT_PINNEDPUBLICKEY */ +#define have_curlssl_pinnedpubkey 1 +#endif + /* API setup for CyaSSL */ #define curlssl_init Curl_cyassl_init #define curlssl_cleanup() Curl_nop_stmt diff --git a/Utilities/cmcurl/lib/vtls/darwinssl.c b/Utilities/cmcurl/lib/vtls/darwinssl.c index 03adcef..ebb9e30 100644 --- a/Utilities/cmcurl/lib/vtls/darwinssl.c +++ b/Utilities/cmcurl/lib/vtls/darwinssl.c @@ -10,7 +10,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -28,7 +28,7 @@ #include "curl_setup.h" -#include "urldata.h" /* for the SessionHandle definition */ +#include "urldata.h" /* for the Curl_easy definition */ #include "curl_base64.h" #include "strtok.h" @@ -781,7 +781,7 @@ CF_INLINE void GetDarwinVersionNumber(int *major, int *minor) int mib[2]; char *os_version; size_t os_version_len; - char *os_version_major, *os_version_minor/*, *os_version_point*/; + char *os_version_major, *os_version_minor; char *tok_buf; /* Get the Darwin kernel version from the kernel using sysctl(): */ @@ -800,7 +800,6 @@ CF_INLINE void GetDarwinVersionNumber(int *major, int *minor) /* Parse the version: */ os_version_major = strtok_r(os_version, ".", &tok_buf); os_version_minor = strtok_r(NULL, ".", &tok_buf); - /*os_version_point = strtok_r(NULL, ".", &tok_buf);*/ *major = atoi(os_version_major); *minor = atoi(os_version_minor); free(os_version); @@ -1000,7 +999,7 @@ CF_INLINE bool is_file(const char *filename) static CURLcode darwinssl_connect_step1(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; #ifdef ENABLE_IPV6 @@ -1010,8 +1009,6 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn, #endif /* ENABLE_IPV6 */ size_t all_ciphers_count = 0UL, allowed_ciphers_count = 0UL, i; SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL; - char *ssl_sessionid; - size_t ssl_sessionid_len; OSStatus err = noErr; #if CURL_BUILD_MAC int darwinver_maj = 0, darwinver_min = 0; @@ -1282,14 +1279,21 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn, #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS /* Snow Leopard introduced the SSLSetSessionOption() function, but due to a library bug with the way the kSSLSessionOptionBreakOnServerAuth flag - works, it doesn't work as expected under Snow Leopard or Lion. + works, it doesn't work as expected under Snow Leopard, Lion or + Mountain Lion. So we need to call SSLSetEnableCertVerify() on those older cats in order to disable certificate validation if the user turned that off. (SecureTransport will always validate the certificate chain by - default.) */ - /* (Note: Darwin 12.x.x is Mountain Lion.) */ + default.) + Note: + Darwin 11.x.x is Lion (10.7) + Darwin 12.x.x is Mountain Lion (10.8) + Darwin 13.x.x is Mavericks (10.9) + Darwin 14.x.x is Yosemite (10.10) + Darwin 15.x.x is El Capitan (10.11) + */ #if CURL_BUILD_MAC - if(SSLSetSessionOption != NULL && darwinver_maj >= 12) { + if(SSLSetSessionOption != NULL && darwinver_maj >= 13) { #else if(SSLSetSessionOption != NULL) { #endif /* CURL_BUILD_MAC */ @@ -1468,37 +1472,46 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn, #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ /* Check if there's a cached ID we can/should use here! */ - if(!Curl_ssl_getsessionid(conn, (void **)&ssl_sessionid, - &ssl_sessionid_len)) { - /* we got a session id, use it! */ - err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len); - if(err != noErr) { - failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); - return CURLE_SSL_CONNECT_ERROR; - } - /* Informational message */ - infof(data, "SSL re-using session ID\n"); - } - /* If there isn't one, then let's make one up! This has to be done prior - to starting the handshake. */ - else { - CURLcode result; - ssl_sessionid = - aprintf("%s:%d:%d:%s:%hu", data->set.str[STRING_SSL_CAFILE], - data->set.ssl.verifypeer, data->set.ssl.verifyhost, - conn->host.name, conn->remote_port); - ssl_sessionid_len = strlen(ssl_sessionid); - - err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len); - if(err != noErr) { - failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); - return CURLE_SSL_CONNECT_ERROR; + if(conn->ssl_config.sessionid) { + char *ssl_sessionid; + size_t ssl_sessionid_len; + + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, (void **)&ssl_sessionid, + &ssl_sessionid_len)) { + /* we got a session id, use it! */ + err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len); + Curl_ssl_sessionid_unlock(conn); + if(err != noErr) { + failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } + /* Informational message */ + infof(data, "SSL re-using session ID\n"); } + /* If there isn't one, then let's make one up! This has to be done prior + to starting the handshake. */ + else { + CURLcode result; + ssl_sessionid = + aprintf("%s:%d:%d:%s:%hu", data->set.str[STRING_SSL_CAFILE], + data->set.ssl.verifypeer, data->set.ssl.verifyhost, + conn->host.name, conn->remote_port); + ssl_sessionid_len = strlen(ssl_sessionid); + + err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len); + if(err != noErr) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); + return CURLE_SSL_CONNECT_ERROR; + } - result = Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_sessionid_len); - if(result) { - failf(data, "failed to store ssl session"); - return result; + result = Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_sessionid_len); + Curl_ssl_sessionid_unlock(conn); + if(result) { + failf(data, "failed to store ssl session"); + return result; + } } } @@ -1620,7 +1633,7 @@ static int read_cert(const char *file, unsigned char **out, size_t *outlen) return 0; } -static int sslerr_to_curlerr(struct SessionHandle *data, int err) +static int sslerr_to_curlerr(struct Curl_easy *data, int err) { switch(err) { case errSSLXCertChainInvalid: @@ -1649,7 +1662,7 @@ static int sslerr_to_curlerr(struct SessionHandle *data, int err) } } -static int append_cert_to_array(struct SessionHandle *data, +static int append_cert_to_array(struct Curl_easy *data, unsigned char *buf, size_t buflen, CFMutableArrayRef array) { @@ -1694,7 +1707,7 @@ static int append_cert_to_array(struct SessionHandle *data, return CURLE_OK; } -static int verify_cert(const char *cafile, struct SessionHandle *data, +static int verify_cert(const char *cafile, struct Curl_easy *data, SSLContextRef ctx) { int n = 0, rc; @@ -1814,7 +1827,7 @@ static int verify_cert(const char *cafile, struct SessionHandle *data, static CURLcode darwinssl_connect_step2(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; OSStatus err; SSLCipherSuite cipher; @@ -1954,7 +1967,7 @@ static CURLcode darwinssl_connect_step3(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CFStringRef server_cert_summary; char server_cert_summary_c[128]; @@ -2078,7 +2091,7 @@ darwinssl_connect_common(struct connectdata *conn, bool *done) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; @@ -2233,7 +2246,7 @@ void Curl_darwinssl_close(struct connectdata *conn, int sockindex) int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; ssize_t nread; int what; int rc; @@ -2381,7 +2394,7 @@ static ssize_t darwinssl_send(struct connectdata *conn, size_t len, CURLcode *curlcode) { - /*struct SessionHandle *data = conn->data;*/ + /*struct Curl_easy *data = conn->data;*/ struct ssl_connect_data *connssl = &conn->ssl[sockindex]; size_t processed = 0UL; OSStatus err; @@ -2447,7 +2460,7 @@ static ssize_t darwinssl_recv(struct connectdata *conn, size_t buffersize, CURLcode *curlcode) { - /*struct SessionHandle *data = conn->data;*/ + /*struct Curl_easy *data = conn->data;*/ struct ssl_connect_data *connssl = &conn->ssl[num]; size_t processed = 0UL; OSStatus err = SSLRead(connssl->ssl_ctx, buf, buffersize, &processed); diff --git a/Utilities/cmcurl/lib/vtls/darwinssl.h b/Utilities/cmcurl/lib/vtls/darwinssl.h index 3bb69c0..8b185b6 100644 --- a/Utilities/cmcurl/lib/vtls/darwinssl.h +++ b/Utilities/cmcurl/lib/vtls/darwinssl.h @@ -12,7 +12,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/vtls/gskit.c b/Utilities/cmcurl/lib/vtls/gskit.c index d884bd4..55a55ef 100644 --- a/Utilities/cmcurl/lib/vtls/gskit.c +++ b/Utilities/cmcurl/lib/vtls/gskit.c @@ -9,7 +9,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -163,7 +163,7 @@ static bool is_separator(char c) } -static CURLcode gskit_status(struct SessionHandle *data, int rc, +static CURLcode gskit_status(struct Curl_easy *data, int rc, const char *procname, CURLcode defcode) { /* Process GSKit status and map it to a CURLcode. */ @@ -206,7 +206,7 @@ static CURLcode gskit_status(struct SessionHandle *data, int rc, } -static CURLcode set_enum(struct SessionHandle *data, gsk_handle h, +static CURLcode set_enum(struct Curl_easy *data, gsk_handle h, GSK_ENUM_ID id, GSK_ENUM_VALUE value, bool unsupported_ok) { int rc = gsk_attribute_set_enum(h, id, value); @@ -228,7 +228,7 @@ static CURLcode set_enum(struct SessionHandle *data, gsk_handle h, } -static CURLcode set_buffer(struct SessionHandle *data, gsk_handle h, +static CURLcode set_buffer(struct Curl_easy *data, gsk_handle h, GSK_BUF_ID id, const char *buffer, bool unsupported_ok) { int rc = gsk_attribute_set_buffer(h, id, buffer, 0); @@ -250,7 +250,7 @@ static CURLcode set_buffer(struct SessionHandle *data, gsk_handle h, } -static CURLcode set_numeric(struct SessionHandle *data, +static CURLcode set_numeric(struct Curl_easy *data, gsk_handle h, GSK_NUM_ID id, int value) { int rc = gsk_attribute_set_numeric_value(h, id, value); @@ -270,7 +270,7 @@ static CURLcode set_numeric(struct SessionHandle *data, } -static CURLcode set_callback(struct SessionHandle *data, +static CURLcode set_callback(struct Curl_easy *data, gsk_handle h, GSK_CALLBACK_ID id, void *info) { int rc = gsk_attribute_set_callback(h, id, info); @@ -289,7 +289,7 @@ static CURLcode set_callback(struct SessionHandle *data, } -static CURLcode set_ciphers(struct SessionHandle *data, +static CURLcode set_ciphers(struct Curl_easy *data, gsk_handle h, unsigned int *protoflags) { const char *cipherlist = data->set.str[STRING_SSL_CIPHER_LIST]; @@ -436,7 +436,7 @@ void Curl_gskit_cleanup(void) } -static CURLcode init_environment(struct SessionHandle *data, +static CURLcode init_environment(struct Curl_easy *data, gsk_handle *envir, const char *appid, const char *file, const char *label, const char *password) @@ -502,7 +502,7 @@ static void close_async_handshake(struct ssl_connect_data *connssl) static void close_one(struct ssl_connect_data *conn, - struct SessionHandle *data) + struct Curl_easy *data) { if(conn->handle) { gskit_status(data, gsk_secure_soc_close(&conn->handle), @@ -517,7 +517,7 @@ static void close_one(struct ssl_connect_data *conn, static ssize_t gskit_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode cc; int written; @@ -536,7 +536,7 @@ static ssize_t gskit_send(struct connectdata *conn, int sockindex, static ssize_t gskit_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int buffsize; int nread; CURLcode cc; @@ -555,7 +555,7 @@ static ssize_t gskit_recv(struct connectdata *conn, int num, char *buf, static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; gsk_handle envir; CURLcode result; @@ -750,7 +750,7 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex) static CURLcode gskit_connect_step2(struct connectdata *conn, int sockindex, bool nonblocking) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; Qso_OverlappedIO_t cstat; long timeout_ms; @@ -801,7 +801,7 @@ static CURLcode gskit_connect_step2(struct connectdata *conn, int sockindex, static CURLcode gskit_connect_step3(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; const gsk_cert_data_elem *cdev; int cdec; @@ -874,7 +874,7 @@ static CURLcode gskit_connect_step3(struct connectdata *conn, int sockindex) return CURLE_SSL_PINNEDPUBKEYNOTMATCH; Curl_parseX509(&x509, cert, certend); p = &x509.subjectPublicKeyInfo; - result = Curl_pin_peer_pubkey(ptr, p->header, p->end - p->header); + result = Curl_pin_peer_pubkey(data, ptr, p->header, p->end - p->header); if(result) { failf(data, "SSL: public key does not match pinned public key!"); return result; @@ -889,7 +889,7 @@ static CURLcode gskit_connect_step3(struct connectdata *conn, int sockindex) static CURLcode gskit_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; long timeout_ms; Qso_OverlappedIO_t cstat; @@ -976,7 +976,7 @@ CURLcode Curl_gskit_connect(struct connectdata *conn, int sockindex) void Curl_gskit_close(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->use) @@ -987,7 +987,7 @@ void Curl_gskit_close(struct connectdata *conn, int sockindex) int Curl_gskit_shutdown(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; ssize_t nread; int what; int rc; diff --git a/Utilities/cmcurl/lib/vtls/gskit.h b/Utilities/cmcurl/lib/vtls/gskit.h index af31faf..41483cb 100644 --- a/Utilities/cmcurl/lib/vtls/gskit.h +++ b/Utilities/cmcurl/lib/vtls/gskit.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is diff --git a/Utilities/cmcurl/lib/vtls/gtls.c b/Utilities/cmcurl/lib/vtls/gtls.c index c54dfc1..1c3e6b1 100644 --- a/Utilities/cmcurl/lib/vtls/gtls.c +++ b/Utilities/cmcurl/lib/vtls/gtls.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -62,7 +62,7 @@ /* Some hackish cast macros based on: - http://library.gnome.org/devel/glib/unstable/glib-Type-Conversion-Macros.html + https://developer.gnome.org/glib/unstable/glib-Type-Conversion-Macros.html */ #ifndef GNUTLS_POINTER_TO_INT_CAST #define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p)) @@ -201,7 +201,7 @@ int Curl_gtls_cleanup(void) return 1; } -static void showtime(struct SessionHandle *data, +static void showtime(struct Curl_easy *data, const char *text, time_t stamp) { @@ -262,7 +262,7 @@ static CURLcode handshake(struct connectdata *conn, bool duringconnect, bool nonblocking) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; gnutls_session_t session = conn->ssl[sockindex].session; curl_socket_t sockfd = conn->sock[sockindex]; @@ -367,11 +367,9 @@ static CURLcode gtls_connect_step1(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; gnutls_session_t session; int rc; - void *ssl_sessionid; - size_t ssl_idsize; bool sni = TRUE; /* default is SNI enabled */ #ifdef ENABLE_IPV6 struct in6_addr addr; @@ -487,6 +485,14 @@ gtls_connect_step1(struct connectdata *conn, } #endif +#ifdef CURL_CA_FALLBACK + /* use system ca certificate store as fallback */ + if(data->set.ssl.verifypeer && + !(data->set.ssl.CAfile || data->set.ssl.CApath)) { + gnutls_certificate_set_x509_system_trust(conn->ssl[sockindex].cred); + } +#endif + if(data->set.ssl.CRLfile) { /* set the CRL list file */ rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred, @@ -633,12 +639,12 @@ gtls_connect_step1(struct connectdata *conn, #endif #ifdef HAS_ALPN - if(data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_alpn) { int cur = 0; gnutls_datum_t protocols[2]; #ifdef USE_NGHTTP2 - if(data->set.httpversion == CURL_HTTP_VERSION_2_0) { + if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur].data = (unsigned char *)NGHTTP2_PROTO_VERSION_ID; protocols[cur].size = NGHTTP2_PROTO_VERSION_ID_LEN; cur++; @@ -656,15 +662,44 @@ gtls_connect_step1(struct connectdata *conn, #endif if(data->set.str[STRING_CERT]) { - if(gnutls_certificate_set_x509_key_file( - conn->ssl[sockindex].cred, - data->set.str[STRING_CERT], - data->set.str[STRING_KEY] ? - data->set.str[STRING_KEY] : data->set.str[STRING_CERT], - do_file_type(data->set.str[STRING_CERT_TYPE]) ) != - GNUTLS_E_SUCCESS) { - failf(data, "error reading X.509 key or certificate file"); + if(data->set.str[STRING_KEY_PASSWD]) { +#if HAVE_GNUTLS_CERTIFICATE_SET_X509_KEY_FILE2 + const unsigned int supported_key_encryption_algorithms = + GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR | + GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES | + GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 | + GNUTLS_PKCS_USE_PBES2_AES_256; + rc = gnutls_certificate_set_x509_key_file2( + conn->ssl[sockindex].cred, + data->set.str[STRING_CERT], + data->set.str[STRING_KEY] ? + data->set.str[STRING_KEY] : data->set.str[STRING_CERT], + do_file_type(data->set.str[STRING_CERT_TYPE]), + data->set.str[STRING_KEY_PASSWD], + supported_key_encryption_algorithms); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, + "error reading X.509 potentially-encrypted key file: %s", + gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } +#else + failf(data, "gnutls lacks support for encrypted key files"); return CURLE_SSL_CONNECT_ERROR; +#endif + } + else { + rc = gnutls_certificate_set_x509_key_file( + conn->ssl[sockindex].cred, + data->set.str[STRING_CERT], + data->set.str[STRING_KEY] ? + data->set.str[STRING_KEY] : data->set.str[STRING_CERT], + do_file_type(data->set.str[STRING_CERT_TYPE]) ); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "error reading X.509 key or certificate file: %s", + gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } } } @@ -712,19 +747,26 @@ gtls_connect_step1(struct connectdata *conn, /* This might be a reconnect, so we check for a session ID in the cache to speed up things */ + if(conn->ssl_config.sessionid) { + void *ssl_sessionid; + size_t ssl_idsize; - if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) { - /* we got a session id, use it! */ - gnutls_session_set_data(session, ssl_sessionid, ssl_idsize); + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) { + /* we got a session id, use it! */ + gnutls_session_set_data(session, ssl_sessionid, ssl_idsize); - /* Informational message */ - infof (data, "SSL re-using session ID\n"); + /* Informational message */ + infof (data, "SSL re-using session ID\n"); + } + Curl_ssl_sessionid_unlock(conn); } return CURLE_OK; } -static CURLcode pkp_pin_peer_pubkey(gnutls_x509_crt_t cert, +static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, + gnutls_x509_crt_t cert, const char *pinnedpubkey) { /* Scratch */ @@ -769,7 +811,7 @@ static CURLcode pkp_pin_peer_pubkey(gnutls_x509_crt_t cert, /* End Gyrations */ /* The one good exit point */ - result = Curl_pin_peer_pubkey(pinnedpubkey, buff1, len1); + result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); } while(0); if(NULL != key) @@ -798,11 +840,9 @@ gtls_connect_step3(struct connectdata *conn, unsigned int bits; time_t certclock; const char *ptr; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; gnutls_session_t session = conn->ssl[sockindex].session; int rc; - bool incache; - void *ssl_sessionid; #ifdef HAS_ALPN gnutls_datum_t proto; #endif @@ -1152,7 +1192,7 @@ gtls_connect_step3(struct connectdata *conn, ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; if(ptr) { - result = pkp_pin_peer_pubkey(x509_cert, ptr); + result = pkp_pin_peer_pubkey(data, x509_cert, ptr); if(result != CURLE_OK) { failf(data, "SSL: public key does not match pinned public key!"); gnutls_x509_crt_deinit(x509_cert); @@ -1202,7 +1242,7 @@ gtls_connect_step3(struct connectdata *conn, infof(data, "\t compression: %s\n", ptr); #ifdef HAS_ALPN - if(data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_alpn) { rc = gnutls_alpn_get_selected_protocol(session, &proto); if(rc == 0) { infof(data, "ALPN, server accepted to use %.*s\n", proto.size, @@ -1212,7 +1252,7 @@ gtls_connect_step3(struct connectdata *conn, if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data, NGHTTP2_PROTO_VERSION_ID_LEN)) { - conn->negnpn = CURL_HTTP_VERSION_2_0; + conn->negnpn = CURL_HTTP_VERSION_2; } else #endif @@ -1230,11 +1270,13 @@ gtls_connect_step3(struct connectdata *conn, conn->recv[sockindex] = gtls_recv; conn->send[sockindex] = gtls_send; - { + if(conn->ssl_config.sessionid) { /* we always unconditionally get the session id here, as even if we already got it from the cache and asked to use it in the connection, it might've been rejected and then a new one is in use now and we need to detect that. */ + bool incache; + void *ssl_sessionid; void *connect_sessionid; size_t connect_idsize = 0; @@ -1246,6 +1288,7 @@ gtls_connect_step3(struct connectdata *conn, /* extract session ID to the allocated buffer */ gnutls_session_get_data(session, connect_sessionid, &connect_idsize); + Curl_ssl_sessionid_lock(conn); incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)); if(incache) { /* there was one before in the cache, so instead of risking that the @@ -1255,6 +1298,7 @@ gtls_connect_step3(struct connectdata *conn, /* store this session id */ result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize); + Curl_ssl_sessionid_unlock(conn); if(result) { free(connect_sessionid); result = CURLE_OUT_OF_MEMORY; @@ -1343,7 +1387,7 @@ static ssize_t gtls_send(struct connectdata *conn, { ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len); - if(rc < 0 ) { + if(rc < 0) { *curlcode = (rc == GNUTLS_E_AGAIN) ? CURLE_AGAIN : CURLE_SEND_ERROR; @@ -1387,7 +1431,7 @@ int Curl_gtls_shutdown(struct connectdata *conn, int sockindex) { ssize_t result; int retval = 0; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int done = 0; char buf[120]; @@ -1500,7 +1544,7 @@ size_t Curl_gtls_version(char *buffer, size_t size) } #ifndef USE_GNUTLS_NETTLE -static int Curl_gtls_seed(struct SessionHandle *data) +static int Curl_gtls_seed(struct Curl_easy *data) { /* we have the "SSL is seeded" boolean static to prevent multiple time-consuming seedings in vain */ @@ -1524,7 +1568,7 @@ static int Curl_gtls_seed(struct SessionHandle *data) #endif /* data might be NULL! */ -int Curl_gtls_random(struct SessionHandle *data, +int Curl_gtls_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { diff --git a/Utilities/cmcurl/lib/vtls/gtls.h b/Utilities/cmcurl/lib/vtls/gtls.h index 0afd9b9..e0a95a7 100644 --- a/Utilities/cmcurl/lib/vtls/gtls.h +++ b/Utilities/cmcurl/lib/vtls/gtls.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -41,7 +41,7 @@ void Curl_gtls_close(struct connectdata *conn, int sockindex); void Curl_gtls_session_free(void *ptr); size_t Curl_gtls_version(char *buffer, size_t size); int Curl_gtls_shutdown(struct connectdata *conn, int sockindex); -int Curl_gtls_random(struct SessionHandle *data, +int Curl_gtls_random(struct Curl_easy *data, unsigned char *entropy, size_t length); void Curl_gtls_md5sum(unsigned char *tmp, /* input */ @@ -64,6 +64,9 @@ bool Curl_gtls_cert_status_request(void); /* this backend supports CURLOPT_CERTINFO */ #define have_curlssl_certinfo 1 +/* this backend supports CURLOPT_PINNEDPUBLICKEY */ +#define have_curlssl_pinnedpubkey 1 + /* API setup for GnuTLS */ #define curlssl_init Curl_gtls_init #define curlssl_cleanup Curl_gtls_cleanup diff --git a/Utilities/cmcurl/lib/vtls/mbedtls.c b/Utilities/cmcurl/lib/vtls/mbedtls.c new file mode 100644 index 0000000..a1e7d23 --- /dev/null +++ b/Utilities/cmcurl/lib/vtls/mbedtls.c @@ -0,0 +1,871 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* + * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code + * but vtls.c should ever call or use these functions. + * + */ + +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +#include <mbedtls/net.h> +#include <mbedtls/ssl.h> +#include <mbedtls/certs.h> +#include <mbedtls/x509.h> +#include <mbedtls/version.h> + +#include <mbedtls/error.h> +#include <mbedtls/entropy.h> +#include <mbedtls/ctr_drbg.h> +#include <mbedtls/sha256.h> + +#include "urldata.h" +#include "sendf.h" +#include "inet_pton.h" +#include "mbedtls.h" +#include "vtls.h" +#include "parsedate.h" +#include "connect.h" /* for the connect timeout */ +#include "select.h" +#include "rawstr.h" +#include "polarssl_threadlock.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* apply threading? */ +#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) +#define THREADING_SUPPORT +#endif + +#if defined(THREADING_SUPPORT) +static mbedtls_entropy_context entropy; + +static int entropy_init_initialized = 0; + +/* start of entropy_init_mutex() */ +static void entropy_init_mutex(mbedtls_entropy_context *ctx) +{ + /* lock 0 = entropy_init_mutex() */ + Curl_polarsslthreadlock_lock_function(0); + if(entropy_init_initialized == 0) { + mbedtls_entropy_init(ctx); + entropy_init_initialized = 1; + } + Curl_polarsslthreadlock_unlock_function(0); +} +/* end of entropy_init_mutex() */ + +/* start of entropy_func_mutex() */ +static int entropy_func_mutex(void *data, unsigned char *output, size_t len) +{ + int ret; + /* lock 1 = entropy_func_mutex() */ + Curl_polarsslthreadlock_lock_function(1); + ret = mbedtls_entropy_func(data, output, len); + Curl_polarsslthreadlock_unlock_function(1); + + return ret; +} +/* end of entropy_func_mutex() */ + +#endif /* THREADING_SUPPORT */ + +/* Define this to enable lots of debugging for mbedTLS */ +#undef MBEDTLS_DEBUG + +#ifdef MBEDTLS_DEBUG +static void mbed_debug(void *context, int level, const char *f_name, + int line_nb, const char *line) +{ + struct Curl_easy *data = NULL; + + if(!context) + return; + + data = (struct Curl_easy *)context; + + infof(data, "%s", line); + (void) level; +} +#else +#endif + +/* ALPN for http2? */ +#ifdef USE_NGHTTP2 +# undef HAS_ALPN +# ifdef MBEDTLS_SSL_ALPN +# define HAS_ALPN +# endif +#endif + + +/* + * profile + */ +const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr = +{ + /* Hashes from SHA-1 and above */ + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | + MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512), + 0xFFFFFFF, /* Any PK alg */ + 0xFFFFFFF, /* Any curve */ + 1024, /* RSA min key len */ +}; + +/* See https://tls.mbed.org/discussions/generic/ + howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der +*/ +#define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE) +#define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES) + +#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \ + RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES) + +static Curl_recv mbed_recv; +static Curl_send mbed_send; + +static CURLcode +mbed_connect_step1(struct connectdata *conn, + int sockindex) +{ + struct Curl_easy *data = conn->data; + struct ssl_connect_data* connssl = &conn->ssl[sockindex]; + + int ret = -1; + char errorbuf[128]; + errorbuf[0]=0; + + /* mbedTLS only supports SSLv3 and TLSv1 */ + if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) { + failf(data, "mbedTLS does not support SSLv2"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef THREADING_SUPPORT + entropy_init_mutex(&entropy); + mbedtls_ctr_drbg_init(&connssl->ctr_drbg); + + ret = mbedtls_ctr_drbg_seed(&connssl->ctr_drbg, entropy_func_mutex, + &entropy, NULL, 0); + if(ret) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n", + -ret, errorbuf); + } +#else + mbedtls_entropy_init(&connssl->entropy); + mbedtls_ctr_drbg_init(&connssl->ctr_drbg); + + ret = mbedtls_ctr_drbg_seed(&connssl->ctr_drbg, mbedtls_entropy_func, + &connssl->entropy, NULL, 0); + if(ret) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n", + -ret, errorbuf); + } +#endif /* THREADING_SUPPORT */ + + /* Load the trusted CA */ + mbedtls_x509_crt_init(&connssl->cacert); + + if(data->set.str[STRING_SSL_CAFILE]) { + ret = mbedtls_x509_crt_parse_file(&connssl->cacert, + data->set.str[STRING_SSL_CAFILE]); + + if(ret<0) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s", + data->set.str[STRING_SSL_CAFILE], -ret, errorbuf); + + if(data->set.ssl.verifypeer) + return CURLE_SSL_CACERT_BADFILE; + } + } + + if(data->set.str[STRING_SSL_CAPATH]) { + ret = mbedtls_x509_crt_parse_path(&connssl->cacert, + data->set.str[STRING_SSL_CAPATH]); + + if(ret<0) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s", + data->set.str[STRING_SSL_CAPATH], -ret, errorbuf); + + if(data->set.ssl.verifypeer) + return CURLE_SSL_CACERT_BADFILE; + } + } + + /* Load the client certificate */ + mbedtls_x509_crt_init(&connssl->clicert); + + if(data->set.str[STRING_CERT]) { + ret = mbedtls_x509_crt_parse_file(&connssl->clicert, + data->set.str[STRING_CERT]); + + if(ret) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s", + data->set.str[STRING_CERT], -ret, errorbuf); + + return CURLE_SSL_CERTPROBLEM; + } + } + + /* Load the client private key */ + mbedtls_pk_init(&connssl->pk); + + if(data->set.str[STRING_KEY]) { + ret = mbedtls_pk_parse_keyfile(&connssl->pk, data->set.str[STRING_KEY], + data->set.str[STRING_KEY_PASSWD]); + if(ret == 0 && !mbedtls_pk_can_do(&connssl->pk, MBEDTLS_PK_RSA)) + ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; + + if(ret) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s", + data->set.str[STRING_KEY], -ret, errorbuf); + + return CURLE_SSL_CERTPROBLEM; + } + } + + /* Load the CRL */ + mbedtls_x509_crl_init(&connssl->crl); + + if(data->set.str[STRING_SSL_CRLFILE]) { + ret = mbedtls_x509_crl_parse_file(&connssl->crl, + data->set.str[STRING_SSL_CRLFILE]); + + if(ret) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s", + data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf); + + return CURLE_SSL_CRL_BADFILE; + } + } + + infof(data, "mbedTLS: Connecting to %s:%d\n", + conn->host.name, conn->remote_port); + + mbedtls_ssl_config_init(&connssl->config); + + mbedtls_ssl_init(&connssl->ssl); + if(mbedtls_ssl_setup(&connssl->ssl, &connssl->config)) { + failf(data, "mbedTLS: ssl_init failed"); + return CURLE_SSL_CONNECT_ERROR; + } + ret = mbedtls_ssl_config_defaults(&connssl->config, + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); + if(ret) { + failf(data, "mbedTLS: ssl_config failed"); + return CURLE_SSL_CONNECT_ERROR; + } + + /* new profile with RSA min key len = 1024 ... */ + mbedtls_ssl_conf_cert_profile(&connssl->config, + &mbedtls_x509_crt_profile_fr); + + switch(data->set.ssl.version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_1); + infof(data, "mbedTLS: Set min SSL version to TLS 1.0\n"); + break; + case CURL_SSLVERSION_SSLv3: + mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_0); + mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_0); + infof(data, "mbedTLS: Set SSL version to SSLv3\n"); + break; + case CURL_SSLVERSION_TLSv1_0: + mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_1); + mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_1); + infof(data, "mbedTLS: Set SSL version to TLS 1.0\n"); + break; + case CURL_SSLVERSION_TLSv1_1: + mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_2); + mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_2); + infof(data, "mbedTLS: Set SSL version to TLS 1.1\n"); + break; + case CURL_SSLVERSION_TLSv1_2: + mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_3); + mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_3); + infof(data, "mbedTLS: Set SSL version to TLS 1.2\n"); + break; + default: + failf(data, "mbedTLS: Unsupported SSL protocol version"); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_conf_authmode(&connssl->config, MBEDTLS_SSL_VERIFY_OPTIONAL); + + mbedtls_ssl_conf_rng(&connssl->config, mbedtls_ctr_drbg_random, + &connssl->ctr_drbg); + mbedtls_ssl_set_bio(&connssl->ssl, &conn->sock[sockindex], + mbedtls_net_send, + mbedtls_net_recv, + NULL /* rev_timeout() */); + + mbedtls_ssl_conf_ciphersuites(&connssl->config, + mbedtls_ssl_list_ciphersuites()); + + /* Check if there's a cached ID we can/should use here! */ + if(conn->ssl_config.sessionid) { + void *old_session = NULL; + + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) { + ret = mbedtls_ssl_set_session(&connssl->ssl, old_session); + if(ret) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; + } + infof(data, "mbedTLS re-using session\n"); + } + Curl_ssl_sessionid_unlock(conn); + } + + mbedtls_ssl_conf_ca_chain(&connssl->config, + &connssl->cacert, + &connssl->crl); + + if(data->set.str[STRING_KEY]) { + mbedtls_ssl_conf_own_cert(&connssl->config, + &connssl->clicert, &connssl->pk); + } + if(mbedtls_ssl_set_hostname(&connssl->ssl, conn->host.name)) { + /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and* + the name to set in the SNI extension. So even if curl connects to a + host specified as an IP address, this function must be used. */ + failf(data, "couldn't set hostname in mbedTLS"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifdef HAS_ALPN + if(conn->bits.tls_enable_alpn) { + const char **p = &connssl->protocols[0]; +#ifdef USE_NGHTTP2 + if(data->set.httpversion >= CURL_HTTP_VERSION_2) + *p++ = NGHTTP2_PROTO_VERSION_ID; +#endif + *p++ = ALPN_HTTP_1_1; + *p = NULL; + /* this function doesn't clone the protocols array, which is why we need + to keep it around */ + if(mbedtls_ssl_conf_alpn_protocols(&connssl->config, + &connssl->protocols[0])) { + failf(data, "Failed setting ALPN protocols"); + return CURLE_SSL_CONNECT_ERROR; + } + for(p = &connssl->protocols[0]; *p; ++p) + infof(data, "ALPN, offering %s\n", *p); + } +#endif + +#ifdef MBEDTLS_DEBUG + mbedtls_ssl_conf_dbg(&connssl->config, mbed_debug, data); +#endif + + connssl->connecting_state = ssl_connect_2; + + return CURLE_OK; +} + +static CURLcode +mbed_connect_step2(struct connectdata *conn, + int sockindex) +{ + int ret; + struct Curl_easy *data = conn->data; + struct ssl_connect_data* connssl = &conn->ssl[sockindex]; + const mbedtls_x509_crt *peercert; + +#ifdef HAS_ALPN + const char* next_protocol; +#endif + + char errorbuf[128]; + errorbuf[0] = 0; + + conn->recv[sockindex] = mbed_recv; + conn->send[sockindex] = mbed_send; + + ret = mbedtls_ssl_handshake(&connssl->ssl); + + if(ret == MBEDTLS_ERR_SSL_WANT_READ) { + connssl->connecting_state = ssl_connect_2_reading; + return CURLE_OK; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + connssl->connecting_state = ssl_connect_2_writing; + return CURLE_OK; + } + else if(ret) { +#ifdef MBEDTLS_ERROR_C + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); +#endif /* MBEDTLS_ERROR_C */ + failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } + + infof(data, "mbedTLS: Handshake complete, cipher is %s\n", + mbedtls_ssl_get_ciphersuite(&conn->ssl[sockindex].ssl) + ); + + ret = mbedtls_ssl_get_verify_result(&conn->ssl[sockindex].ssl); + + if(ret && data->set.ssl.verifypeer) { + if(ret & MBEDTLS_X509_BADCERT_EXPIRED) + failf(data, "Cert verify failed: BADCERT_EXPIRED"); + + if(ret & MBEDTLS_X509_BADCERT_REVOKED) { + failf(data, "Cert verify failed: BADCERT_REVOKED"); + return CURLE_SSL_CACERT; + } + + if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) + failf(data, "Cert verify failed: BADCERT_CN_MISMATCH"); + + if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED) + failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED"); + + return CURLE_PEER_FAILED_VERIFICATION; + } + + peercert = mbedtls_ssl_get_peer_cert(&connssl->ssl); + + if(peercert && data->set.verbose) { + const size_t bufsize = 16384; + char *buffer = malloc(bufsize); + + if(!buffer) + return CURLE_OUT_OF_MEMORY; + + if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0) + infof(data, "Dumping cert info:\n%s\n", buffer); + else + infof(data, "Unable to dump certificate information.\n"); + + free(buffer); + } + + if(data->set.str[STRING_SSL_PINNEDPUBLICKEY]) { + int size; + CURLcode result; + mbedtls_x509_crt *p; + unsigned char pubkey[PUB_DER_MAX_BYTES]; + + if(!peercert || !peercert->raw.p || !peercert->raw.len) { + failf(data, "Failed due to missing peer certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + p = calloc(1, sizeof(*p)); + + if(!p) + return CURLE_OUT_OF_MEMORY; + + mbedtls_x509_crt_init(p); + + /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der + needs a non-const key, for now. + https://github.com/ARMmbed/mbedtls/issues/396 */ + if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) { + failf(data, "Failed copying peer certificate"); + mbedtls_x509_crt_free(p); + free(p); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES); + + if(size <= 0) { + failf(data, "Failed copying public key from peer certificate"); + mbedtls_x509_crt_free(p); + free(p); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */ + result = Curl_pin_peer_pubkey(data, + data->set.str[STRING_SSL_PINNEDPUBLICKEY], + &pubkey[PUB_DER_MAX_BYTES - size], size); + if(result) { + mbedtls_x509_crt_free(p); + free(p); + return result; + } + + mbedtls_x509_crt_free(p); + free(p); + } + +#ifdef HAS_ALPN + if(conn->bits.tls_enable_alpn) { + next_protocol = mbedtls_ssl_get_alpn_protocol(&connssl->ssl); + + if(next_protocol) { + infof(data, "ALPN, server accepted to use %s\n", next_protocol); +#ifdef USE_NGHTTP2 + if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID, + NGHTTP2_PROTO_VERSION_ID_LEN) && + !next_protocol[NGHTTP2_PROTO_VERSION_ID_LEN]) { + conn->negnpn = CURL_HTTP_VERSION_2; + } + else +#endif + if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH) && + !next_protocol[ALPN_HTTP_1_1_LENGTH]) { + conn->negnpn = CURL_HTTP_VERSION_1_1; + } + } + else { + infof(data, "ALPN, server did not agree to a protocol\n"); + } + } +#endif + + connssl->connecting_state = ssl_connect_3; + infof(data, "SSL connected\n"); + + return CURLE_OK; +} + +static CURLcode +mbed_connect_step3(struct connectdata *conn, + int sockindex) +{ + CURLcode retcode = CURLE_OK; + struct ssl_connect_data *connssl = &conn->ssl[sockindex]; + struct Curl_easy *data = conn->data; + + DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); + + if(conn->ssl_config.sessionid) { + int ret; + mbedtls_ssl_session *our_ssl_sessionid; + void *old_ssl_sessionid = NULL; + + our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session)); + if(!our_ssl_sessionid) + return CURLE_OUT_OF_MEMORY; + + mbedtls_ssl_session_init(our_ssl_sessionid); + + ret = mbedtls_ssl_get_session(&connssl->ssl, our_ssl_sessionid); + if(ret) { + failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; + } + + /* If there's already a matching session in the cache, delete it */ + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)) + Curl_ssl_delsessionid(conn, old_ssl_sessionid); + + retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0); + Curl_ssl_sessionid_unlock(conn); + if(retcode) { + free(our_ssl_sessionid); + failf(data, "failed to store ssl session"); + return retcode; + } + } + + connssl->connecting_state = ssl_connect_done; + + return CURLE_OK; +} + +static ssize_t mbed_send(struct connectdata *conn, int sockindex, + const void *mem, size_t len, + CURLcode *curlcode) +{ + int ret = -1; + + ret = mbedtls_ssl_write(&conn->ssl[sockindex].ssl, + (unsigned char *)mem, len); + + if(ret < 0) { + *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ? + CURLE_AGAIN : CURLE_SEND_ERROR; + ret = -1; + } + + return ret; +} + +void Curl_mbedtls_close_all(struct Curl_easy *data) +{ + (void)data; +} + +void Curl_mbedtls_close(struct connectdata *conn, int sockindex) +{ + mbedtls_pk_free(&conn->ssl[sockindex].pk); + mbedtls_x509_crt_free(&conn->ssl[sockindex].clicert); + mbedtls_x509_crt_free(&conn->ssl[sockindex].cacert); + mbedtls_x509_crl_free(&conn->ssl[sockindex].crl); + mbedtls_ssl_config_free(&conn->ssl[sockindex].config); + mbedtls_ssl_free(&conn->ssl[sockindex].ssl); + mbedtls_ctr_drbg_free(&conn->ssl[sockindex].ctr_drbg); +#ifndef THREADING_SUPPORT + mbedtls_entropy_free(&conn->ssl[sockindex].entropy); +#endif /* THREADING_SUPPORT */ +} + +static ssize_t mbed_recv(struct connectdata *conn, int num, + char *buf, size_t buffersize, + CURLcode *curlcode) +{ + int ret = -1; + ssize_t len = -1; + + memset(buf, 0, buffersize); + ret = mbedtls_ssl_read(&conn->ssl[num].ssl, (unsigned char *)buf, + buffersize); + + if(ret <= 0) { + if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) + return 0; + + *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_READ) ? + CURLE_AGAIN : CURLE_RECV_ERROR; + return -1; + } + + len = ret; + + return len; +} + +void Curl_mbedtls_session_free(void *ptr) +{ + mbedtls_ssl_session_free(ptr); + free(ptr); +} + +size_t Curl_mbedtls_version(char *buffer, size_t size) +{ + unsigned int version = mbedtls_version_get_number(); + return snprintf(buffer, size, "mbedTLS/%d.%d.%d", version>>24, + (version>>16)&0xff, (version>>8)&0xff); +} + +static CURLcode +mbed_connect_common(struct connectdata *conn, + int sockindex, + bool nonblocking, + bool *done) +{ + CURLcode retcode; + struct Curl_easy *data = conn->data; + struct ssl_connect_data *connssl = &conn->ssl[sockindex]; + curl_socket_t sockfd = conn->sock[sockindex]; + long timeout_ms; + int what; + + /* check if the connection has already been established */ + if(ssl_connection_complete == connssl->state) { + *done = TRUE; + return CURLE_OK; + } + + if(ssl_connect_1==connssl->connecting_state) { + /* Find out how much more time we're allowed */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + retcode = mbed_connect_step1(conn, sockindex); + if(retcode) + return retcode; + } + + while(ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state) { + + /* check allowed time left */ + timeout_ms = Curl_timeleft(data, NULL, TRUE); + + if(timeout_ms < 0) { + /* no need to continue if time already is up */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + /* if ssl is expecting something, check if it's available. */ + if(connssl->connecting_state == ssl_connect_2_reading + || connssl->connecting_state == ssl_connect_2_writing) { + + curl_socket_t writefd = ssl_connect_2_writing== + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + curl_socket_t readfd = ssl_connect_2_reading== + connssl->connecting_state?sockfd:CURL_SOCKET_BAD; + + what = Curl_socket_ready(readfd, writefd, nonblocking ? 0 : timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + return CURLE_SSL_CONNECT_ERROR; + } + else if(0 == what) { + if(nonblocking) { + *done = FALSE; + return CURLE_OK; + } + else { + /* timeout */ + failf(data, "SSL connection timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + /* Run transaction, and return to the caller if it failed or if + * this connection is part of a multi handle and this loop would + * execute again. This permits the owner of a multi handle to + * abort a connection attempt before step2 has completed while + * ensuring that a client using select() or epoll() will always + * have a valid fdset to wait on. + */ + retcode = mbed_connect_step2(conn, sockindex); + if(retcode || (nonblocking && + (ssl_connect_2 == connssl->connecting_state || + ssl_connect_2_reading == connssl->connecting_state || + ssl_connect_2_writing == connssl->connecting_state))) + return retcode; + + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3==connssl->connecting_state) { + retcode = mbed_connect_step3(conn, sockindex); + if(retcode) + return retcode; + } + + if(ssl_connect_done==connssl->connecting_state) { + connssl->state = ssl_connection_complete; + conn->recv[sockindex] = mbed_recv; + conn->send[sockindex] = mbed_send; + *done = TRUE; + } + else + *done = FALSE; + + /* Reset our connect state machine */ + connssl->connecting_state = ssl_connect_1; + + return CURLE_OK; +} + +CURLcode +Curl_mbedtls_connect_nonblocking(struct connectdata *conn, + int sockindex, + bool *done) +{ + return mbed_connect_common(conn, sockindex, TRUE, done); +} + + +CURLcode +Curl_mbedtls_connect(struct connectdata *conn, + int sockindex) +{ + CURLcode retcode; + bool done = FALSE; + + retcode = mbed_connect_common(conn, sockindex, FALSE, &done); + if(retcode) + return retcode; + + DEBUGASSERT(done); + + return CURLE_OK; +} + +/* + * return 0 error initializing SSL + * return 1 SSL initialized successfully + */ +int Curl_mbedtls_init(void) +{ + return Curl_polarsslthreadlock_thread_setup(); +} + +void Curl_mbedtls_cleanup(void) +{ + (void)Curl_polarsslthreadlock_thread_cleanup(); +} + +int Curl_mbedtls_data_pending(const struct connectdata *conn, int sockindex) +{ + mbedtls_ssl_context *ssl = + (mbedtls_ssl_context *)&conn->ssl[sockindex].ssl; + return ssl->in_msglen != 0; +} + +#endif /* USE_MBEDTLS */ diff --git a/Utilities/cmcurl/lib/vtls/mbedtls.h b/Utilities/cmcurl/lib/vtls/mbedtls.h new file mode 100644 index 0000000..1021d54 --- /dev/null +++ b/Utilities/cmcurl/lib/vtls/mbedtls.h @@ -0,0 +1,80 @@ +#ifndef HEADER_CURL_MBEDTLS_H +#define HEADER_CURL_MBEDTLS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2010, Hoi-Ho Chan, <hoiho.chan@gmail.com> + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifdef USE_MBEDTLS + +#include <mbedtls/sha256.h> + +/* Called on first use mbedTLS, setup threading if supported */ +int Curl_mbedtls_init(void); +void Curl_mbedtls_cleanup(void); +int Curl_mbedtls_data_pending(const struct connectdata *conn, int sockindex); + +CURLcode Curl_mbedtls_connect(struct connectdata *conn, int sockindex); + +CURLcode Curl_mbedtls_connect_nonblocking(struct connectdata *conn, + int sockindex, + bool *done); + +/* tell mbedTLS to close down all open information regarding connections (and + thus session ID caching etc) */ +void Curl_mbedtls_close_all(struct Curl_easy *data); + + /* close a SSL connection */ +void Curl_mbedtls_close(struct connectdata *conn, int sockindex); + +void Curl_mbedtls_session_free(void *ptr); +size_t Curl_mbedtls_version(char *buffer, size_t size); +int Curl_mbedtls_shutdown(struct connectdata *conn, int sockindex); + +/* this backends supports CURLOPT_PINNEDPUBLICKEY */ +#define have_curlssl_pinnedpubkey 1 + +/* API setup for mbedTLS */ +#define curlssl_init() Curl_mbedtls_init() +#define curlssl_cleanup() Curl_mbedtls_cleanup() +#define curlssl_connect Curl_mbedtls_connect +#define curlssl_connect_nonblocking Curl_mbedtls_connect_nonblocking +#define curlssl_session_free(x) Curl_mbedtls_session_free(x) +#define curlssl_close_all Curl_mbedtls_close_all +#define curlssl_close Curl_mbedtls_close +#define curlssl_shutdown(x,y) 0 +#define curlssl_set_engine(x,y) (x=x, y=y, CURLE_NOT_BUILT_IN) +#define curlssl_set_engine_default(x) (x=x, CURLE_NOT_BUILT_IN) +#define curlssl_engines_list(x) (x=x, (struct curl_slist *)NULL) +#define curlssl_version Curl_mbedtls_version +#define curlssl_check_cxn(x) (x=x, -1) +#define curlssl_data_pending(x,y) Curl_mbedtls_data_pending(x, y) +#define CURL_SSL_BACKEND CURLSSLBACKEND_MBEDTLS +#define curlssl_sha256sum(a,b,c,d) mbedtls_sha256(a,b,c,0) + +/* This might cause libcurl to use a weeker random! + TODO: implement proper use of Polarssl's CTR-DRBG or HMAC-DRBG and use that +*/ +#define curlssl_random(x,y,z) (x=x, y=y, z=z, CURLE_NOT_BUILT_IN) + +#endif /* USE_MBEDTLS */ +#endif /* HEADER_CURL_MBEDTLS_H */ diff --git a/Utilities/cmcurl/lib/vtls/nss.c b/Utilities/cmcurl/lib/vtls/nss.c index 91727c7..ad33f25 100644 --- a/Utilities/cmcurl/lib/vtls/nss.c +++ b/Utilities/cmcurl/lib/vtls/nss.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -198,12 +198,12 @@ static const char* nss_error_to_name(PRErrorCode code) return "unknown error"; } -static void nss_print_error_message(struct SessionHandle *data, PRUint32 err) +static void nss_print_error_message(struct Curl_easy *data, PRUint32 err) { failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); } -static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model, +static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model, char *cipher_list) { unsigned int i; @@ -211,16 +211,22 @@ static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model, PRBool found; char *cipher; + /* use accessors to avoid dynamic linking issues after an update of NSS */ + const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers(); + const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers(); + if(!implemented_ciphers) + return SECFailure; + /* First disable all ciphers. This uses a different max value in case * NSS adds more ciphers later we don't want them available by * accident */ - for(i=0; i<SSL_NumImplementedCiphers; i++) { - SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], PR_FALSE); + for(i = 0; i < num_implemented_ciphers; i++) { + SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE); } /* Set every entry in our list to false */ - for(i=0; i<NUM_OF_CIPHERS; i++) { + for(i = 0; i < NUM_OF_CIPHERS; i++) { cipher_state[i] = PR_FALSE; } @@ -269,21 +275,21 @@ static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model, } /* - * Get the number of ciphers that are enabled. We use this to determine + * Return true if at least one cipher-suite is enabled. Used to determine * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers. */ -static int num_enabled_ciphers(void) +static bool any_cipher_enabled(void) { - PRInt32 policy = 0; - int count = 0; unsigned int i; for(i=0; i<NUM_OF_CIPHERS; i++) { + PRInt32 policy = 0; SSL_CipherPolicyGet(cipherlist[i].num, &policy); if(policy) - count++; + return TRUE; } - return count; + + return FALSE; } /* @@ -313,7 +319,7 @@ static int is_file(const char *filename) * should be later deallocated using free(). If the OOM failure occurs, we * return NULL, too. */ -static char* dup_nickname(struct SessionHandle *data, enum dupstring cert_kind) +static char* dup_nickname(struct Curl_easy *data, enum dupstring cert_kind) { const char *str = data->set.str[cert_kind]; const char *n; @@ -322,8 +328,8 @@ static char* dup_nickname(struct SessionHandle *data, enum dupstring cert_kind) /* no such file exists, use the string as nickname */ return strdup(str); - /* search the last slash; we require at least one slash in a file name */ - n = strrchr(str, '/'); + /* search the first slash; we require at least one slash in a file name */ + n = strchr(str, '/'); if(!n) { infof(data, "warning: certificate file name \"%s\" handled as nickname; " "please use \"./%s\" to force file name\n", str, str); @@ -591,7 +597,7 @@ static int display_error(struct connectdata *conn, PRInt32 err, static CURLcode cert_stuff(struct connectdata *conn, int sockindex, char *cert_file, char *key_file) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result; if(cert_file) { @@ -690,7 +696,7 @@ static void HandshakeCallback(PRFileDesc *sock, void *arg) unsigned int buflen; SSLNextProtoState state; - if(!conn->data->set.ssl_enable_npn && !conn->data->set.ssl_enable_alpn) { + if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) { return; } @@ -714,7 +720,7 @@ static void HandshakeCallback(PRFileDesc *sock, void *arg) #ifdef USE_NGHTTP2 if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) { - conn->negnpn = CURL_HTTP_VERSION_2_0; + conn->negnpn = CURL_HTTP_VERSION_2; } else #endif @@ -730,7 +736,7 @@ static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data, PRBool *canFalseStart) { struct connectdata *conn = client_data; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; SSLChannelInfo channelInfo; SSLCipherSuiteInfo cipherInfo; @@ -785,7 +791,7 @@ end: } #endif -static void display_cert_info(struct SessionHandle *data, +static void display_cert_info(struct Curl_easy *data, CERTCertificate *cert) { char *subject, *issuer, *common_name; @@ -886,7 +892,7 @@ static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock) static SECStatus BadCertHandler(void *arg, PRFileDesc *sock) { struct connectdata *conn = (struct connectdata *)arg; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; PRErrorCode err = PR_GetError(); CERTCertificate *cert; @@ -922,12 +928,6 @@ static SECStatus check_issuer_cert(PRFileDesc *sock, SECStatus res=SECSuccess; void *proto_win = NULL; - /* - PRArenaPool *tmpArena = NULL; - CERTAuthKeyID *authorityKeyID = NULL; - SECITEM *caname = NULL; - */ - cert = SSL_PeerCertificate(sock); cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner); @@ -950,7 +950,7 @@ static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl, const char *pinnedpubkey) { CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; - struct SessionHandle *data = connssl->data; + struct Curl_easy *data = connssl->data; CERTCertificate *cert; if(!pinnedpubkey) @@ -967,8 +967,7 @@ static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl, SECItem *cert_der = PK11_DEREncodePublicKey(pubkey); if(cert_der) { /* compare the public key with the pinned public key */ - result = Curl_pin_peer_pubkey(pinnedpubkey, - cert_der->data, + result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data, cert_der->len); SECITEM_FreeItem(cert_der, PR_TRUE); } @@ -1003,7 +1002,7 @@ static SECStatus SelectClientCert(void *arg, PRFileDesc *sock, struct SECKEYPrivateKeyStr **pRetKey) { struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg; - struct SessionHandle *data = connssl->data; + struct Curl_easy *data = connssl->data; const char *nickname = connssl->client_nickname; if(connssl->obj_clicert) { @@ -1135,7 +1134,7 @@ static PRStatus nspr_io_close(PRFileDesc *fd) } /* data might be NULL */ -static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir) +static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir) { NSSInitParameters initparams; @@ -1173,7 +1172,7 @@ static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir) } /* data might be NULL */ -static CURLcode nss_init(struct SessionHandle *data) +static CURLcode nss_init(struct Curl_easy *data) { char *cert_dir; struct_stat st; @@ -1223,7 +1222,7 @@ static CURLcode nss_init(struct SessionHandle *data) if(result) return result; - if(num_enabled_ciphers() == 0) + if(!any_cipher_enabled()) NSS_SetDomesticPolicy(); initialized = 1; @@ -1252,7 +1251,7 @@ int Curl_nss_init(void) } /* data might be NULL */ -CURLcode Curl_nss_force_init(struct SessionHandle *data) +CURLcode Curl_nss_force_init(struct Curl_easy *data) { CURLcode result; if(!nss_initlock) { @@ -1398,7 +1397,7 @@ static Curl_send nss_send; static CURLcode nss_load_ca_certificates(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; const char *cafile = data->set.ssl.CAfile; const char *capath = data->set.ssl.CApath; @@ -1448,7 +1447,7 @@ static CURLcode nss_load_ca_certificates(struct connectdata *conn, } static CURLcode nss_init_sslver(SSLVersionRange *sslver, - struct SessionHandle *data) + struct Curl_easy *data) { switch(data->set.ssl.version) { default: @@ -1501,7 +1500,7 @@ static CURLcode nss_init_sslver(SSLVersionRange *sslver, } static CURLcode nss_fail_connect(struct ssl_connect_data *connssl, - struct SessionHandle *data, + struct Curl_easy *data, CURLcode curlerr) { PRErrorCode err = 0; @@ -1528,7 +1527,7 @@ static CURLcode nss_fail_connect(struct ssl_connect_data *connssl, /* Switch the SSL socket into non-blocking mode. */ static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl, - struct SessionHandle *data) + struct Curl_easy *data) { static PRSocketOptionData sock_opt; sock_opt.option = PR_SockOpt_Nonblocking; @@ -1547,7 +1546,7 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex) PRFileDesc *nspr_io_stub = NULL; PRBool ssl_no_cache; PRBool ssl_cbc_random_iv; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CURLcode result; @@ -1745,14 +1744,14 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex) #endif #ifdef SSL_ENABLE_NPN - if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, data->set.ssl_enable_npn - ? PR_TRUE : PR_FALSE) != SECSuccess) + if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn + ? PR_TRUE : PR_FALSE) != SECSuccess) goto error; #endif #ifdef SSL_ENABLE_ALPN - if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, data->set.ssl_enable_alpn - ? PR_TRUE : PR_FALSE) != SECSuccess) + if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn + ? PR_TRUE : PR_FALSE) != SECSuccess) goto error; #endif @@ -1769,12 +1768,12 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex) #endif #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN) - if(data->set.ssl_enable_npn || data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) { int cur = 0; unsigned char protocols[128]; #ifdef USE_NGHTTP2 - if(data->set.httpversion == CURL_HTTP_VERSION_2_0) { + if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN; memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN); @@ -1792,9 +1791,17 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex) /* Force handshake on next I/O */ - SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE); + if(SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE) + != SECSuccess) + goto error; - SSL_SetURL(connssl->handle, conn->host.name); + /* propagate hostname to the TLS layer */ + if(SSL_SetURL(connssl->handle, conn->host.name) != SECSuccess) + goto error; + + /* prevent NSS from re-using the session for a different hostname */ + if(SSL_SetSockPeerID(connssl->handle, conn->host.name) != SECSuccess) + goto error; return CURLE_OK; @@ -1808,7 +1815,7 @@ error: static CURLcode nss_do_connect(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; CURLcode result = CURLE_SSL_CONNECT_ERROR; PRUint32 timeout; @@ -1871,7 +1878,7 @@ static CURLcode nss_connect_common(struct connectdata *conn, int sockindex, bool *done) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; const bool blocking = (done == NULL); CURLcode result; @@ -2008,14 +2015,14 @@ size_t Curl_nss_version(char *buffer, size_t size) } /* data might be NULL */ -int Curl_nss_seed(struct SessionHandle *data) +int Curl_nss_seed(struct Curl_easy *data) { /* make sure that NSS is initialized */ return !!Curl_nss_force_init(data); } /* data might be NULL */ -int Curl_nss_random(struct SessionHandle *data, +int Curl_nss_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { diff --git a/Utilities/cmcurl/lib/vtls/nssg.h b/Utilities/cmcurl/lib/vtls/nssg.h index 5fd7275..ac67e6a 100644 --- a/Utilities/cmcurl/lib/vtls/nssg.h +++ b/Utilities/cmcurl/lib/vtls/nssg.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -42,12 +42,12 @@ void Curl_nss_cleanup(void); size_t Curl_nss_version(char *buffer, size_t size); int Curl_nss_check_cxn(struct connectdata *cxn); -int Curl_nss_seed(struct SessionHandle *data); +int Curl_nss_seed(struct Curl_easy *data); /* initialize NSS library if not already */ -CURLcode Curl_nss_force_init(struct SessionHandle *data); +CURLcode Curl_nss_force_init(struct Curl_easy *data); -int Curl_nss_random(struct SessionHandle *data, +int Curl_nss_random(struct Curl_easy *data, unsigned char *entropy, size_t length); @@ -74,6 +74,9 @@ bool Curl_nss_false_start(void); /* this backend supports CURLOPT_CERTINFO */ #define have_curlssl_certinfo 1 +/* this backends supports CURLOPT_PINNEDPUBLICKEY */ +#define have_curlssl_pinnedpubkey 1 + /* API setup for NSS */ #define curlssl_init Curl_nss_init #define curlssl_cleanup Curl_nss_cleanup diff --git a/Utilities/cmcurl/lib/vtls/openssl.c b/Utilities/cmcurl/lib/vtls/openssl.c index 90e4c2b..3027ca3 100644 --- a/Utilities/cmcurl/lib/vtls/openssl.c +++ b/Utilities/cmcurl/lib/vtls/openssl.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -68,7 +68,7 @@ #include <openssl/pkcs12.h> #endif -#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_IS_BORINGSSL) +#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP) #include <openssl/ocsp.h> #endif @@ -83,23 +83,8 @@ #error "OPENSSL_VERSION_NUMBER not defined" #endif -#if OPENSSL_VERSION_NUMBER >= 0x00907001L && !defined(OPENSSL_IS_BORINGSSL) -/* ENGINE_load_private_key() takes four arguments */ -#define HAVE_ENGINE_LOAD_FOUR_ARGS +#if defined(HAVE_OPENSSL_ENGINE_H) #include <openssl/ui.h> -#else -/* ENGINE_load_private_key() takes three arguments */ -#undef HAVE_ENGINE_LOAD_FOUR_ARGS -#endif - -#if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && \ - defined(HAVE_OPENSSL_PKCS12_H) && \ - !defined(OPENSSL_IS_BORINGSSL) -/* OpenSSL has PKCS 12 support, BoringSSL does not */ -#define HAVE_PKCS12_SUPPORT -#else -/* OpenSSL does not have PKCS12 support */ -#undef HAVE_PKCS12_SUPPORT #endif #if OPENSSL_VERSION_NUMBER >= 0x00909000L @@ -108,18 +93,13 @@ #define SSL_METHOD_QUAL #endif -#if OPENSSL_VERSION_NUMBER >= 0x00907000L -/* 0.9.6 didn't have X509_STORE_set_flags() */ -#define HAVE_X509_STORE_SET_FLAGS 1 -#else -#define X509_STORE_set_flags(x,y) Curl_nop_stmt -#endif - -#ifdef OPENSSL_IS_BORINGSSL -/* BoringSSL has no ERR_remove_state() */ -#define ERR_remove_state(x) -#elif (OPENSSL_VERSION_NUMBER >= 0x10000000L) +#if (OPENSSL_VERSION_NUMBER >= 0x10000000L) #define HAVE_ERR_REMOVE_THREAD_STATE 1 +#if (OPENSSL_VERSION_NUMBER >= 0x10100004L) && \ + !defined(LIBRESSL_VERSION_NUMBER) +/* OpenSSL 1.1.0 deprecates the function */ +#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1 +#endif #endif #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \ @@ -128,19 +108,39 @@ #define OPENSSL_NO_SSL2 #endif -#if defined(OPENSSL_IS_BORINGSSL) -#define NO_RAND_SEED 1 -/* In BoringSSL OpenSSL_add_all_algorithms does nothing */ -#define OpenSSL_add_all_algorithms() -/* BoringSSL does not have CONF_modules_load_file */ -#define CONF_modules_load_file(a,b,c) +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \ + !defined(LIBRESSL_VERSION_NUMBER) +#define SSLeay_add_ssl_algorithms() SSL_library_init() +#define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER +#define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */ +#define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */ +#define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */ +#endif + +#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \ + !defined(LIBRESSL_VERSION_NUMBER) +#define HAVE_X509_GET0_SIGNATURE 1 #endif -#if (OPENSSL_VERSION_NUMBER < 0x0090808fL) || defined(OPENSSL_IS_BORINGSSL) -/* not present in BoringSSL or older OpenSSL */ +#if OPENSSL_VERSION_NUMBER >= 0x10002003L && \ + OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \ + !defined(OPENSSL_NO_COMP) +#define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1 +#endif + +#if (OPENSSL_VERSION_NUMBER < 0x0090808fL) +/* not present in older OpenSSL */ #define OPENSSL_load_builtin_modules(x) #endif +#if defined(LIBRESSL_VERSION_NUMBER) +#define OSSL_PACKAGE "LibreSSL" +#elif defined(OPENSSL_IS_BORINGSSL) +#define OSSL_PACKAGE "BoringSSL" +#else +#define OSSL_PACKAGE "OpenSSL" +#endif + /* * Number of bytes to read from the random number seed file. This must be * a finite value (because some entropy "files" like /dev/urandom have @@ -171,7 +171,6 @@ static int passwd_callback(char *buf, int num, int encrypting, * pass in an argument that is never used. */ -#ifndef NO_RAND_SEED #ifdef HAVE_RAND_STATUS #define seed_enough(x) rand_enough() static bool rand_enough(void) @@ -187,7 +186,7 @@ static bool rand_enough(int nread) } #endif -static int ossl_seed(struct SessionHandle *data) +static int ossl_seed(struct Curl_easy *data) { char *buf = data->state.buffer; /* point to the big buffer */ int nread=0; @@ -256,7 +255,7 @@ static int ossl_seed(struct SessionHandle *data) return nread; } -static void Curl_ossl_seed(struct SessionHandle *data) +static void Curl_ossl_seed(struct Curl_easy *data) { /* we have the "SSL is seeded" boolean static to prevent multiple time-consuming seedings in vain */ @@ -268,11 +267,6 @@ static void Curl_ossl_seed(struct SessionHandle *data) ssl_seeded = TRUE; } } -#else -/* BoringSSL needs no seeding */ -#define Curl_ossl_seed(x) -#endif - #ifndef SSL_FILETYPE_ENGINE #define SSL_FILETYPE_ENGINE 42 @@ -295,7 +289,7 @@ static int do_file_type(const char *type) return -1; } -#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_LOAD_FOUR_ARGS) +#if defined(HAVE_OPENSSL_ENGINE_H) /* * Supply default password to the engine user interface conversation. * The password is passed by OpenSSL engine from ENGINE_load_private_key() @@ -345,7 +339,7 @@ int cert_stuff(struct connectdata *conn, char *key_file, const char *key_type) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int file_type = do_file_type(cert_type); @@ -369,7 +363,8 @@ int cert_stuff(struct connectdata *conn, if(SSL_CTX_use_certificate_chain_file(ctx, cert_file) != 1) { failf(data, - "could not load PEM client certificate, OpenSSL error %s, " + "could not load PEM client certificate, " OSSL_PACKAGE + " error %s, " "(no key found, wrong pass phrase, or wrong file format?)", ERR_error_string(ERR_get_error(), NULL) ); return 0; @@ -384,7 +379,8 @@ int cert_stuff(struct connectdata *conn, cert_file, file_type) != 1) { failf(data, - "could not load ASN1 client certificate, OpenSSL error %s, " + "could not load ASN1 client certificate, " OSSL_PACKAGE + " error %s, " "(no key found, wrong pass phrase, or wrong file format?)", ERR_error_string(ERR_get_error(), NULL) ); return 0; @@ -445,12 +441,11 @@ int cert_stuff(struct connectdata *conn, case SSL_FILETYPE_PKCS12: { -#ifdef HAVE_PKCS12_SUPPORT +#ifdef HAVE_OPENSSL_PKCS12_H FILE *f; PKCS12 *p12; EVP_PKEY *pri; STACK_OF(X509) *ca = NULL; - int i; f = fopen(cert_file, "rb"); if(!f) { @@ -470,7 +465,8 @@ int cert_stuff(struct connectdata *conn, if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509, &ca)) { failf(data, - "could not parse PKCS12 file, check password, OpenSSL error %s", + "could not parse PKCS12 file, check password, " OSSL_PACKAGE + " error %s", ERR_error_string(ERR_get_error(), NULL) ); PKCS12_free(p12); return 0; @@ -480,7 +476,8 @@ int cert_stuff(struct connectdata *conn, if(SSL_CTX_use_certificate(ctx, x509) != 1) { failf(data, - "could not load PKCS12 client certificate, OpenSSL error %s", + "could not load PKCS12 client certificate, " OSSL_PACKAGE + " error %s", ERR_error_string(ERR_get_error(), NULL) ); goto fail; } @@ -497,8 +494,8 @@ int cert_stuff(struct connectdata *conn, goto fail; } /* Set Certificate Verification chain */ - if(ca && sk_X509_num(ca)) { - for(i = 0; i < sk_X509_num(ca); i++) { + if(ca) { + while(sk_X509_num(ca)) { /* * Note that sk_X509_pop() is used below to make sure the cert is * removed from the stack properly before getting passed to @@ -508,6 +505,7 @@ int cert_stuff(struct connectdata *conn, */ X509 *x = sk_X509_pop(ca); if(!SSL_CTX_add_extra_chain_cert(ctx, x)) { + X509_free(x); failf(data, "cannot add certificate to certificate chain"); goto fail; } @@ -561,28 +559,23 @@ int cert_stuff(struct connectdata *conn, { /* XXXX still needs some work */ EVP_PKEY *priv_key = NULL; if(data->state.engine) { -#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS UI_METHOD *ui_method = UI_create_method((char *)"cURL user interface"); if(!ui_method) { - failf(data, "unable do create OpenSSL user-interface method"); + failf(data, "unable do create " OSSL_PACKAGE + " user-interface method"); return 0; } UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); UI_method_set_reader(ui_method, ssl_ui_reader); UI_method_set_writer(ui_method, ssl_ui_writer); -#endif /* the typecast below was added to please mingw32 */ priv_key = (EVP_PKEY *) ENGINE_load_private_key(data->state.engine, key_file, -#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS ui_method, -#endif data->set.str[STRING_KEY_PASSWD]); -#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS UI_destroy_method(ui_method); -#endif if(!priv_key) { failf(data, "failed to load private key from crypto engine"); return 0; @@ -679,7 +672,7 @@ static int x509_name_oneline(X509_NAME *a, char *buf, size_t size) /* Return error string for last OpenSSL error */ -static char *SSL_strerror(unsigned long error, char *buf, size_t size) +static char *ossl_strerror(unsigned long error, char *buf, size_t size) { /* OpenSSL 0.9.6 and later has a function named ERR_error_string_n() that takes the size of the buffer as a @@ -702,16 +695,6 @@ int Curl_ossl_init(void) ENGINE_load_builtin_engines(); #endif - /* Lets get nice error messages */ - SSL_load_error_strings(); - - /* Init the global ciphers and digests */ - if(!SSLeay_add_ssl_algorithms()) - return 0; - - OpenSSL_add_all_algorithms(); - - /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately that function makes an exit() call on wrongly formatted config files which makes it hard to use in some situations. OPENSSL_config() itself @@ -728,6 +711,15 @@ int Curl_ossl_init(void) CONF_MFLAGS_DEFAULT_SECTION| CONF_MFLAGS_IGNORE_MISSING_FILE); + /* Lets get nice error messages */ + SSL_load_error_strings(); + + /* Init the global ciphers and digests */ + if(!SSLeay_add_ssl_algorithms()) + return 0; + + OpenSSL_add_all_algorithms(); + return 1; } @@ -751,15 +743,24 @@ void Curl_ossl_cleanup(void) ERR_free_strings(); /* Free thread local error state, destroying hash upon zero refcount */ -#ifdef HAVE_ERR_REMOVE_THREAD_STATE +#ifdef HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED + +#elif defined(HAVE_ERR_REMOVE_THREAD_STATE) ERR_remove_thread_state(NULL); #else ERR_remove_state(0); #endif + + /* Free all memory allocated by all configuration modules */ + CONF_modules_free(); + +#ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS + SSL_COMP_free_compression_methods(); +#endif } /* - * This function uses SSL_peek to determine connection status. + * This function is used to determine connection status. * * Return codes: * 1 means the connection is still in place @@ -768,22 +769,51 @@ void Curl_ossl_cleanup(void) */ int Curl_ossl_check_cxn(struct connectdata *conn) { - int rc; + /* SSL_peek takes data out of the raw recv buffer without peeking so we use + recv MSG_PEEK instead. Bug #795 */ +#ifdef MSG_PEEK char buf; - - rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1); - if(rc > 0) - return 1; /* connection still in place */ - - if(rc == 0) + ssize_t nread; + nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf, + (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK); + if(nread == 0) return 0; /* connection has been closed */ - + else if(nread == 1) + return 1; /* connection still in place */ + else if(nread == -1) { + int err = SOCKERRNO; + if(err == EINPROGRESS || +#if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK) + err == EAGAIN || +#endif + err == EWOULDBLOCK) + return 1; /* connection still in place */ + if(err == ECONNRESET || +#ifdef ECONNABORTED + err == ECONNABORTED || +#endif +#ifdef ENETDOWN + err == ENETDOWN || +#endif +#ifdef ENETRESET + err == ENETRESET || +#endif +#ifdef ESHUTDOWN + err == ESHUTDOWN || +#endif +#ifdef ETIMEDOUT + err == ETIMEDOUT || +#endif + err == ENOTCONN) + return 0; /* connection has been closed */ + } +#endif return -1; /* connection status unknown */ } /* Selects an OpenSSL crypto engine */ -CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine) +CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine) { #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H) ENGINE *e; @@ -814,7 +844,7 @@ CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine) ENGINE_free(e); failf(data, "Failed to initialise SSL Engine '%s':\n%s", - engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf))); + engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf))); return CURLE_SSL_ENGINE_INITFAILED; } data->state.engine = e; @@ -828,7 +858,7 @@ CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine) /* Sets engine as default for all SSL operations */ -CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data) +CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data) { #ifdef HAVE_OPENSSL_ENGINE_H if(data->state.engine) { @@ -850,7 +880,7 @@ CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data) /* Return list of OpenSSL crypto engine names. */ -struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data) +struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data) { struct curl_slist *list = NULL; #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H) @@ -899,9 +929,9 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex) { int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; - char buf[120]; /* We will use this for the OpenSSL error buffer, so it has - to be at least 120 bytes long. */ + struct Curl_easy *data = conn->data; + char buf[256]; /* We will use this for the OpenSSL error buffer, so it has + to be at least 256 bytes long. */ unsigned long sslerror; ssize_t nread; int buffsize; @@ -949,8 +979,8 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex) default: /* openssl/ssl.h says "look at error stack/return value/errno" */ sslerror = ERR_get_error(); - failf(conn->data, "SSL read: %s, errno %d", - ERR_error_string(sslerror, buf), + failf(conn->data, OSSL_PACKAGE " SSL read: %s, errno %d", + ossl_strerror(sslerror, buf, sizeof(buf)), SOCKERRNO); done = 1; break; @@ -1002,7 +1032,7 @@ void Curl_ossl_session_free(void *ptr) * This function is called when the 'data' struct is going away. Close * down everything and free all resources! */ -void Curl_ossl_close_all(struct SessionHandle *data) +void Curl_ossl_close_all(struct Curl_easy *data) { #ifdef HAVE_OPENSSL_ENGINE_H if(data->state.engine) { @@ -1015,49 +1045,6 @@ void Curl_ossl_close_all(struct SessionHandle *data) #endif } -static int asn1_output(const ASN1_UTCTIME *tm, - char *buf, - size_t sizeofbuf) -{ - const char *asn1_string; - int gmt=FALSE; - int i; - int year=0, month=0, day=0, hour=0, minute=0, second=0; - - i=tm->length; - asn1_string=(const char *)tm->data; - - if(i < 10) - return 1; - if(asn1_string[i-1] == 'Z') - gmt=TRUE; - for(i=0; i<10; i++) - if((asn1_string[i] > '9') || (asn1_string[i] < '0')) - return 2; - - year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0'); - if(year < 50) - year+=100; - - month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0'); - if((month > 12) || (month < 1)) - return 3; - - day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0'); - hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0'); - minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0'); - - if((asn1_string[10] >= '0') && (asn1_string[10] <= '9') && - (asn1_string[11] >= '0') && (asn1_string[11] <= '9')) - second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0'); - - snprintf(buf, sizeofbuf, - "%04d-%02d-%02d %02d:%02d:%02d %s", - year+1900, month, day, hour, minute, second, (gmt?"GMT":"")); - - return 0; -} - /* ====================================================== */ @@ -1084,11 +1071,10 @@ static int asn1_output(const ASN1_UTCTIME *tm, */ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) { - int matched = -1; /* -1 is no alternative match yet, 1 means match and 0 - means mismatch */ + bool matched = FALSE; int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */ size_t addrlen = 0; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; STACK_OF(GENERAL_NAME) *altnames; #ifdef ENABLE_IPV6 struct in6_addr addr; @@ -1096,6 +1082,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) struct in_addr addr; #endif CURLcode result = CURLE_OK; + bool dNSName = FALSE; /* if a dNSName field exists in the cert */ #ifdef ENABLE_IPV6 if(conn->bits.ipv6_ip && @@ -1116,16 +1103,23 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) if(altnames) { int numalts; int i; + bool dnsmatched = FALSE; + bool ipmatched = FALSE; /* get amount of alternatives, RFC2459 claims there MUST be at least one, but we don't depend on it... */ numalts = sk_GENERAL_NAME_num(altnames); - /* loop through all alternatives while none has matched */ - for(i=0; (i<numalts) && (matched != 1); i++) { + /* loop through all alternatives - until a dnsmatch */ + for(i=0; (i < numalts) && !dnsmatched; i++) { /* get a handle to alternative name number i */ const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i); + /* If a subjectAltName extension of type dNSName is present, that MUST + be used as the identity. / RFC2818 section 3.1 */ + if(check->type == GEN_DNS) + dNSName = TRUE; + /* only check alternatives of the same type the target is */ if(check->type == target) { /* get data and length */ @@ -1147,33 +1141,42 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) if((altlen == strlen(altptr)) && /* if this isn't true, there was an embedded zero in the name string and we cannot match it. */ - Curl_cert_hostcheck(altptr, conn->host.name)) - matched = 1; - else - matched = 0; + Curl_cert_hostcheck(altptr, conn->host.name)) { + dnsmatched = TRUE; + infof(data, + " subjectAltName: host \"%s\" matched cert's \"%s\"\n", + conn->host.dispname, altptr); + } break; case GEN_IPADD: /* IP address comparison */ /* compare alternative IP address if the data chunk is the same size our server IP address is */ - if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) - matched = 1; - else - matched = 0; + if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) { + ipmatched = TRUE; + infof(data, + " subjectAltName: host \"%s\" matched cert's IP address!\n", + conn->host.dispname); + } break; } } } GENERAL_NAMES_free(altnames); + + if(dnsmatched || (!dNSName && ipmatched)) { + /* count as a match if the dnsname matched or if there was no dnsname + fields at all AND there was an IP field match */ + matched = TRUE; + } } - if(matched == 1) - /* an alternative name matched the server hostname */ - infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname); - else if(matched == 0) { - /* an alternative name field existed, but didn't match and then - we MUST fail */ - infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname); + if(matched) + /* an alternative name matched */ + ; + else if(dNSName) { + /* an dNSName field existed, but didn't match and then we MUST fail */ + infof(data, " subjectAltName does not match %s\n", conn->host.dispname); failf(data, "SSL: no alternative certificate subject name matches " "target host name '%s'", conn->host.dispname); result = CURLE_PEER_FAILED_VERIFICATION; @@ -1183,7 +1186,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) distinguished one to get the most significant one. */ int j, i=-1; -/* The following is done because of a bug in 0.9.6b */ + /* The following is done because of a bug in 0.9.6b */ unsigned char *nulstr = (unsigned char *)""; unsigned char *peer_CN = nulstr; @@ -1255,7 +1258,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) result = CURLE_PEER_FAILED_VERIFICATION; } else { - infof(data, "\t common name: %s (matched)\n", peer_CN); + infof(data, " common name: %s (matched)\n", peer_CN); } if(peer_CN) OPENSSL_free(peer_CN); @@ -1265,14 +1268,14 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) } #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ - !defined(OPENSSL_IS_BORINGSSL) + !defined(OPENSSL_NO_OCSP) static CURLcode verifystatus(struct connectdata *conn, struct ssl_connect_data *connssl) { int i, ocsp_status; const unsigned char *p; CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; OCSP_RESPONSE *rsp = NULL; OCSP_BASICRESP *br = NULL; @@ -1351,7 +1354,8 @@ static CURLcode verifystatus(struct connectdata *conn, ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; - if(!(single = OCSP_resp_get0(br, i))) + single = OCSP_resp_get0(br, i); + if(!single) continue; cert_status = OCSP_single_get0_status(single, &crl_reason, &rev, @@ -1487,7 +1491,7 @@ static void ssl_tls_trace(int direction, int ssl_ver, int content_type, const void *buf, size_t len, SSL *ssl, void *userp) { - struct SessionHandle *data; + struct Curl_easy *data; const char *msg_name, *tls_rt_name; char ssl_buf[1024]; char unknown[32]; @@ -1620,12 +1624,12 @@ select_next_proto_cb(SSL *ssl, (void)ssl; #ifdef USE_NGHTTP2 - if(conn->data->set.httpversion == CURL_HTTP_VERSION_2_0 && + if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 && !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN)) { infof(conn->data, "NPN, negotiated HTTP2 (%s)\n", NGHTTP2_PROTO_VERSION_ID); - conn->negnpn = CURL_HTTP_VERSION_2_0; + conn->negnpn = CURL_HTTP_VERSION_2; return SSL_TLSEXT_ERR_OK; } #endif @@ -1673,9 +1677,8 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; char *ciphers; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; SSL_METHOD_QUAL SSL_METHOD *req_method = NULL; - void *ssl_sessionid = NULL; X509_LOOKUP *lookup = NULL; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; @@ -1707,7 +1710,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) case CURL_SSLVERSION_TLSv1_2: /* it will be handled later with the context options */ #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ - !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) + !defined(LIBRESSL_VERSION_NUMBER) req_method = TLS_client_method(); #else req_method = SSLv23_client_method(); @@ -1716,7 +1719,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) break; case CURL_SSLVERSION_SSLv2: #ifdef OPENSSL_NO_SSL2 - failf(data, "OpenSSL was built without SSLv2 support"); + failf(data, OSSL_PACKAGE " was built without SSLv2 support"); return CURLE_NOT_BUILT_IN; #else #ifdef USE_TLS_SRP @@ -1729,7 +1732,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) #endif case CURL_SSLVERSION_SSLv3: #ifdef OPENSSL_NO_SSL3_METHOD - failf(data, "OpenSSL was built without SSLv3 support"); + failf(data, OSSL_PACKAGE " was built without SSLv3 support"); return CURLE_NOT_BUILT_IN; #else #ifdef USE_TLS_SRP @@ -1887,17 +1890,17 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) SSL_CTX_set_options(connssl->ctx, ctx_options); #ifdef HAS_NPN - if(data->set.ssl_enable_npn) + if(conn->bits.tls_enable_npn) SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn); #endif #ifdef HAS_ALPN - if(data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_alpn) { int cur = 0; unsigned char protocols[128]; #ifdef USE_NGHTTP2 - if(data->set.httpversion == CURL_HTTP_VERSION_2_0) { + if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN; memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID, @@ -1997,6 +2000,13 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]: "none"); } +#ifdef CURL_CA_FALLBACK + else if(data->set.ssl.verifypeer) { + /* verfying the peer without any CA certificates won't + work so use openssl's built in default as fallback */ + SSL_CTX_set_default_verify_paths(connssl->ctx); + } +#endif if(data->set.str[STRING_SSL_CRLFILE]) { /* tell SSL where to find CRL file that is used to check certificate @@ -2063,7 +2073,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) } #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ - !defined(OPENSSL_IS_BORINGSSL) + !defined(OPENSSL_NO_OCSP) if(data->set.ssl.verifystatus) SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp); #endif @@ -2084,15 +2094,22 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) #endif /* Check if there's a cached ID we can/should use here! */ - if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) { - /* we got a session id, use it! */ - if(!SSL_set_session(connssl->handle, ssl_sessionid)) { - failf(data, "SSL: SSL_set_session failed: %s", - ERR_error_string(ERR_get_error(), NULL)); - return CURLE_SSL_CONNECT_ERROR; + if(conn->ssl_config.sessionid) { + void *ssl_sessionid = NULL; + + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) { + /* we got a session id, use it! */ + if(!SSL_set_session(connssl->handle, ssl_sessionid)) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "SSL: SSL_set_session failed: %s", + ERR_error_string(ERR_get_error(), NULL)); + return CURLE_SSL_CONNECT_ERROR; + } + /* Informational message */ + infof (data, "SSL re-using session ID\n"); } - /* Informational message */ - infof (data, "SSL re-using session ID\n"); + Curl_ssl_sessionid_unlock(conn); } /* pass the raw socket into the SSL layers */ @@ -2109,7 +2126,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int err; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; DEBUGASSERT(ssl_connect_2 == connssl->connecting_state @@ -2141,27 +2158,22 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) least 256 bytes long. */ CURLcode result; long lerr; + int lib; + int reason; - connssl->connecting_state = ssl_connect_2; /* the connection failed, - we're not waiting for - anything else. */ - - errdetail = ERR_get_error(); /* Gets the earliest error code from the - thread's error queue and removes the - entry. */ - - switch(errdetail) { - case 0x1407E086: - /* 1407E086: - SSL routines: - SSL2_SET_CERTIFICATE: - certificate verify failed */ - /* fall-through */ - case 0x14090086: - /* 14090086: - SSL routines: - SSL3_GET_SERVER_CERTIFICATE: - certificate verify failed */ + /* the connection failed, we're not waiting for anything else. */ + connssl->connecting_state = ssl_connect_2; + + /* Get the earliest error code from the thread's error queue and removes + the entry. */ + errdetail = ERR_get_error(); + + /* Extract which lib and reason */ + lib = ERR_GET_LIB(errdetail); + reason = ERR_GET_REASON(errdetail); + + if((lib == ERR_LIB_SSL) && + (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) { result = CURLE_SSL_CACERT; lerr = SSL_get_verify_result(connssl->handle); @@ -2173,13 +2185,11 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) else /* strcpy() is fine here as long as the string fits within error_buffer */ - strcpy(error_buffer, - "SSL certificate problem, check your CA cert"); - break; - default: + strcpy(error_buffer, "SSL certificate verification failed"); + } + else { result = CURLE_SSL_CONNECT_ERROR; - SSL_strerror(errdetail, error_buffer, sizeof(error_buffer)); - break; + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)); } /* detail is already set to the SSL error above */ @@ -2213,7 +2223,7 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) /* Sets data and len to negotiated protocol, len is 0 if no protocol was * negotiated */ - if(data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_alpn) { const unsigned char* neg_protocol; unsigned int len; SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len); @@ -2223,7 +2233,7 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) #ifdef USE_NGHTTP2 if(len == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) { - conn->negnpn = CURL_HTTP_VERSION_2_0; + conn->negnpn = CURL_HTTP_VERSION_2; } else #endif @@ -2256,58 +2266,59 @@ static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len) return 0; } -static void pubkey_show(struct SessionHandle *data, +#define push_certinfo(_label, _num) \ +do { \ + long info_len = BIO_get_mem_data(mem, &ptr); \ + Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \ + if(1!=BIO_reset(mem)) \ + break; \ +} WHILE_FALSE + +static void pubkey_show(struct Curl_easy *data, + BIO *mem, int num, const char *type, const char *name, - unsigned char *raw, - int len) +#ifdef HAVE_OPAQUE_RSA_DSA_DH + const +#endif + BIGNUM *bn) { - size_t left; - int i; + char *ptr; char namebuf[32]; - char *buffer; - - left = len*3 + 1; - buffer = malloc(left); - if(buffer) { - char *ptr=buffer; - snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); - for(i=0; i< len; i++) { - snprintf(ptr, left, "%02x:", raw[i]); - ptr += 3; - left -= 3; - } - infof(data, " %s: %s\n", namebuf, buffer); - Curl_ssl_push_certinfo(data, num, namebuf, buffer); - free(buffer); - } + + snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); + + if(bn) + BN_print(mem, bn); + push_certinfo(namebuf, num); } +#ifdef HAVE_OPAQUE_RSA_DSA_DH +#define print_pubkey_BN(_type, _name, _num) \ + pubkey_show(data, mem, _num, #_type, #_name, _name) + +#else #define print_pubkey_BN(_type, _name, _num) \ do { \ - if(pubkey->pkey._type->_name) { \ - int len = BN_num_bytes(pubkey->pkey._type->_name); \ - if(len < CERTBUFFERSIZE) { \ - BN_bn2bin(pubkey->pkey._type->_name, (unsigned char*)bufp); \ - bufp[len] = 0; \ - pubkey_show(data, _num, #_type, #_name, (unsigned char*)bufp, len); \ - } \ + if(_type->_name) { \ + pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \ } \ } WHILE_FALSE +#endif -static int X509V3_ext(struct SessionHandle *data, +static int X509V3_ext(struct Curl_easy *data, int certnum, STACK_OF(X509_EXTENSION) *exts) { int i; size_t j; - if(sk_X509_EXTENSION_num(exts) <= 0) + if((int)sk_X509_EXTENSION_num(exts) <= 0) /* no extensions, bail out */ return 1; - for(i=0; i<sk_X509_EXTENSION_num(exts); i++) { + for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) { ASN1_OBJECT *obj; X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); BUF_MEM *biomem; @@ -2323,18 +2334,12 @@ static int X509V3_ext(struct SessionHandle *data, asn1_object_dump(obj, namebuf, sizeof(namebuf)); - infof(data, "%s: %s\n", namebuf, - X509_EXTENSION_get_critical(ext)?"(critical)":""); - if(!X509V3_EXT_print(bio_out, ext, 0, 0)) ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext)); BIO_get_mem_ptr(bio_out, &biomem); - /* biomem->length bytes at biomem->data, this little loop here is only - done for the infof() call, we send the "raw" data to the certinfo - function */ - for(j=0; j<(size_t)biomem->length; j++) { + for(j = 0; j < (size_t)biomem->length; j++) { const char *sep=""; if(biomem->data[j] == '\n') { sep=", "; @@ -2346,7 +2351,6 @@ static int X509V3_ext(struct SessionHandle *data, ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep, biomem->data[j]); } - infof(data, " %s\n", buf); Curl_ssl_push_certinfo(data, certnum, namebuf, buf); @@ -2356,46 +2360,6 @@ static int X509V3_ext(struct SessionHandle *data, return 0; /* all is fine */ } - -static void X509_signature(struct SessionHandle *data, - int numcert, - ASN1_STRING *sig) -{ - char buf[1024]; - char *ptr = buf; - int i; - - for(i=0; i<sig->length; i++) - ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%02x:", sig->data[i]); - - infof(data, " Signature: %s\n", buf); - Curl_ssl_push_certinfo(data, numcert, "Signature", buf); -} - -static void dumpcert(struct SessionHandle *data, X509 *x, int numcert) -{ - BIO *bio_out = BIO_new(BIO_s_mem()); - BUF_MEM *biomem; - - /* this outputs the cert in this 64 column wide style with newlines and - -----BEGIN CERTIFICATE----- texts and more */ - PEM_write_bio_X509(bio_out, x); - - BIO_get_mem_ptr(bio_out, &biomem); - - Curl_ssl_push_certinfo_len(data, numcert, - "Cert", biomem->data, biomem->length); - - BIO_free(bio_out); -} - -/* - * This size was previously 512 which has been reported "too small" without - * any specifics, so it was enlarged to allow more data to get shown uncut. - * The "perfect" size is yet to figure out. - */ -#define CERTBUFFERSIZE 8192 - static CURLcode get_cert_chain(struct connectdata *conn, struct ssl_connect_data *connssl) @@ -2403,17 +2367,12 @@ static CURLcode get_cert_chain(struct connectdata *conn, CURLcode result; STACK_OF(X509) *sk; int i; - char *bufp; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; int numcerts; - - bufp = malloc(CERTBUFFERSIZE); - if(!bufp) - return CURLE_OUT_OF_MEMORY; + BIO *mem; sk = SSL_get_peer_cert_chain(connssl->handle); if(!sk) { - free(bufp); return CURLE_OUT_OF_MEMORY; } @@ -2421,99 +2380,122 @@ static CURLcode get_cert_chain(struct connectdata *conn, result = Curl_ssl_init_certinfo(data, numcerts); if(result) { - free(bufp); return result; } - infof(data, "--- Certificate chain\n"); - for(i=0; i<numcerts; i++) { - long value; - ASN1_INTEGER *num; - ASN1_TIME *certdate; + mem = BIO_new(BIO_s_mem()); - /* get the certs in "importance order" */ -#if 0 - X509 *x = sk_X509_value(sk, numcerts - i - 1); -#else + for(i = 0; i < numcerts; i++) { + ASN1_INTEGER *num; X509 *x = sk_X509_value(sk, i); -#endif - - X509_CINF *cinf; EVP_PKEY *pubkey=NULL; int j; char *ptr; + ASN1_BIT_STRING *psig = NULL; - (void)x509_name_oneline(X509_get_subject_name(x), bufp, CERTBUFFERSIZE); - infof(data, "%2d Subject: %s\n", i, bufp); - Curl_ssl_push_certinfo(data, i, "Subject", bufp); + X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); + push_certinfo("Subject", i); - (void)x509_name_oneline(X509_get_issuer_name(x), bufp, CERTBUFFERSIZE); - infof(data, " Issuer: %s\n", bufp); - Curl_ssl_push_certinfo(data, i, "Issuer", bufp); + X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); + push_certinfo("Issuer", i); - value = X509_get_version(x); - infof(data, " Version: %lu (0x%lx)\n", value+1, value); - snprintf(bufp, CERTBUFFERSIZE, "%lx", value); - Curl_ssl_push_certinfo(data, i, "Version", bufp); /* hex */ + BIO_printf(mem, "%lx", X509_get_version(x)); + push_certinfo("Version", i); - num=X509_get_serialNumber(x); - { - int left = CERTBUFFERSIZE; + num = X509_get_serialNumber(x); + if(num->type == V_ASN1_NEG_INTEGER) + BIO_puts(mem, "-"); + for(j = 0; j < num->length; j++) + BIO_printf(mem, "%02x", num->data[j]); + push_certinfo("Serial Number", i); - ptr = bufp; - if(num->type == V_ASN1_NEG_INTEGER) { - *ptr++='-'; - left--; - } - - for(j=0; (j<num->length) && (left>=3); j++) { - snprintf(ptr, left, "%02x", num->data[j]); - ptr += 2; - left -= 2; +#if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS) + { + X509_ALGOR *palg = NULL; + ASN1_STRING *a = ASN1_STRING_new(); + if(a) { + X509_get0_signature(&psig, &palg, x); + X509_signature_print(mem, palg, a); + ASN1_STRING_free(a); + + if(palg) { + i2a_ASN1_OBJECT(mem, palg->algorithm); + push_certinfo("Public Key Algorithm", i); + } } - if(num->length) - infof(data, " Serial Number: %s\n", bufp); - else - bufp[0]=0; + X509V3_ext(data, i, X509_get0_extensions(x)); } - if(bufp[0]) - Curl_ssl_push_certinfo(data, i, "Serial Number", bufp); /* hex */ - - cinf = x->cert_info; +#else + { + /* before OpenSSL 1.0.2 */ + X509_CINF *cinf = x->cert_info; - j = asn1_object_dump(cinf->signature->algorithm, bufp, CERTBUFFERSIZE); - if(!j) { - infof(data, " Signature Algorithm: %s\n", bufp); - Curl_ssl_push_certinfo(data, i, "Signature Algorithm", bufp); - } + i2a_ASN1_OBJECT(mem, cinf->signature->algorithm); + push_certinfo("Signature Algorithm", i); - certdate = X509_get_notBefore(x); - asn1_output(certdate, bufp, CERTBUFFERSIZE); - infof(data, " Start date: %s\n", bufp); - Curl_ssl_push_certinfo(data, i, "Start date", bufp); + i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm); + push_certinfo("Public Key Algorithm", i); - certdate = X509_get_notAfter(x); - asn1_output(certdate, bufp, CERTBUFFERSIZE); - infof(data, " Expire date: %s\n", bufp); - Curl_ssl_push_certinfo(data, i, "Expire date", bufp); + X509V3_ext(data, i, cinf->extensions); - j = asn1_object_dump(cinf->key->algor->algorithm, bufp, CERTBUFFERSIZE); - if(!j) { - infof(data, " Public Key Algorithm: %s\n", bufp); - Curl_ssl_push_certinfo(data, i, "Public Key Algorithm", bufp); + psig = x->signature; } +#endif + + ASN1_TIME_print(mem, X509_get_notBefore(x)); + push_certinfo("Start date", i); + + ASN1_TIME_print(mem, X509_get_notAfter(x)); + push_certinfo("Expire date", i); pubkey = X509_get_pubkey(x); if(!pubkey) infof(data, " Unable to load public key\n"); else { - switch(pubkey->type) { + int pktype; +#ifdef HAVE_OPAQUE_EVP_PKEY + pktype = EVP_PKEY_id(pubkey); +#else + pktype = pubkey->type; +#endif + switch(pktype) { case EVP_PKEY_RSA: - infof(data, " RSA Public Key (%d bits)\n", - BN_num_bits(pubkey->pkey.rsa->n)); - snprintf(bufp, CERTBUFFERSIZE, "%d", BN_num_bits(pubkey->pkey.rsa->n)); - Curl_ssl_push_certinfo(data, i, "RSA Public Key", bufp); - + { + RSA *rsa; +#ifdef HAVE_OPAQUE_EVP_PKEY + rsa = EVP_PKEY_get0_RSA(pubkey); +#else + rsa = pubkey->pkey.rsa; +#endif + +#ifdef HAVE_OPAQUE_RSA_DSA_DH + { + const BIGNUM *n; + const BIGNUM *e; + const BIGNUM *d; + const BIGNUM *p; + const BIGNUM *q; + const BIGNUM *dmp1; + const BIGNUM *dmq1; + const BIGNUM *iqmp; + + RSA_get0_key(rsa, &n, &e, &d); + RSA_get0_factors(rsa, &p, &q); + RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); + BN_print(mem, n); + push_certinfo("RSA Public Key", i); + print_pubkey_BN(rsa, n, i); + print_pubkey_BN(rsa, e, i); + print_pubkey_BN(rsa, d, i); + print_pubkey_BN(rsa, p, i); + print_pubkey_BN(rsa, q, i); + print_pubkey_BN(rsa, dmp1, i); + print_pubkey_BN(rsa, dmq1, i); + print_pubkey_BN(rsa, iqmp, i); + } +#else + BIO_printf(mem, "%d", BN_num_bits(rsa->n)); + push_certinfo("RSA Public Key", i); print_pubkey_BN(rsa, n, i); print_pubkey_BN(rsa, e, i); print_pubkey_BN(rsa, d, i); @@ -2522,20 +2504,75 @@ static CURLcode get_cert_chain(struct connectdata *conn, print_pubkey_BN(rsa, dmp1, i); print_pubkey_BN(rsa, dmq1, i); print_pubkey_BN(rsa, iqmp, i); +#endif + break; + } case EVP_PKEY_DSA: + { + DSA *dsa; +#ifdef HAVE_OPAQUE_EVP_PKEY + dsa = EVP_PKEY_get0_DSA(pubkey); +#else + dsa = pubkey->pkey.dsa; +#endif +#ifdef HAVE_OPAQUE_RSA_DSA_DH + { + const BIGNUM *p; + const BIGNUM *q; + const BIGNUM *g; + const BIGNUM *priv_key; + const BIGNUM *pub_key; + + DSA_get0_pqg(dsa, &p, &q, &g); + DSA_get0_key(dsa, &pub_key, &priv_key); + + print_pubkey_BN(dsa, p, i); + print_pubkey_BN(dsa, q, i); + print_pubkey_BN(dsa, g, i); + print_pubkey_BN(dsa, priv_key, i); + print_pubkey_BN(dsa, pub_key, i); + } +#else print_pubkey_BN(dsa, p, i); print_pubkey_BN(dsa, q, i); print_pubkey_BN(dsa, g, i); print_pubkey_BN(dsa, priv_key, i); print_pubkey_BN(dsa, pub_key, i); +#endif break; + } case EVP_PKEY_DH: + { + DH *dh; +#ifdef HAVE_OPAQUE_EVP_PKEY + dh = EVP_PKEY_get0_DH(pubkey); +#else + dh = pubkey->pkey.dh; +#endif +#ifdef HAVE_OPAQUE_RSA_DSA_DH + { + const BIGNUM *p; + const BIGNUM *q; + const BIGNUM *g; + const BIGNUM *priv_key; + const BIGNUM *pub_key; + DH_get0_pqg(dh, &p, &q, &g); + DH_get0_key(dh, &pub_key, &priv_key); + print_pubkey_BN(dh, p, i); + print_pubkey_BN(dh, q, i); + print_pubkey_BN(dh, g, i); + print_pubkey_BN(dh, priv_key, i); + print_pubkey_BN(dh, pub_key, i); + } +#else print_pubkey_BN(dh, p, i); print_pubkey_BN(dh, g, i); print_pubkey_BN(dh, priv_key, i); print_pubkey_BN(dh, pub_key, i); +#endif break; + } #if 0 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */ /* left TODO */ @@ -2545,14 +2582,17 @@ static CURLcode get_cert_chain(struct connectdata *conn, EVP_PKEY_free(pubkey); } - X509V3_ext(data, i, cinf->extensions); - - X509_signature(data, i, x->signature); + if(psig) { + for(j = 0; j < psig->length; j++) + BIO_printf(mem, "%02x:", psig->data[j]); + push_certinfo("Signature", i); + } - dumpcert(data, x, i); + PEM_write_bio_X509(mem, x); + push_certinfo("Cert", i); } - free(bufp); + BIO_free(mem); return CURLE_OK; } @@ -2561,7 +2601,8 @@ static CURLcode get_cert_chain(struct connectdata *conn, * Heavily modified from: * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL */ -static CURLcode pkp_pin_peer_pubkey(X509* cert, const char *pinnedpubkey) +static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert, + const char *pinnedpubkey) { /* Scratch */ int len1 = 0, len2 = 0; @@ -2606,7 +2647,7 @@ static CURLcode pkp_pin_peer_pubkey(X509* cert, const char *pinnedpubkey) /* End Gyrations */ /* The one good exit point */ - result = Curl_pin_peer_pubkey(pinnedpubkey, buff1, len1); + result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); } while(0); /* https://www.openssl.org/docs/crypto/buffer.html */ @@ -2630,13 +2671,13 @@ static CURLcode servercert(struct connectdata *conn, { CURLcode result = CURLE_OK; int rc; - long lerr; - ASN1_TIME *certdate; - struct SessionHandle *data = conn->data; + long lerr, len; + struct Curl_easy *data = conn->data; X509 *issuer; FILE *fp; char *buffer = data->state.buffer; const char *ptr; + BIO *mem = BIO_new(BIO_s_mem()); if(data->set.ssl.certinfo) /* we've been asked to gather certificate info! */ @@ -2644,8 +2685,10 @@ static CURLcode servercert(struct connectdata *conn, connssl->server_cert = SSL_get_peer_certificate(connssl->handle); if(!connssl->server_cert) { - if(strict) - failf(data, "SSL: couldn't get peer certificate!"); + if(!strict) + return CURLE_OK; + + failf(data, "SSL: couldn't get peer certificate!"); return CURLE_PEER_FAILED_VERIFICATION; } @@ -2653,15 +2696,19 @@ static CURLcode servercert(struct connectdata *conn, rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert), buffer, BUFSIZE); - infof(data, "\t subject: %s\n", rc?"[NONE]":buffer); + infof(data, " subject: %s\n", rc?"[NONE]":buffer); + + ASN1_TIME_print(mem, X509_get_notBefore(connssl->server_cert)); + len = BIO_get_mem_data(mem, (char **) &ptr); + infof(data, " start date: %.*s\n", len, ptr); + rc = BIO_reset(mem); - certdate = X509_get_notBefore(connssl->server_cert); - asn1_output(certdate, buffer, BUFSIZE); - infof(data, "\t start date: %s\n", buffer); + ASN1_TIME_print(mem, X509_get_notAfter(connssl->server_cert)); + len = BIO_get_mem_data(mem, (char **) &ptr); + infof(data, " expire date: %.*s\n", len, ptr); + rc = BIO_reset(mem); - certdate = X509_get_notAfter(connssl->server_cert); - asn1_output(certdate, buffer, BUFSIZE); - infof(data, "\t expire date: %s\n", buffer); + BIO_free(mem); if(data->set.ssl.verifyhost) { result = verifyhost(conn, connssl->server_cert); @@ -2680,7 +2727,7 @@ static CURLcode servercert(struct connectdata *conn, result = CURLE_SSL_CONNECT_ERROR; } else { - infof(data, "\t issuer: %s\n", buffer); + infof(data, " issuer: %s\n", buffer); /* We could do all sorts of certificate verification stuff here before deallocating the certificate. */ @@ -2720,7 +2767,7 @@ static CURLcode servercert(struct connectdata *conn, return CURLE_SSL_ISSUER_ERROR; } - infof(data, "\t SSL certificate issuer check ok (%s)\n", + infof(data, " SSL certificate issuer check ok (%s)\n", data->set.str[STRING_SSL_ISSUERCERT]); X509_free(issuer); } @@ -2738,16 +2785,16 @@ static CURLcode servercert(struct connectdata *conn, result = CURLE_PEER_FAILED_VERIFICATION; } else - infof(data, "\t SSL certificate verify result: %s (%ld)," + infof(data, " SSL certificate verify result: %s (%ld)," " continuing anyway.\n", X509_verify_cert_error_string(lerr), lerr); } else - infof(data, "\t SSL certificate verify ok.\n"); + infof(data, " SSL certificate verify ok.\n"); } #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ - !defined(OPENSSL_IS_BORINGSSL) + !defined(OPENSSL_NO_OCSP) if(data->set.ssl.verifystatus) { result = verifystatus(conn, connssl); if(result) { @@ -2764,7 +2811,7 @@ static CURLcode servercert(struct connectdata *conn, ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; if(!result && ptr) { - result = pkp_pin_peer_pubkey(connssl->server_cert, ptr); + result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr); if(result) failf(data, "SSL: public key does not match pinned public key!"); } @@ -2779,43 +2826,49 @@ static CURLcode servercert(struct connectdata *conn, static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; - void *old_ssl_sessionid = NULL; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - bool incache; - SSL_SESSION *our_ssl_sessionid; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); - our_ssl_sessionid = SSL_get1_session(connssl->handle); + if(conn->ssl_config.sessionid) { + bool incache; + SSL_SESSION *our_ssl_sessionid; + void *old_ssl_sessionid = NULL; - /* SSL_get1_session() will increment the reference count and the session - will stay in memory until explicitly freed with SSL_SESSION_free(3), - regardless of its state. */ + our_ssl_sessionid = SSL_get1_session(connssl->handle); - incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)); - if(incache) { - if(old_ssl_sessionid != our_ssl_sessionid) { - infof(data, "old SSL session ID is stale, removing\n"); - Curl_ssl_delsessionid(conn, old_ssl_sessionid); - incache = FALSE; + /* SSL_get1_session() will increment the reference count and the session + will stay in memory until explicitly freed with SSL_SESSION_free(3), + regardless of its state. */ + + Curl_ssl_sessionid_lock(conn); + incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)); + if(incache) { + if(old_ssl_sessionid != our_ssl_sessionid) { + infof(data, "old SSL session ID is stale, removing\n"); + Curl_ssl_delsessionid(conn, old_ssl_sessionid); + incache = FALSE; + } } - } - if(!incache) { - result = Curl_ssl_addsessionid(conn, our_ssl_sessionid, - 0 /* unknown size */); - if(result) { - failf(data, "failed to store ssl session"); - return result; + if(!incache) { + result = Curl_ssl_addsessionid(conn, our_ssl_sessionid, + 0 /* unknown size */); + if(result) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "failed to store ssl session"); + return result; + } } - } - else { - /* Session was incache, so refcount already incremented earlier. - * Avoid further increments with each SSL_get1_session() call. - * This does not free the session as refcount remains > 0 - */ - SSL_SESSION_free(our_ssl_sessionid); + else { + /* Session was incache, so refcount already incremented earlier. + * Avoid further increments with each SSL_get1_session() call. + * This does not free the session as refcount remains > 0 + */ + SSL_SESSION_free(our_ssl_sessionid); + } + Curl_ssl_sessionid_unlock(conn); } /* @@ -2843,7 +2896,7 @@ static CURLcode ossl_connect_common(struct connectdata *conn, bool *done) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; @@ -2987,7 +3040,7 @@ static ssize_t ossl_send(struct connectdata *conn, /* SSL_write() is said to return 'int' while write() and send() returns 'size_t' */ int err; - char error_buffer[120]; /* OpenSSL documents that this must be at least 120 + char error_buffer[256]; /* OpenSSL documents that this must be at least 256 bytes long. */ unsigned long sslerror; int memlen; @@ -3019,7 +3072,7 @@ static ssize_t ossl_send(struct connectdata *conn, The OpenSSL error queue contains more information on the error. */ sslerror = ERR_get_error(); failf(conn->data, "SSL_write() error: %s", - ERR_error_string(sslerror, error_buffer)); + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); *curlcode = CURLE_SEND_ERROR; return -1; } @@ -3038,8 +3091,8 @@ static ssize_t ossl_recv(struct connectdata *conn, /* connection data */ size_t buffersize, /* max amount to read */ CURLcode *curlcode) { - char error_buffer[120]; /* OpenSSL documents that this must be at - least 120 bytes long. */ + char error_buffer[256]; /* OpenSSL documents that this must be at + least 256 bytes long. */ unsigned long sslerror; ssize_t nread; int buffsize; @@ -3070,7 +3123,7 @@ static ssize_t ossl_recv(struct connectdata *conn, /* connection data */ /* If the return code was negative or there actually is an error in the queue */ failf(conn->data, "SSL read: %s, errno %d", - ERR_error_string(sslerror, error_buffer), + ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)), SOCKERRNO); *curlcode = CURLE_RECV_ERROR; return -1; @@ -3082,86 +3135,45 @@ static ssize_t ossl_recv(struct connectdata *conn, /* connection data */ size_t Curl_ossl_version(char *buffer, size_t size) { -#ifdef YASSL_VERSION - /* yassl provides an OpenSSL API compatibility layer so it looks identical - to OpenSSL in all other aspects */ - return snprintf(buffer, size, "yassl/%s", YASSL_VERSION); -#else /* YASSL_VERSION */ #ifdef OPENSSL_IS_BORINGSSL - return snprintf(buffer, size, "BoringSSL"); + return snprintf(buffer, size, OSSL_PACKAGE); #else /* OPENSSL_IS_BORINGSSL */ - -#if(OPENSSL_VERSION_NUMBER >= 0x905000) - { - char sub[3]; - unsigned long ssleay_value; - sub[2]='\0'; - sub[1]='\0'; - ssleay_value=SSLeay(); - if(ssleay_value < 0x906000) { - ssleay_value=SSLEAY_VERSION_NUMBER; - sub[0]='\0'; - } - else { - if(ssleay_value&0xff0) { - int minor_ver = (ssleay_value >> 4) & 0xff; - if(minor_ver > 26) { - /* handle extended version introduced for 0.9.8za */ - sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1); - sub[0] = 'z'; - } - else { - sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1); - } - } - else - sub[0]='\0'; - } - - return snprintf(buffer, size, "%s/%lx.%lx.%lx%s", -#ifdef LIBRESSL_VERSION_NUMBER - "LibreSSL" -#else - "OpenSSL" -#endif - , (ssleay_value>>28)&0xf, - (ssleay_value>>20)&0xff, - (ssleay_value>>12)&0xff, - sub); + char sub[3]; + unsigned long ssleay_value; + sub[2]='\0'; + sub[1]='\0'; + ssleay_value=SSLeay(); + if(ssleay_value < 0x906000) { + ssleay_value=SSLEAY_VERSION_NUMBER; + sub[0]='\0'; } - -#else /* OPENSSL_VERSION_NUMBER is less than 0.9.5 */ - -#if(OPENSSL_VERSION_NUMBER >= 0x900000) - return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx", - (OPENSSL_VERSION_NUMBER>>28)&0xff, - (OPENSSL_VERSION_NUMBER>>20)&0xff, - (OPENSSL_VERSION_NUMBER>>12)&0xf); - -#else /* (OPENSSL_VERSION_NUMBER >= 0x900000) */ - { - char sub[2]; - sub[1]='\0'; - if(OPENSSL_VERSION_NUMBER&0x0f) { - sub[0]=(OPENSSL_VERSION_NUMBER&0x0f) + 'a' -1; + else { + if(ssleay_value&0xff0) { + int minor_ver = (ssleay_value >> 4) & 0xff; + if(minor_ver > 26) { + /* handle extended version introduced for 0.9.8za */ + sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1); + sub[0] = 'z'; + } + else { + sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1); + } } else sub[0]='\0'; - - return snprintf(buffer, size, "SSL/%x.%x.%x%s", - (OPENSSL_VERSION_NUMBER>>12)&0xff, - (OPENSSL_VERSION_NUMBER>>8)&0xf, - (OPENSSL_VERSION_NUMBER>>4)&0xf, sub); } -#endif /* (OPENSSL_VERSION_NUMBER >= 0x900000) */ -#endif /* OPENSSL_VERSION_NUMBER is less than 0.9.5 */ + return snprintf(buffer, size, "%s/%lx.%lx.%lx%s", + OSSL_PACKAGE, + (ssleay_value>>28)&0xf, + (ssleay_value>>20)&0xff, + (ssleay_value>>12)&0xff, + sub); #endif /* OPENSSL_IS_BORINGSSL */ -#endif /* YASSL_VERSION */ } /* can be called with data == NULL */ -int Curl_ossl_random(struct SessionHandle *data, unsigned char *entropy, +int Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { if(data) { @@ -3183,7 +3195,7 @@ void Curl_ossl_md5sum(unsigned char *tmp, /* input */ MD5_Final(md5sum, &MD5pw); } -#ifndef OPENSSL_NO_SHA256 +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum /* output */, @@ -3200,7 +3212,7 @@ void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */ bool Curl_ossl_cert_status_request(void) { #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ - !defined(OPENSSL_IS_BORINGSSL) + !defined(OPENSSL_NO_OCSP) return TRUE; #else return FALSE; diff --git a/Utilities/cmcurl/lib/vtls/openssl.h b/Utilities/cmcurl/lib/vtls/openssl.h index a1f347a..ee18e71 100644 --- a/Utilities/cmcurl/lib/vtls/openssl.h +++ b/Utilities/cmcurl/lib/vtls/openssl.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -41,20 +41,20 @@ void Curl_ossl_close(struct connectdata *conn, int sockindex); /* tell OpenSSL to close down all open information regarding connections (and thus session ID caching etc) */ -void Curl_ossl_close_all(struct SessionHandle *data); +void Curl_ossl_close_all(struct Curl_easy *data); /* Sets an OpenSSL engine */ -CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine); +CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine); /* function provided for the generic SSL-layer, called when a session id should be freed */ void Curl_ossl_session_free(void *ptr); /* Sets engine as default for all SSL operations */ -CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data); +CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data); /* Build list of OpenSSL engines */ -struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data); +struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data); int Curl_ossl_init(void); void Curl_ossl_cleanup(void); @@ -66,7 +66,7 @@ bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex); /* return 0 if a find random is filled in */ -int Curl_ossl_random(struct SessionHandle *data, unsigned char *entropy, +int Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy, size_t length); void Curl_ossl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, @@ -88,9 +88,12 @@ bool Curl_ossl_cert_status_request(void); /* this backend supports CURLOPT_CERTINFO */ #define have_curlssl_certinfo 1 -/* this backend suppots CURLOPT_SSL_CTX_* */ +/* this backend supports CURLOPT_SSL_CTX_* */ #define have_curlssl_ssl_ctx 1 +/* this backend supports CURLOPT_PINNEDPUBLICKEY */ +#define have_curlssl_pinnedpubkey 1 + /* API setup for OpenSSL */ #define curlssl_init Curl_ossl_init #define curlssl_cleanup Curl_ossl_cleanup @@ -108,7 +111,7 @@ bool Curl_ossl_cert_status_request(void); #define curlssl_data_pending(x,y) Curl_ossl_data_pending(x,y) #define curlssl_random(x,y,z) Curl_ossl_random(x,y,z) #define curlssl_md5sum(a,b,c,d) Curl_ossl_md5sum(a,b,c,d) -#ifndef OPENSSL_NO_SHA256 +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) #define curlssl_sha256sum(a,b,c,d) Curl_ossl_sha256sum(a,b,c,d) #endif #define curlssl_cert_status_request() Curl_ossl_cert_status_request() diff --git a/Utilities/cmcurl/lib/vtls/polarssl.c b/Utilities/cmcurl/lib/vtls/polarssl.c index 066c055..d33f548 100644 --- a/Utilities/cmcurl/lib/vtls/polarssl.c +++ b/Utilities/cmcurl/lib/vtls/polarssl.c @@ -5,12 +5,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -36,6 +36,7 @@ #include <polarssl/certs.h> #include <polarssl/x509.h> #include <polarssl/version.h> +#include <polarssl/sha256.h> #if POLARSSL_VERSION_NUMBER < 0x01030000 #error too old PolarSSL @@ -60,6 +61,15 @@ /* The last #include file should be: */ #include "memdebug.h" +/* See https://tls.mbed.org/discussions/generic/ + howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der +*/ +#define RSA_PUB_DER_MAX_BYTES (38 + 2 * POLARSSL_MPI_MAX_SIZE) +#define ECP_PUB_DER_MAX_BYTES (30 + 2 * POLARSSL_ECP_MAX_BYTES) + +#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \ + RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES) + /* apply threading? */ #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) #define THREADING_SUPPORT @@ -74,12 +84,12 @@ static int entropy_init_initialized = 0; static void entropy_init_mutex(entropy_context *ctx) { /* lock 0 = entropy_init_mutex() */ - polarsslthreadlock_lock_function(0); + Curl_polarsslthreadlock_lock_function(0); if(entropy_init_initialized == 0) { entropy_init(ctx); entropy_init_initialized = 1; } - polarsslthreadlock_unlock_function(0); + Curl_polarsslthreadlock_unlock_function(0); } /* end of entropy_init_mutex() */ @@ -88,9 +98,9 @@ static int entropy_func_mutex(void *data, unsigned char *output, size_t len) { int ret; /* lock 1 = entropy_func_mutex() */ - polarsslthreadlock_lock_function(1); + Curl_polarsslthreadlock_lock_function(1); ret = entropy_func(data, output, len); - polarsslthreadlock_unlock_function(1); + Curl_polarsslthreadlock_unlock_function(1); return ret; } @@ -104,12 +114,12 @@ static int entropy_func_mutex(void *data, unsigned char *output, size_t len) #ifdef POLARSSL_DEBUG static void polarssl_debug(void *context, int level, const char *line) { - struct SessionHandle *data = NULL; + struct Curl_easy *data = NULL; if(!context) return; - data = (struct SessionHandle *)context; + data = (struct Curl_easy *)context; infof(data, "%s", line); (void) level; @@ -130,7 +140,7 @@ static CURLcode polarssl_connect_step1(struct connectdata *conn, int sockindex) { - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; bool sni = TRUE; /* default is SNI enabled */ @@ -140,8 +150,6 @@ polarssl_connect_step1(struct connectdata *conn, #else struct in_addr addr; #endif - void *old_session = NULL; - size_t old_session_size = 0; char errorbuf[128]; errorbuf[0]=0; @@ -157,7 +165,7 @@ polarssl_connect_step1(struct connectdata *conn, entropy_init_mutex(&entropy); if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy, - connssl->ssn.id, connssl->ssn.length)) != 0) { + NULL, 0)) != 0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ @@ -168,7 +176,7 @@ polarssl_connect_step1(struct connectdata *conn, entropy_init(&connssl->entropy); if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy, - connssl->ssn.id, connssl->ssn.length)) != 0) { + NULL, 0)) != 0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ @@ -328,13 +336,22 @@ polarssl_connect_step1(struct connectdata *conn, net_send, &conn->sock[sockindex]); ssl_set_ciphersuites(&connssl->ssl, ssl_list_ciphersuites()); - if(!Curl_ssl_getsessionid(conn, &old_session, &old_session_size)) { - memcpy(&connssl->ssn, old_session, old_session_size); - infof(data, "PolarSSL re-using session\n"); - } - ssl_set_session(&connssl->ssl, - &connssl->ssn); + /* Check if there's a cached ID we can/should use here! */ + if(conn->ssl_config.sessionid) { + void *old_session = NULL; + + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) { + ret = ssl_set_session(&connssl->ssl, old_session); + Curl_ssl_sessionid_unlock(conn); + if(ret) { + failf(data, "ssl_set_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; + } + infof(data, "PolarSSL re-using session\n"); + } + } ssl_set_ca_chain(&connssl->ssl, &connssl->cacert, @@ -344,22 +361,21 @@ polarssl_connect_step1(struct connectdata *conn, ssl_set_own_cert_rsa(&connssl->ssl, &connssl->clicert, &connssl->rsa); - if(!Curl_inet_pton(AF_INET, conn->host.name, &addr) && -#ifdef ENABLE_IPV6 - !Curl_inet_pton(AF_INET6, conn->host.name, &addr) && -#endif - sni && ssl_set_hostname(&connssl->ssl, conn->host.name)) { - infof(data, "WARNING: failed to configure " - "server name indication (SNI) TLS extension\n"); + if(ssl_set_hostname(&connssl->ssl, conn->host.name)) { + /* ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name + to set in the SNI extension. So even if curl connects to a host + specified as an IP address, this function must be used. */ + failf(data, "couldn't set hostname in PolarSSL"); + return CURLE_SSL_CONNECT_ERROR; } #ifdef HAS_ALPN - if(data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_alpn) { static const char* protocols[3]; int cur = 0; #ifdef USE_NGHTTP2 - if(data->set.httpversion == CURL_HTTP_VERSION_2_0) { + if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID; infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } @@ -388,7 +404,7 @@ polarssl_connect_step2(struct connectdata *conn, int sockindex) { int ret; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; char buffer[1024]; @@ -453,8 +469,63 @@ polarssl_connect_step2(struct connectdata *conn, infof(data, "Dumping cert info:\n%s\n", buffer); } + /* adapted from mbedtls.c */ + if(data->set.str[STRING_SSL_PINNEDPUBLICKEY]) { + int size; + CURLcode result; + x509_crt *p; + unsigned char pubkey[PUB_DER_MAX_BYTES]; + const x509_crt *peercert; + + peercert = ssl_get_peer_cert(&connssl->ssl); + + if(!peercert || !peercert->raw.p || !peercert->raw.len) { + failf(data, "Failed due to missing peer certificate"); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + p = calloc(1, sizeof(*p)); + + if(!p) + return CURLE_OUT_OF_MEMORY; + + x509_crt_init(p); + + /* Make a copy of our const peercert because pk_write_pubkey_der + needs a non-const key, for now. + https://github.com/ARMmbed/mbedtls/issues/396 */ + if(x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) { + failf(data, "Failed copying peer certificate"); + x509_crt_free(p); + free(p); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + size = pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES); + + if(size <= 0) { + failf(data, "Failed copying public key from peer certificate"); + x509_crt_free(p); + free(p); + return CURLE_SSL_PINNEDPUBKEYNOTMATCH; + } + + /* pk_write_pubkey_der writes data at the end of the buffer. */ + result = Curl_pin_peer_pubkey(data, + data->set.str[STRING_SSL_PINNEDPUBLICKEY], + &pubkey[PUB_DER_MAX_BYTES - size], size); + if(result) { + x509_crt_free(p); + free(p); + return result; + } + + x509_crt_free(p); + free(p); + } + #ifdef HAS_ALPN - if(data->set.ssl_enable_alpn) { + if(conn->bits.tls_enable_alpn) { const char *next_protocol = ssl_get_alpn_protocol(&connssl->ssl); if(next_protocol != NULL) { @@ -463,7 +534,7 @@ polarssl_connect_step2(struct connectdata *conn, #ifdef USE_NGHTTP2 if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN)) { - conn->negnpn = CURL_HTTP_VERSION_2_0; + conn->negnpn = CURL_HTTP_VERSION_2; } else #endif @@ -486,39 +557,40 @@ static CURLcode polarssl_connect_step3(struct connectdata *conn, int sockindex) { - CURLcode result = CURLE_OK; + CURLcode retcode = CURLE_OK; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct SessionHandle *data = conn->data; - void *old_ssl_sessionid = NULL; - ssl_session *our_ssl_sessionid = &conn->ssl[sockindex].ssn; - bool incache; + struct Curl_easy *data = conn->data; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); - /* Save the current session data for possible re-use */ - incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)); - if(incache) { - if(old_ssl_sessionid != our_ssl_sessionid) { - infof(data, "old SSL session ID is stale, removing\n"); - Curl_ssl_delsessionid(conn, old_ssl_sessionid); - incache = FALSE; - } - } + if(conn->ssl_config.sessionid) { + int ret; + ssl_session *our_ssl_sessionid; + void *old_ssl_sessionid = NULL; - if(!incache) { - void *new_session = malloc(sizeof(ssl_session)); + our_ssl_sessionid = malloc(sizeof(ssl_session)); + if(!our_ssl_sessionid) + return CURLE_OUT_OF_MEMORY; - if(new_session) { - memcpy(new_session, our_ssl_sessionid, sizeof(ssl_session)); + ssl_session_init(our_ssl_sessionid); - result = Curl_ssl_addsessionid(conn, new_session, sizeof(ssl_session)); + ret = ssl_get_session(&connssl->ssl, our_ssl_sessionid); + if(ret) { + failf(data, "ssl_get_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; } - else - result = CURLE_OUT_OF_MEMORY; - if(result) { + /* If there's already a matching session in the cache, delete it */ + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL)) + Curl_ssl_delsessionid(conn, old_ssl_sessionid); + + retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0); + Curl_ssl_sessionid_unlock(conn); + if(retcode) { + free(our_ssl_sessionid); failf(data, "failed to store ssl session"); - return result; + return retcode; } } @@ -584,6 +656,7 @@ static ssize_t polarssl_recv(struct connectdata *conn, void Curl_polarssl_session_free(void *ptr) { + ssl_session_free(ptr); free(ptr); } @@ -605,7 +678,7 @@ polarssl_connect_common(struct connectdata *conn, bool *done) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; @@ -740,14 +813,14 @@ Curl_polarssl_connect(struct connectdata *conn, * return 0 error initializing SSL * return 1 SSL initialized successfully */ -int polarssl_init(void) +int Curl_polarssl_init(void) { - return polarsslthreadlock_thread_setup(); + return Curl_polarsslthreadlock_thread_setup(); } -void polarssl_cleanup(void) +void Curl_polarssl_cleanup(void) { - (void)polarsslthreadlock_thread_cleanup(); + (void)Curl_polarsslthreadlock_thread_cleanup(); } #endif /* USE_POLARSSL */ diff --git a/Utilities/cmcurl/lib/vtls/polarssl.h b/Utilities/cmcurl/lib/vtls/polarssl.h index f980dbb..7098b24 100644 --- a/Utilities/cmcurl/lib/vtls/polarssl.h +++ b/Utilities/cmcurl/lib/vtls/polarssl.h @@ -7,12 +7,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, Hoi-Ho Chan, <hoiho.chan@gmail.com> - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,9 +26,11 @@ #ifdef USE_POLARSSL +#include <polarssl/sha256.h> + /* Called on first use PolarSSL, setup threading if supported */ -int polarssl_init(void); -void polarssl_cleanup(void); +int Curl_polarssl_init(void); +void Curl_polarssl_cleanup(void); CURLcode Curl_polarssl_connect(struct connectdata *conn, int sockindex); @@ -50,9 +52,12 @@ int Curl_polarssl_shutdown(struct connectdata *conn, int sockindex); /* this backend supports the CAPATH option */ #define have_curlssl_ca_path 1 +/* this backends supports CURLOPT_PINNEDPUBLICKEY */ +#define have_curlssl_pinnedpubkey 1 + /* API setup for PolarSSL */ -#define curlssl_init() polarssl_init() -#define curlssl_cleanup() polarssl_cleanup() +#define curlssl_init() Curl_polarssl_init() +#define curlssl_cleanup() Curl_polarssl_cleanup() #define curlssl_connect Curl_polarssl_connect #define curlssl_connect_nonblocking Curl_polarssl_connect_nonblocking #define curlssl_session_free(x) Curl_polarssl_session_free(x) @@ -65,6 +70,7 @@ int Curl_polarssl_shutdown(struct connectdata *conn, int sockindex); #define curlssl_version Curl_polarssl_version #define curlssl_check_cxn(x) ((void)x, -1) #define curlssl_data_pending(x,y) ((void)x, (void)y, 0) +#define curlssl_sha256sum(a,b,c,d) sha256(a,b,c,0) /* This might cause libcurl to use a weeker random! TODO: implement proper use of Polarssl's CTR-DRBG or HMAC-DRBG and use that diff --git a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c index 62abf43..3b0ebf8 100644 --- a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c +++ b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c @@ -5,12 +5,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * + * Copyright (C) 2013-2015, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> - * Copyright (C) 2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -22,7 +22,7 @@ ***************************************************************************/ #include "curl_setup.h" -#if defined(USE_POLARSSL) && \ +#if (defined(USE_POLARSSL) || defined(USE_MBEDTLS)) && \ (defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)) #if defined(USE_THREADS_POSIX) @@ -47,7 +47,7 @@ /* This array will store all of the mutexes available to PolarSSL. */ static POLARSSL_MUTEX_T *mutex_buf = NULL; -int polarsslthreadlock_thread_setup(void) +int Curl_polarsslthreadlock_thread_setup(void) { int i; int ret; @@ -73,7 +73,7 @@ int polarsslthreadlock_thread_setup(void) return 1; /* OK */ } -int polarsslthreadlock_thread_cleanup(void) +int Curl_polarsslthreadlock_thread_cleanup(void) { int i; int ret; @@ -100,7 +100,7 @@ int polarsslthreadlock_thread_cleanup(void) return 1; /* OK */ } -int polarsslthreadlock_lock_function(int n) +int Curl_polarsslthreadlock_lock_function(int n) { int ret; #ifdef HAVE_PTHREAD_H @@ -125,7 +125,7 @@ int polarsslthreadlock_lock_function(int n) return 1; /* OK */ } -int polarsslthreadlock_unlock_function(int n) +int Curl_polarsslthreadlock_unlock_function(int n) { int ret; #ifdef HAVE_PTHREAD_H @@ -150,4 +150,4 @@ int polarsslthreadlock_unlock_function(int n) return 1; /* OK */ } -#endif /* USE_POLARSSL */ +#endif /* USE_POLARSSL || USE_MBEDTLS */ diff --git a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.h b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.h index b67b3f9..dda5359 100644 --- a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.h +++ b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.h @@ -7,12 +7,12 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * + * Copyright (C) 2013-2015, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, Hoi-Ho Chan, <hoiho.chan@gmail.com> - * Copyright (C) 2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -24,7 +24,7 @@ ***************************************************************************/ #include "curl_setup.h" -#ifdef USE_POLARSSL +#if (defined USE_POLARSSL) || (defined USE_MBEDTLS) #if defined(USE_THREADS_POSIX) # define POLARSSL_MUTEX_T pthread_mutex_t @@ -34,17 +34,17 @@ #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) -int polarsslthreadlock_thread_setup(void); -int polarsslthreadlock_thread_cleanup(void); -int polarsslthreadlock_lock_function(int n); -int polarsslthreadlock_unlock_function(int n); +int Curl_polarsslthreadlock_thread_setup(void); +int Curl_polarsslthreadlock_thread_cleanup(void); +int Curl_polarsslthreadlock_lock_function(int n); +int Curl_polarsslthreadlock_unlock_function(int n); #else -#define polarsslthreadlock_thread_setup() 1 -#define polarsslthreadlock_thread_cleanup() 1 -#define polarsslthreadlock_lock_function(x) 1 -#define polarsslthreadlock_unlock_function(x) 1 +#define Curl_polarsslthreadlock_thread_setup() 1 +#define Curl_polarsslthreadlock_thread_cleanup() 1 +#define Curl_polarsslthreadlock_lock_function(x) 1 +#define Curl_polarsslthreadlock_unlock_function(x) 1 #endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ diff --git a/Utilities/cmcurl/lib/vtls/schannel.c b/Utilities/cmcurl/lib/vtls/schannel.c index 2174e21..f991ec9 100644 --- a/Utilities/cmcurl/lib/vtls/schannel.c +++ b/Utilities/cmcurl/lib/vtls/schannel.c @@ -5,13 +5,13 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 2012 - 2015, Marc Hoersken, <info@marc-hoersken.de> + * Copyright (C) 2012 - 2016, Marc Hoersken, <info@marc-hoersken.de> * Copyright (C) 2012, Mark Salisbury, <mark.salisbury@hp.com> - * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -56,11 +56,23 @@ #include "inet_pton.h" /* for IP addr SNI check */ #include "curl_multibyte.h" #include "warnless.h" +#include "x509asn1.h" #include "curl_printf.h" +#include "system_win32.h" + + /* The last #include file should be: */ #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" +/* ALPN requires version 8.1 of the Windows SDK, which was + shipped with Visual Studio 2013, aka _MSC_VER 1800: + + https://technet.microsoft.com/en-us/library/hh831771%28v=ws.11%29.aspx +*/ +#if defined(_MSC_VER) && (_MSC_VER >= 1800) && !defined(_USING_V110_SDK71_) +# define HAS_ALPN 1 +#endif + /* Uncomment to force verbose output * #define infof(x, y, ...) printf(y, __VA_ARGS__) * #define failf(x, y, ...) printf(y, __VA_ARGS__) @@ -93,10 +105,15 @@ static CURLcode schannel_connect_step1(struct connectdata *conn, int sockindex) { ssize_t written = -1; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; SecBuffer outbuf; SecBufferDesc outbuf_desc; + SecBuffer inbuf; + SecBufferDesc inbuf_desc; +#ifdef HAS_ALPN + unsigned char alpn_buffer[128]; +#endif SCHANNEL_CRED schannel_cred; SECURITY_STATUS sspi_status = SEC_E_OK; struct curl_schannel_cred *old_cred = NULL; @@ -110,12 +127,24 @@ schannel_connect_step1(struct connectdata *conn, int sockindex) infof(data, "schannel: SSL/TLS connection with %s port %hu (step 1/3)\n", conn->host.name, conn->remote_port); + connssl->cred = NULL; + /* check for an existing re-usable credential handle */ - if(!Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL)) { - connssl->cred = old_cred; - infof(data, "schannel: re-using existing credential handle\n"); + if(conn->ssl_config.sessionid) { + Curl_ssl_sessionid_lock(conn); + if(!Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL)) { + connssl->cred = old_cred; + infof(data, "schannel: re-using existing credential handle\n"); + + /* increment the reference counter of the credential/session handle */ + connssl->cred->refcount++; + infof(data, "schannel: incremented credential handle refcount = %d\n", + connssl->cred->refcount); + } + Curl_ssl_sessionid_unlock(conn); } - else { + + if(!connssl->cred) { /* setup Schannel API options */ memset(&schannel_cred, 0, sizeof(schannel_cred)); schannel_cred.dwVersion = SCHANNEL_CRED_VERSION; @@ -188,8 +217,10 @@ schannel_connect_step1(struct connectdata *conn, int sockindex) return CURLE_OUT_OF_MEMORY; } memset(connssl->cred, 0, sizeof(struct curl_schannel_cred)); + connssl->cred->refcount = 1; - /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx */ + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx + */ sspi_status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL, @@ -218,6 +249,63 @@ schannel_connect_step1(struct connectdata *conn, int sockindex) infof(data, "schannel: using IP address, SNI is not supported by OS.\n"); } +#ifdef HAS_ALPN + /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above */ + if(conn->bits.tls_enable_alpn && + Curl_verify_windows_version(6, 3, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + int cur = 0; + int list_start_index = 0; + unsigned int* extension_len = NULL; + unsigned short* list_len = NULL; + + /* The first four bytes will be an unsigned int indicating number + of bytes of data in the rest of the the buffer. */ + extension_len = (unsigned int*)(&alpn_buffer[cur]); + cur += sizeof(unsigned int); + + /* The next four bytes are an indicator that this buffer will contain + ALPN data, as opposed to NPN, for example. */ + *(unsigned int*)&alpn_buffer[cur] = + SecApplicationProtocolNegotiationExt_ALPN; + cur += sizeof(unsigned int); + + /* The next two bytes will be an unsigned short indicating the number + of bytes used to list the preferred protocols. */ + list_len = (unsigned short*)(&alpn_buffer[cur]); + cur += sizeof(unsigned short); + + list_start_index = cur; + +#ifdef USE_NGHTTP2 + if(data->set.httpversion >= CURL_HTTP_VERSION_2) { + memcpy(&alpn_buffer[cur], NGHTTP2_PROTO_ALPN, NGHTTP2_PROTO_ALPN_LEN); + cur += NGHTTP2_PROTO_ALPN_LEN; + infof(data, "schannel: ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); + } +#endif + + alpn_buffer[cur++] = ALPN_HTTP_1_1_LENGTH; + memcpy(&alpn_buffer[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH); + cur += ALPN_HTTP_1_1_LENGTH; + infof(data, "schannel: ALPN, offering %s\n", ALPN_HTTP_1_1); + + *list_len = curlx_uitous(cur - list_start_index); + *extension_len = *list_len + sizeof(unsigned int) + sizeof(unsigned short); + + InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); + } + else + { + InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); + } +#else /* HAS_ALPN */ + InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&inbuf_desc, &inbuf, 1); +#endif + /* setup output buffer */ InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&outbuf_desc, &outbuf, 1); @@ -240,11 +328,11 @@ schannel_connect_step1(struct connectdata *conn, int sockindex) if(!host_name) return CURLE_OUT_OF_MEMORY; - /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */ + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */ sspi_status = s_pSecFn->InitializeSecurityContext( &connssl->cred->cred_handle, NULL, host_name, - connssl->req_flags, 0, 0, NULL, 0, &connssl->ctxt->ctxt_handle, + connssl->req_flags, 0, 0, &inbuf_desc, 0, &connssl->ctxt->ctxt_handle, &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp); Curl_unicodefree(host_name); @@ -291,7 +379,7 @@ schannel_connect_step2(struct connectdata *conn, int sockindex) { int i; ssize_t nread = -1, written = -1; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; unsigned char *reallocated_buffer; size_t reallocated_length; @@ -407,8 +495,8 @@ schannel_connect_step2(struct connectdata *conn, int sockindex) if(!host_name) return CURLE_OUT_OF_MEMORY; - /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */ - + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx + */ sspi_status = s_pSecFn->InitializeSecurityContext( &connssl->cred->cred_handle, &connssl->ctxt->ctxt_handle, host_name, connssl->req_flags, 0, 0, &inbuf_desc, 0, NULL, @@ -531,10 +619,13 @@ static CURLcode schannel_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; - struct curl_schannel_cred *old_cred = NULL; - bool incache; + SECURITY_STATUS sspi_status = SEC_E_OK; + CERT_CONTEXT *ccert_context = NULL; +#ifdef HAS_ALPN + SecPkgContext_ApplicationProtocol alpn_result; +#endif DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); @@ -559,34 +650,98 @@ schannel_connect_step3(struct connectdata *conn, int sockindex) return CURLE_SSL_CONNECT_ERROR; } - /* increment the reference counter of the credential/session handle */ - if(connssl->cred && connssl->ctxt) { - connssl->cred->refcount++; - infof(data, "schannel: incremented credential handle refcount = %d\n", - connssl->cred->refcount); +#ifdef HAS_ALPN + /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above */ + if(conn->bits.tls_enable_alpn && + Curl_verify_windows_version(6, 3, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL)) { + sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle, + SECPKG_ATTR_APPLICATION_PROTOCOL, &alpn_result); + + if(sspi_status != SEC_E_OK) { + failf(data, "schannel: failed to retrieve ALPN result"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(alpn_result.ProtoNegoStatus == + SecApplicationProtocolNegotiationStatus_Success) { + + infof(data, "schannel: ALPN, server accepted to use %.*s\n", + alpn_result.ProtocolIdSize, alpn_result.ProtocolId); + +#ifdef USE_NGHTTP2 + if(alpn_result.ProtocolIdSize == NGHTTP2_PROTO_VERSION_ID_LEN && + !memcmp(NGHTTP2_PROTO_VERSION_ID, alpn_result.ProtocolId, + NGHTTP2_PROTO_VERSION_ID_LEN)) { + conn->negnpn = CURL_HTTP_VERSION_2; + } + else +#endif + if(alpn_result.ProtocolIdSize == ALPN_HTTP_1_1_LENGTH && + !memcmp(ALPN_HTTP_1_1, alpn_result.ProtocolId, + ALPN_HTTP_1_1_LENGTH)) { + conn->negnpn = CURL_HTTP_VERSION_1_1; + } + } + else + infof(data, "ALPN, server did not agree to a protocol\n"); } +#endif /* save the current session data for possible re-use */ - incache = !(Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL)); - if(incache) { - if(old_cred != connssl->cred) { - infof(data, "schannel: old credential handle is stale, removing\n"); - Curl_ssl_delsessionid(conn, (void *)old_cred); - incache = FALSE; + if(conn->ssl_config.sessionid) { + bool incache; + struct curl_schannel_cred *old_cred = NULL; + + Curl_ssl_sessionid_lock(conn); + incache = !(Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL)); + if(incache) { + if(old_cred != connssl->cred) { + infof(data, "schannel: old credential handle is stale, removing\n"); + /* we're not taking old_cred ownership here, no refcount++ is needed */ + Curl_ssl_delsessionid(conn, (void *)old_cred); + incache = FALSE; + } } + if(!incache) { + result = Curl_ssl_addsessionid(conn, (void *)connssl->cred, + sizeof(struct curl_schannel_cred)); + if(result) { + Curl_ssl_sessionid_unlock(conn); + failf(data, "schannel: failed to store credential handle"); + return result; + } + else { + /* this cred session is now also referenced by sessionid cache */ + connssl->cred->refcount++; + infof(data, "schannel: stored credential handle in session cache\n"); + } + } + Curl_ssl_sessionid_unlock(conn); } - if(!incache) { - result = Curl_ssl_addsessionid(conn, (void *)connssl->cred, - sizeof(struct curl_schannel_cred)); - if(result) { - failf(data, "schannel: failed to store credential handle"); - return result; + if(data->set.ssl.certinfo) { + sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle, + SECPKG_ATTR_REMOTE_CERT_CONTEXT, &ccert_context); + + if((sspi_status != SEC_E_OK) || (ccert_context == NULL)) { + failf(data, "schannel: failed to retrieve remote cert context"); + return CURLE_SSL_CONNECT_ERROR; } - else { - connssl->cred->cached = TRUE; - infof(data, "schannel: stored credential handle in session cache\n"); + + result = Curl_ssl_init_certinfo(data, 1); + if(!result) { + if(((ccert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) && + (ccert_context->cbCertEncoded > 0)) { + + const char *beg = (const char *) ccert_context->pbCertEncoded; + const char *end = beg + ccert_context->cbCertEncoded; + result = Curl_extract_certinfo(conn, 0, beg, end); + } } + CertFreeCertificateContext(ccert_context); + if(result) + return result; } connssl->connecting_state = ssl_connect_done; @@ -599,7 +754,7 @@ schannel_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; @@ -759,7 +914,7 @@ schannel_send(struct connectdata *conn, int sockindex, /* copy data into output buffer */ memcpy(outbuf[1].pvBuffer, buf, len); - /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */ + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */ sspi_status = s_pSecFn->EncryptMessage(&connssl->ctxt->ctxt_handle, 0, &outbuf_desc, 0); @@ -858,7 +1013,7 @@ schannel_recv(struct connectdata *conn, int sockindex, { size_t size = 0; ssize_t nread = -1; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; unsigned char *reallocated_buffer; size_t reallocated_length; @@ -973,7 +1128,8 @@ schannel_recv(struct connectdata *conn, int sockindex, InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&inbuf_desc, inbuf, 4); - /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx */ + /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx + */ sspi_status = s_pSecFn->DecryptMessage(&connssl->ctxt->ctxt_handle, &inbuf_desc, 0, NULL); @@ -1120,23 +1276,8 @@ cleanup: */ if(len && !connssl->decdata_offset && connssl->recv_connection_closed && !connssl->recv_sspi_close_notify) { - BOOL isWin2k; - ULONGLONG cm; - OSVERSIONINFOEX osver; - - memset(&osver, 0, sizeof(osver)); - osver.dwOSVersionInfoSize = sizeof(osver); - osver.dwMajorVersion = 5; - - cm = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL); - cm = VerSetConditionMask(cm, VER_MINORVERSION, VER_EQUAL); - cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); - - isWin2k = VerifyVersionInfo(&osver, - (VER_MAJORVERSION | VER_MINORVERSION | - VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR), - cm); + bool isWin2k = Curl_verify_windows_version(5, 0, PLATFORM_WINNT, + VERSION_EQUAL); if(isWin2k && sspi_status == SEC_E_OK) connssl->recv_sspi_close_notify = true; @@ -1204,7 +1345,7 @@ bool Curl_schannel_data_pending(const struct connectdata *conn, int sockindex) if(connssl->use) /* SSL/TLS is in use */ return (connssl->encdata_offset > 0 || - connssl->decdata_offset > 0 ) ? TRUE : FALSE; + connssl->decdata_offset > 0) ? TRUE : FALSE; else return FALSE; } @@ -1218,10 +1359,10 @@ void Curl_schannel_close(struct connectdata *conn, int sockindex) int Curl_schannel_shutdown(struct connectdata *conn, int sockindex) { - /* See http://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx + /* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx * Shutting Down an Schannel Connection */ - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; infof(data, "schannel: shutting down SSL/TLS connection with %s port %hu\n", @@ -1294,19 +1435,10 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex) /* free SSPI Schannel API credential handle */ if(connssl->cred) { - /* decrement the reference counter of the credential/session handle */ - if(connssl->cred->refcount > 0) { - connssl->cred->refcount--; - infof(data, "schannel: decremented credential handle refcount = %d\n", - connssl->cred->refcount); - } - - /* if the handle was not cached and the refcount is zero */ - if(!connssl->cred->cached && connssl->cred->refcount == 0) { - infof(data, "schannel: clear credential handle\n"); - s_pSecFn->FreeCredentialsHandle(&connssl->cred->cred_handle); - Curl_safefree(connssl->cred); - } + Curl_ssl_sessionid_lock(conn); + Curl_schannel_session_free(connssl->cred); + Curl_ssl_sessionid_unlock(conn); + connssl->cred = NULL; } /* free internal buffer for received encrypted data */ @@ -1328,16 +1460,13 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex) void Curl_schannel_session_free(void *ptr) { + /* this is expected to be called under sessionid lock */ struct curl_schannel_cred *cred = ptr; - if(cred && cred->cached) { - if(cred->refcount == 0) { - s_pSecFn->FreeCredentialsHandle(&cred->cred_handle); - Curl_safefree(cred); - } - else { - cred->cached = FALSE; - } + cred->refcount--; + if(cred->refcount == 0) { + s_pSecFn->FreeCredentialsHandle(&cred->cred_handle); + Curl_safefree(cred); } } @@ -1379,7 +1508,7 @@ int Curl_schannel_random(unsigned char *entropy, size_t length) static CURLcode verify_certificate(struct connectdata *conn, int sockindex) { SECURITY_STATUS status; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CURLcode result = CURLE_OK; CERT_CONTEXT *pCertContextServer = NULL; diff --git a/Utilities/cmcurl/lib/vtls/schannel.h b/Utilities/cmcurl/lib/vtls/schannel.h index 5329584..8a4991e 100644 --- a/Utilities/cmcurl/lib/vtls/schannel.h +++ b/Utilities/cmcurl/lib/vtls/schannel.h @@ -12,7 +12,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -97,6 +97,9 @@ int Curl_schannel_random(unsigned char *entropy, size_t length); /* Set the API backend definition to Schannel */ #define CURL_SSL_BACKEND CURLSSLBACKEND_SCHANNEL +/* this backend supports CURLOPT_CERTINFO */ +#define have_curlssl_certinfo 1 + /* API setup for Schannel */ #define curlssl_init Curl_schannel_init #define curlssl_cleanup Curl_schannel_cleanup diff --git a/Utilities/cmcurl/lib/vtls/vtls.c b/Utilities/cmcurl/lib/vtls/vtls.c index 01bbc61..3863777 100644 --- a/Utilities/cmcurl/lib/vtls/vtls.c +++ b/Utilities/cmcurl/lib/vtls/vtls.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -41,7 +41,7 @@ defines/macros #defined by the lib-specific header files. "SSL/TLS Strong Encryption: An Introduction" - http://httpd.apache.org/docs-2.0/ssl/ssl_intro.html + https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html */ #include "curl_setup.h" @@ -99,6 +99,7 @@ Curl_ssl_config_matches(struct ssl_config_data* data, (data->verifyhost == needle->verifyhost) && safe_strequal(data->CApath, needle->CApath) && safe_strequal(data->CAfile, needle->CAfile) && + safe_strequal(data->clientcert, needle->clientcert) && safe_strequal(data->random_file, needle->random_file) && safe_strequal(data->egdsocket, needle->egdsocket) && safe_strequal(data->cipher_list, needle->cipher_list)) @@ -156,6 +157,15 @@ Curl_clone_ssl_config(struct ssl_config_data *source, else dest->random_file = NULL; + if(source->clientcert) { + dest->clientcert = strdup(source->clientcert); + if(!dest->clientcert) + return FALSE; + dest->sessionid = FALSE; + } + else + dest->clientcert = NULL; + return TRUE; } @@ -166,6 +176,7 @@ void Curl_free_ssl_config(struct ssl_config_data* sslc) Curl_safefree(sslc->cipher_list); Curl_safefree(sslc->egdsocket); Curl_safefree(sslc->random_file); + Curl_safefree(sslc->clientcert); } @@ -181,7 +192,7 @@ void Curl_free_ssl_config(struct ssl_config_data* sslc) * */ -unsigned int Curl_rand(struct SessionHandle *data) +unsigned int Curl_rand(struct Curl_easy *data) { unsigned int r = 0; static unsigned int randseed; @@ -276,7 +287,7 @@ void Curl_ssl_cleanup(void) } } -static bool ssl_prefs_check(struct SessionHandle *data) +static bool ssl_prefs_check(struct Curl_easy *data) { /* check for CURLOPT_SSLVERSION invalid parameter value */ if((data->set.ssl.version < 0) @@ -330,6 +341,25 @@ Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex, } /* + * Lock shared SSL session data + */ +void Curl_ssl_sessionid_lock(struct connectdata *conn) +{ + if(SSLSESSION_SHARED(conn->data)) + Curl_share_lock(conn->data, + CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE); +} + +/* + * Unlock shared SSL session data + */ +void Curl_ssl_sessionid_unlock(struct connectdata *conn) +{ + if(SSLSESSION_SHARED(conn->data)) + Curl_share_unlock(conn->data, CURL_LOCK_DATA_SSL_SESSION); +} + +/* * Check if there's a session ID for the given connection in the cache, and if * there's one suitable, it is provided. Returns TRUE when no entry matched. */ @@ -338,22 +368,22 @@ bool Curl_ssl_getsessionid(struct connectdata *conn, size_t *idsize) /* set 0 if unknown */ { struct curl_ssl_session *check; - struct SessionHandle *data = conn->data; + struct Curl_easy *data = conn->data; size_t i; long *general_age; bool no_match = TRUE; *ssl_sessionid = NULL; + DEBUGASSERT(conn->ssl_config.sessionid); + if(!conn->ssl_config.sessionid) /* session ID re-use is disabled */ return TRUE; /* Lock if shared */ - if(SSLSESSION_SHARED(data)) { - Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE); + if(SSLSESSION_SHARED(data)) general_age = &data->share->sessionage; - } else general_age = &data->state.sessionage; @@ -363,6 +393,12 @@ bool Curl_ssl_getsessionid(struct connectdata *conn, /* not session ID means blank entry */ continue; if(Curl_raw_equal(conn->host.name, check->name) && + ((!conn->bits.conn_to_host && !check->conn_to_host) || + (conn->bits.conn_to_host && check->conn_to_host && + Curl_raw_equal(conn->conn_to_host.name, check->conn_to_host))) && + ((!conn->bits.conn_to_port && check->conn_to_port == -1) || + (conn->bits.conn_to_port && check->conn_to_port != -1 && + conn->conn_to_port == check->conn_to_port)) && (conn->remote_port == check->remote_port) && Curl_ssl_config_matches(&conn->ssl_config, &check->ssl_config)) { /* yes, we have a session ID! */ @@ -376,10 +412,6 @@ bool Curl_ssl_getsessionid(struct connectdata *conn, } } - /* Unlock */ - if(SSLSESSION_SHARED(data)) - Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION); - return no_match; } @@ -400,6 +432,7 @@ void Curl_ssl_kill_session(struct curl_ssl_session *session) Curl_free_ssl_config(&session->ssl_config); Curl_safefree(session->name); + Curl_safefree(session->conn_to_host); } } @@ -409,10 +442,7 @@ void Curl_ssl_kill_session(struct curl_ssl_session *session) void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid) { size_t i; - struct SessionHandle *data=conn->data; - - if(SSLSESSION_SHARED(data)) - Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE); + struct Curl_easy *data=conn->data; for(i = 0; i < data->set.ssl.max_ssl_sessions; i++) { struct curl_ssl_session *check = &data->state.session[i]; @@ -422,9 +452,6 @@ void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid) break; } } - - if(SSLSESSION_SHARED(data)) - Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION); } /* @@ -438,26 +465,40 @@ CURLcode Curl_ssl_addsessionid(struct connectdata *conn, size_t idsize) { size_t i; - struct SessionHandle *data=conn->data; /* the mother of all structs */ + struct Curl_easy *data=conn->data; /* the mother of all structs */ struct curl_ssl_session *store = &data->state.session[0]; long oldest_age=data->state.session[0].age; /* zero if unused */ char *clone_host; + char *clone_conn_to_host; + int conn_to_port; long *general_age; - /* Even though session ID re-use might be disabled, that only disables USING - IT. We still store it here in case the re-using is again enabled for an - upcoming transfer */ + DEBUGASSERT(conn->ssl_config.sessionid); clone_host = strdup(conn->host.name); if(!clone_host) return CURLE_OUT_OF_MEMORY; /* bail out */ + if(conn->bits.conn_to_host) { + clone_conn_to_host = strdup(conn->conn_to_host.name); + if(!clone_conn_to_host) { + free(clone_host); + return CURLE_OUT_OF_MEMORY; /* bail out */ + } + } + else + clone_conn_to_host = NULL; + + if(conn->bits.conn_to_port) + conn_to_port = conn->conn_to_port; + else + conn_to_port = -1; + /* Now we should add the session ID and the host name to the cache, (remove the oldest if necessary) */ /* If using shared SSL session, lock! */ if(SSLSESSION_SHARED(data)) { - Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE); general_age = &data->share->sessionage; } else { @@ -484,17 +525,16 @@ CURLcode Curl_ssl_addsessionid(struct connectdata *conn, store->age = *general_age; /* set current age */ /* free it if there's one already present */ free(store->name); + free(store->conn_to_host); store->name = clone_host; /* clone host name */ + store->conn_to_host = clone_conn_to_host; /* clone connect to host name */ + store->conn_to_port = conn_to_port; /* connect to port number */ store->remote_port = conn->remote_port; /* port number */ - - /* Unlock */ - if(SSLSESSION_SHARED(data)) - Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION); - if(!Curl_clone_ssl_config(&conn->ssl_config, &store->ssl_config)) { store->sessionid = NULL; /* let caller free sessionid */ free(clone_host); + free(clone_conn_to_host); return CURLE_OUT_OF_MEMORY; } @@ -502,7 +542,7 @@ CURLcode Curl_ssl_addsessionid(struct connectdata *conn, } -void Curl_ssl_close_all(struct SessionHandle *data) +void Curl_ssl_close_all(struct Curl_easy *data) { size_t i; /* kill the session ID cache if not shared */ @@ -540,20 +580,20 @@ CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex) /* Selects an SSL crypto engine */ -CURLcode Curl_ssl_set_engine(struct SessionHandle *data, const char *engine) +CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine) { return curlssl_set_engine(data, engine); } /* Selects the default SSL crypto engine */ -CURLcode Curl_ssl_set_engine_default(struct SessionHandle *data) +CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data) { return curlssl_set_engine_default(data); } /* Return list of OpenSSL crypto engine names. */ -struct curl_slist *Curl_ssl_engines_list(struct SessionHandle *data) +struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data) { return curlssl_engines_list(data); } @@ -562,7 +602,7 @@ struct curl_slist *Curl_ssl_engines_list(struct SessionHandle *data) * This sets up a session ID cache to the specified size. Make sure this code * is agnostic to what underlying SSL technology we use. */ -CURLcode Curl_ssl_initsessions(struct SessionHandle *data, size_t amount) +CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount) { struct curl_ssl_session *session; @@ -605,7 +645,7 @@ bool Curl_ssl_data_pending(const struct connectdata *conn, return curlssl_data_pending(conn, connindex); } -void Curl_ssl_free_certinfo(struct SessionHandle *data) +void Curl_ssl_free_certinfo(struct Curl_easy *data) { int i; struct curl_certinfo *ci = &data->info.certs; @@ -623,7 +663,7 @@ void Curl_ssl_free_certinfo(struct SessionHandle *data) } } -CURLcode Curl_ssl_init_certinfo(struct SessionHandle *data, int num) +CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num) { struct curl_certinfo *ci = &data->info.certs; struct curl_slist **table; @@ -645,7 +685,7 @@ CURLcode Curl_ssl_init_certinfo(struct SessionHandle *data, int num) /* * 'value' is NOT a zero terminated string */ -CURLcode Curl_ssl_push_certinfo_len(struct SessionHandle *data, +CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, int certnum, const char *label, const char *value, @@ -686,7 +726,7 @@ CURLcode Curl_ssl_push_certinfo_len(struct SessionHandle *data, * This is a convenience function for push_certinfo_len that takes a zero * terminated value. */ -CURLcode Curl_ssl_push_certinfo(struct SessionHandle *data, +CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data, int certnum, const char *label, const char *value) @@ -696,7 +736,7 @@ CURLcode Curl_ssl_push_certinfo(struct SessionHandle *data, return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen); } -int Curl_ssl_random(struct SessionHandle *data, +int Curl_ssl_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { @@ -765,7 +805,8 @@ static CURLcode pubkey_pem_to_der(const char *pem, * Generic pinned public key check. */ -CURLcode Curl_pin_peer_pubkey(const char *pinnedpubkey, +CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, + const char *pinnedpubkey, const unsigned char *pubkey, size_t pubkeylen) { FILE *fp; @@ -775,9 +816,10 @@ CURLcode Curl_pin_peer_pubkey(const char *pinnedpubkey, CURLcode pem_read; CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; #ifdef curlssl_sha256sum - size_t pinkeylen; - char *pinkeycopy, *begin_pos, *end_pos; - unsigned char *sha256sumdigest = NULL, *expectedsha256sumdigest = NULL; + CURLcode encode; + size_t encodedlen, pinkeylen; + char *encoded, *pinkeycopy, *begin_pos, *end_pos; + unsigned char *sha256sumdigest = NULL; #endif /* if a path wasn't specified, don't pin */ @@ -786,21 +828,29 @@ CURLcode Curl_pin_peer_pubkey(const char *pinnedpubkey, if(!pubkey || !pubkeylen) return result; -#ifdef curlssl_sha256sum /* only do this if pinnedpubkey starts with "sha256//", length 8 */ if(strncmp(pinnedpubkey, "sha256//", 8) == 0) { +#ifdef curlssl_sha256sum /* compute sha256sum of public key */ sha256sumdigest = malloc(SHA256_DIGEST_LENGTH); if(!sha256sumdigest) return CURLE_OUT_OF_MEMORY; curlssl_sha256sum(pubkey, pubkeylen, sha256sumdigest, SHA256_DIGEST_LENGTH); + encode = Curl_base64_encode(data, (char *)sha256sumdigest, + SHA256_DIGEST_LENGTH, &encoded, &encodedlen); + Curl_safefree(sha256sumdigest); + + if(encode) + return encode; + + infof(data, "\t public key hash: sha256//%s\n", encoded); /* it starts with sha256//, copy so we can modify it */ pinkeylen = strlen(pinnedpubkey) + 1; pinkeycopy = malloc(pinkeylen); if(!pinkeycopy) { - Curl_safefree(sha256sumdigest); + Curl_safefree(encoded); return CURLE_OUT_OF_MEMORY; } memcpy(pinkeycopy, pinnedpubkey, pinkeylen); @@ -815,20 +865,11 @@ CURLcode Curl_pin_peer_pubkey(const char *pinnedpubkey, if(end_pos) end_pos[0] = '\0'; - /* decode base64 pinnedpubkey, 8 is length of "sha256//" */ - pem_read = Curl_base64_decode(begin_pos + 8, - &expectedsha256sumdigest, &size); - /* if not valid base64, don't bother comparing or freeing */ - if(!pem_read) { - /* compare sha256 digests directly */ - if(SHA256_DIGEST_LENGTH == size && - !memcmp(sha256sumdigest, expectedsha256sumdigest, - SHA256_DIGEST_LENGTH)) { - result = CURLE_OK; - Curl_safefree(expectedsha256sumdigest); - break; - } - Curl_safefree(expectedsha256sumdigest); + /* compare base64 sha256 digests, 8 is the length of "sha256//" */ + if(encodedlen == strlen(begin_pos + 8) && + !memcmp(encoded, begin_pos + 8, encodedlen)) { + result = CURLE_OK; + break; } /* @@ -840,11 +881,14 @@ CURLcode Curl_pin_peer_pubkey(const char *pinnedpubkey, begin_pos = strstr(end_pos, "sha256//"); } } while(end_pos && begin_pos); - Curl_safefree(sha256sumdigest); + Curl_safefree(encoded); Curl_safefree(pinkeycopy); +#else + /* without sha256 support, this cannot match */ + (void)data; +#endif return result; } -#endif fp = fopen(pinnedpubkey, "rb"); if(!fp) diff --git a/Utilities/cmcurl/lib/vtls/vtls.h b/Utilities/cmcurl/lib/vtls/vtls.h index 2349e5b..a41ecc3 100644 --- a/Utilities/cmcurl/lib/vtls/vtls.h +++ b/Utilities/cmcurl/lib/vtls/vtls.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -32,6 +32,7 @@ #include "cyassl.h" /* CyaSSL versions */ #include "schannel.h" /* Schannel SSPI version */ #include "darwinssl.h" /* SecureTransport (Darwin) version */ +#include "mbedtls.h" /* mbedTLS versions */ #ifndef MAX_PINNED_PUBKEY_SIZE #define MAX_PINNED_PUBKEY_SIZE 1048576 /* 1MB */ @@ -45,7 +46,7 @@ #define SHA256_DIGEST_LENGTH 32 /* fixed size */ #endif -/* see http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-04 */ +/* see https://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-04 */ #define ALPN_HTTP_1_1_LENGTH 8 #define ALPN_HTTP_1_1 "http/1.1" @@ -55,7 +56,7 @@ bool Curl_clone_ssl_config(struct ssl_config_data* source, struct ssl_config_data* dest); void Curl_free_ssl_config(struct ssl_config_data* sslc); -unsigned int Curl_rand(struct SessionHandle *); +unsigned int Curl_rand(struct Curl_easy *); int Curl_ssl_backend(void); @@ -68,16 +69,16 @@ CURLcode Curl_ssl_connect_nonblocking(struct connectdata *conn, bool *done); /* tell the SSL stuff to close down all open information regarding connections (and thus session ID caching etc) */ -void Curl_ssl_close_all(struct SessionHandle *data); +void Curl_ssl_close_all(struct Curl_easy *data); void Curl_ssl_close(struct connectdata *conn, int sockindex); CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex); -CURLcode Curl_ssl_set_engine(struct SessionHandle *data, const char *engine); +CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine); /* Sets engine as default for all SSL operations */ -CURLcode Curl_ssl_set_engine_default(struct SessionHandle *data); -struct curl_slist *Curl_ssl_engines_list(struct SessionHandle *data); +CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data); +struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data); /* init the SSL session ID cache */ -CURLcode Curl_ssl_initsessions(struct SessionHandle *, size_t); +CURLcode Curl_ssl_initsessions(struct Curl_easy *, size_t); size_t Curl_ssl_version(char *buffer, size_t size); bool Curl_ssl_data_pending(const struct connectdata *conn, int connindex); @@ -85,39 +86,71 @@ int Curl_ssl_check_cxn(struct connectdata *conn); /* Certificate information list handling. */ -void Curl_ssl_free_certinfo(struct SessionHandle *data); -CURLcode Curl_ssl_init_certinfo(struct SessionHandle * data, int num); -CURLcode Curl_ssl_push_certinfo_len(struct SessionHandle * data, int certnum, +void Curl_ssl_free_certinfo(struct Curl_easy *data); +CURLcode Curl_ssl_init_certinfo(struct Curl_easy * data, int num); +CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy * data, int certnum, const char * label, const char * value, size_t valuelen); -CURLcode Curl_ssl_push_certinfo(struct SessionHandle * data, int certnum, +CURLcode Curl_ssl_push_certinfo(struct Curl_easy * data, int certnum, const char * label, const char * value); /* Functions to be used by SSL library adaptation functions */ -/* extract a session ID */ +/* Lock session cache mutex. + * Call this before calling other Curl_ssl_*session* functions + * Caller should unlock this mutex as soon as possible, as it may block + * other SSL connection from making progress. + * The purpose of explicitly locking SSL session cache data is to allow + * individual SSL engines to manage session lifetime in their specific way. + */ +void Curl_ssl_sessionid_lock(struct connectdata *conn); + +/* Unlock session cache mutex */ +void Curl_ssl_sessionid_unlock(struct connectdata *conn); + +/* extract a session ID + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * Caller must make sure that the ownership of returned sessionid object + * is properly taken (e.g. its refcount is incremented + * under sessionid mutex). + */ bool Curl_ssl_getsessionid(struct connectdata *conn, void **ssl_sessionid, - size_t *idsize) /* set 0 if unknown */; -/* add a new session ID */ + size_t *idsize); /* set 0 if unknown */ +/* add a new session ID + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * Caller must ensure that it has properly shared ownership of this sessionid + * object with cache (e.g. incrementing refcount on success) + */ CURLcode Curl_ssl_addsessionid(struct connectdata *conn, void *ssl_sessionid, size_t idsize); -/* Kill a single session ID entry in the cache */ +/* Kill a single session ID entry in the cache + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * This will call engine-specific curlssl_session_free function, which must + * take sessionid object ownership from sessionid cache + * (e.g. decrement refcount). + */ void Curl_ssl_kill_session(struct curl_ssl_session *session); -/* delete a session from the cache */ +/* delete a session from the cache + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * This will call engine-specific curlssl_session_free function, which must + * take sessionid object ownership from sessionid cache + * (e.g. decrement refcount). + */ void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid); /* get N random bytes into the buffer, return 0 if a find random is filled in */ -int Curl_ssl_random(struct SessionHandle *data, unsigned char *buffer, +int Curl_ssl_random(struct Curl_easy *data, unsigned char *buffer, size_t length); CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len); /* Check pinned public key. */ -CURLcode Curl_pin_peer_pubkey(const char *pinnedpubkey, +CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, + const char *pinnedpubkey, const unsigned char *pubkey, size_t pubkeylen); bool Curl_ssl_cert_status_request(void); diff --git a/Utilities/cmcurl/lib/warnless.c b/Utilities/cmcurl/lib/warnless.c index 8c130d3..0c4472e 100644 --- a/Utilities/cmcurl/lib/warnless.c +++ b/Utilities/cmcurl/lib/warnless.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -379,6 +379,63 @@ int curlx_sztosi(ssize_t sznum) } /* +** unsigned int to unsigned short +*/ + +unsigned short curlx_uitous(unsigned int uinum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uinum <= (unsigned int) CURL_MASK_USHORT); + return (unsigned short) (uinum & (unsigned int) CURL_MASK_USHORT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned int to unsigned char +*/ + +unsigned char curlx_uitouc(unsigned int uinum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uinum <= (unsigned int) CURL_MASK_UCHAR); + return (unsigned char) (uinum & (unsigned int) CURL_MASK_UCHAR); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* +** unsigned int to signed int +*/ + +int curlx_uitosi(unsigned int uinum) +{ +#ifdef __INTEL_COMPILER +# pragma warning(push) +# pragma warning(disable:810) /* conversion may lose significant bits */ +#endif + + DEBUGASSERT(uinum <= (unsigned int) CURL_MASK_SINT); + return (int) (uinum & (unsigned int) CURL_MASK_SINT); + +#ifdef __INTEL_COMPILER +# pragma warning(pop) +#endif +} + +/* ** signed int to unsigned size_t */ diff --git a/Utilities/cmcurl/lib/warnless.h b/Utilities/cmcurl/lib/warnless.h index ad77d3c..ab6d299 100644 --- a/Utilities/cmcurl/lib/warnless.h +++ b/Utilities/cmcurl/lib/warnless.h @@ -7,11 +7,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -52,6 +52,12 @@ size_t curlx_sotouz(curl_off_t sonum); int curlx_sztosi(ssize_t sznum); +unsigned short curlx_uitous(unsigned int uinum); + +unsigned char curlx_uitouc(unsigned int uinum); + +int curlx_uitosi(unsigned int uinum); + size_t curlx_sitouz(int sinum); #ifdef USE_WINSOCK diff --git a/Utilities/cmcurl/lib/wildcard.c b/Utilities/cmcurl/lib/wildcard.c index 6f55839..dbbe45f 100644 --- a/Utilities/cmcurl/lib/wildcard.c +++ b/Utilities/cmcurl/lib/wildcard.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -25,9 +25,9 @@ #include "wildcard.h" #include "llist.h" #include "fileinfo.h" +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" CURLcode Curl_wildcard_init(struct WildcardData *wc) diff --git a/Utilities/cmcurl/lib/wildcard.h b/Utilities/cmcurl/lib/wildcard.h index 16c80ec..7f61cd1 100644 --- a/Utilities/cmcurl/lib/wildcard.h +++ b/Utilities/cmcurl/lib/wildcard.h @@ -11,7 +11,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -53,6 +53,6 @@ struct WildcardData { CURLcode Curl_wildcard_init(struct WildcardData *wc); void Curl_wildcard_dtor(struct WildcardData *wc); -struct SessionHandle; +struct Curl_easy; #endif /* HEADER_CURL_WILDCARD_H */ diff --git a/Utilities/cmcurl/lib/x509asn1.c b/Utilities/cmcurl/lib/x509asn1.c index a3dfd64..e17bcd9 100644 --- a/Utilities/cmcurl/lib/x509asn1.c +++ b/Utilities/cmcurl/lib/x509asn1.c @@ -5,11 +5,11 @@ * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * - * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. + * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -23,7 +23,7 @@ #include "curl_setup.h" #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \ - defined(USE_CYASSL) + defined(USE_CYASSL) || defined(USE_SCHANNEL) #include <curl/curl.h> #include "urldata.h" @@ -34,9 +34,10 @@ #include "inet_pton.h" #include "curl_base64.h" #include "x509asn1.h" + +/* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" -/* The last #include file should be: */ #include "memdebug.h" @@ -783,7 +784,7 @@ static const char * dumpAlgo(curl_asn1Element * param, return OID2str(oid.beg, oid.end, TRUE); } -static void do_pubkey_field(struct SessionHandle * data, int certnum, +static void do_pubkey_field(struct Curl_easy * data, int certnum, const char * label, curl_asn1Element * elem) { const char * output; @@ -800,7 +801,7 @@ static void do_pubkey_field(struct SessionHandle * data, int certnum, } } -static void do_pubkey(struct SessionHandle * data, int certnum, +static void do_pubkey(struct Curl_easy * data, int certnum, const char * algo, curl_asn1Element * param, curl_asn1Element * pubkey) { @@ -870,7 +871,7 @@ CURLcode Curl_extract_certinfo(struct connectdata * conn, const char * end) { curl_X509certificate cert; - struct SessionHandle * data = conn->data; + struct Curl_easy * data = conn->data; curl_asn1Element param; const char * ccp; char * cp1; @@ -1024,7 +1025,7 @@ CURLcode Curl_extract_certinfo(struct connectdata * conn, return CURLE_OK; } -#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL */ +#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL or USE_SCHANNEL */ #if defined(USE_GSKIT) @@ -1055,13 +1056,12 @@ static const char * checkOID(const char * beg, const char * end, CURLcode Curl_verifyhost(struct connectdata * conn, const char * beg, const char * end) { - struct SessionHandle * data = conn->data; + struct Curl_easy * data = conn->data; curl_X509certificate cert; curl_asn1Element dn; curl_asn1Element elem; curl_asn1Element ext; curl_asn1Element name; - int i; const char * p; const char * q; char * dnsname; @@ -1110,16 +1110,13 @@ CURLcode Curl_verifyhost(struct connectdata * conn, q = Curl_getASN1Element(&name, q, elem.end); switch (name.tag) { case 2: /* DNS name. */ - i = 0; len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING, name.beg, name.end); - if(len > 0) - if(strlen(dnsname) == (size_t) len) - i = Curl_cert_hostcheck((const char *) dnsname, conn->host.name); + if(len > 0 && (size_t)len == strlen(dnsname)) + matched = Curl_cert_hostcheck(dnsname, conn->host.name); + else + matched = 0; free(dnsname); - if(!i) - return CURLE_PEER_FAILED_VERIFICATION; - matched = i; break; case 7: /* IP address. */ diff --git a/Utilities/cmcurl/lib/x509asn1.h b/Utilities/cmcurl/lib/x509asn1.h index eb23e50..0f2b930 100644 --- a/Utilities/cmcurl/lib/x509asn1.h +++ b/Utilities/cmcurl/lib/x509asn1.h @@ -12,7 +12,7 @@ * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. + * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is @@ -26,7 +26,7 @@ #include "curl_setup.h" #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \ - defined(USE_CYASSL) + defined(USE_CYASSL) || defined(USE_SCHANNEL) #include "urldata.h" @@ -128,5 +128,5 @@ CURLcode Curl_extract_certinfo(struct connectdata * conn, int certnum, CURLcode Curl_verifyhost(struct connectdata * conn, const char * beg, const char * end); -#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL */ +#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL or USE_SCHANNEL */ #endif /* HEADER_CURL_X509ASN1_H */ 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@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; @@ -60,10 +60,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="" @@ -88,7 +90,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 +215,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}`" @@ -362,7 +365,6 @@ KWSYS_CXX_SOURCES="\ SystemTools" KWSYS_FILES="\ - auto_ptr.hxx \ Directory.hxx \ Encoding.h \ Encoding.hxx \ @@ -422,6 +424,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 +511,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 +632,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"` ;; @@ -1177,6 +1183,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 +1226,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 +1279,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 +1393,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" |