diff options
333 files changed, 6123 insertions, 2351 deletions
diff --git a/Auxiliary/bash-completion/cmake b/Auxiliary/bash-completion/cmake index 8c0c5e8..638b1c4 100644 --- a/Auxiliary/bash-completion/cmake +++ b/Auxiliary/bash-completion/cmake @@ -116,6 +116,9 @@ _cmake() 2>/dev/null )' -- "$quoted" ) ) return ;; + --loglevel) + COMPREPLY=( $(compgen -W 'error warning notice status verbose debug trace' -- $cur ) ) + ;; --help-command) COMPREPLY=( $( compgen -W '$( cmake --help-command-list 2>/dev/null| grep -v "^cmake version " )' -- "$cur" ) ) diff --git a/Help/command/add_definitions.rst b/Help/command/add_definitions.rst index 39a43f4..d06b01c 100644 --- a/Help/command/add_definitions.rst +++ b/Help/command/add_definitions.rst @@ -20,7 +20,7 @@ preprocessor definitions. * Use :command:`include_directories` to add include directories. * Use :command:`add_compile_options` to add other options. -Flags beginning in -D or /D that look like preprocessor definitions are +Flags beginning in ``-D`` or ``/D`` that look like preprocessor definitions are automatically added to the :prop_dir:`COMPILE_DEFINITIONS` directory property for the current directory. Definitions with non-trivial values may be left in the set of flags instead of being converted for reasons of diff --git a/Help/command/cmake_policy.rst b/Help/command/cmake_policy.rst index a80f982..4bc7807 100644 --- a/Help/command/cmake_policy.rst +++ b/Help/command/cmake_policy.rst @@ -80,7 +80,7 @@ CMake Policy Stack ^^^^^^^^^^^^^^^^^^ CMake keeps policy settings on a stack, so changes made by the -cmake_policy command affect only the top of the stack. A new entry on +``cmake_policy`` command affect only the top of the stack. A new entry on the policy stack is managed automatically for each subdirectory to protect its parents and siblings. CMake also manages a new entry for scripts loaded by :command:`include` and :command:`find_package` commands diff --git a/Help/command/execute_process.rst b/Help/command/execute_process.rst index 2d71352..e6ad037 100644 --- a/Help/command/execute_process.rst +++ b/Help/command/execute_process.rst @@ -18,6 +18,7 @@ Execute one or more child processes. [ERROR_FILE <file>] [OUTPUT_QUIET] [ERROR_QUIET] + [COMMAND_ECHO <where>] [OUTPUT_STRIP_TRAILING_WHITESPACE] [ERROR_STRIP_TRAILING_WHITESPACE] [ENCODING <name>]) @@ -77,6 +78,10 @@ Options: ``OUTPUT_QUIET``, ``ERROR_QUIET`` The standard output or standard error results will be quietly ignored. +``COMMAND_ECHO <where>`` + The command being run will be echo'ed to ``<where>`` with ``<where>`` + being set to ``STDERR``|``STDOUT``|``NONE``. + ``ENCODING <name>`` On Windows, the encoding that is used to decode output from the process. Ignored on other platforms. diff --git a/Help/command/include_external_msproject.rst b/Help/command/include_external_msproject.rst index 88bb2c6..540a13a 100644 --- a/Help/command/include_external_msproject.rst +++ b/Help/command/include_external_msproject.rst @@ -17,7 +17,7 @@ named ``[projectname]``. This can be used in the :command:`add_dependencies` command to make things depend on the external project. ``TYPE``, ``GUID`` and ``PLATFORM`` are optional parameters that allow one to -specify the type of project, id (GUID) of the project and the name of +specify the type of project, id (``GUID``) of the project and the name of the target platform. This is useful for projects requiring values other than the default (e.g. WIX projects). diff --git a/Help/command/message.rst b/Help/command/message.rst index 2b4b1aa..3f9216a 100644 --- a/Help/command/message.rst +++ b/Help/command/message.rst @@ -9,24 +9,56 @@ Display a message to the user. The optional ``<mode>`` keyword determines the type of message: -:: - - (none) = Important information - STATUS = Incidental information - WARNING = CMake Warning, continue processing - AUTHOR_WARNING = CMake Warning (dev), continue processing - SEND_ERROR = CMake Error, continue processing, - but skip generation - FATAL_ERROR = CMake Error, stop processing and generation - DEPRECATION = CMake Deprecation Error or Warning if variable - CMAKE_ERROR_DEPRECATED or CMAKE_WARN_DEPRECATED - is enabled, respectively, else no message. - -The CMake command-line tool displays STATUS messages on stdout and all -other message types on stderr. The CMake GUI displays all messages in -its log area. The interactive dialogs (ccmake and CMakeSetup) show -STATUS messages one at a time on a status line and other messages in -interactive pop-up boxes. +``FATAL_ERROR`` + CMake Error, stop processing and generation. + +``SEND_ERROR`` + CMake Error, continue processing, but skip generation. + +``WARNING`` + CMake Warning, continue processing. + +``AUTHOR_WARNING`` + CMake Warning (dev), continue processing. + +``DEPRECATION`` + CMake Deprecation Error or Warning if variable + :variable:`CMAKE_ERROR_DEPRECATED` or :variable:`CMAKE_WARN_DEPRECATED` + is enabled, respectively, else no message. + +(none) or ``NOTICE`` + Important message printed to stderr to attract user's attention. + +``STATUS`` + The main interesting messages that project users might be interested in. + Ideally these should be concise, no more than a single line, but still + informative. + +``VERBOSE`` + Detailed informational messages intended for project users. These messages + should provide additional details that won't be of interest in most cases, + but which may be useful to those building the project when they want deeper + insight into what's happening. + +``DEBUG`` + Detailed informational messages intended for developers working on the + project itself as opposed to users who just want to build it. These messages + will not typically be of interest to other users building the project and + will often be closely related to internal implementation details. + +``TRACE`` + Fine-grained messages with very low-level implementation details. Messages + using this log level would normally only be temporary and would expect to be + removed before releasing the project, packaging up the files, etc. + +The CMake command-line tool displays ``STATUS`` to ``TRACE`` messages on stdout +with the message preceded by two hyphens and a space. All other message types +are sent to stderr and are not prefixed with hyphens. The CMake GUI displays +all messages in its log area. The interactive dialogs (:manual:`ccmake(1)` +and :manual:`cmake-gui(1)`) show ``STATUS`` to ``TRACE`` messages one at a +time on a status line and other messages in interactive pop-up boxes. +The ``--loglevel`` command-line option to each of these tools can be used to +control which messages will be shown. CMake Warning and Error message text displays using a simple markup language. Non-indented text is formatted in line-wrapped paragraphs diff --git a/Help/command/set_property.rst b/Help/command/set_property.rst index 2624b4b..ec08c8f 100644 --- a/Help/command/set_property.rst +++ b/Help/command/set_property.rst @@ -35,7 +35,7 @@ It must be one of the following: ``SOURCE`` Scope may name zero or more source files. Note that source file properties are visible only to targets added in the same - directory (CMakeLists.txt). + directory (``CMakeLists.txt``). See also the :command:`set_source_files_properties` command. ``INSTALL`` @@ -48,7 +48,7 @@ It must be one of the following: Path components have to be separated by forward slashes, must be normalized and are case sensitive. - To reference the installation prefix itself with a relative path use ".". + To reference the installation prefix itself with a relative path use ``.``. Currently installed file properties are only defined for the WIX generator where the given paths are relative diff --git a/Help/command/set_source_files_properties.rst b/Help/command/set_source_files_properties.rst index 91f995c..ab95d70 100644 --- a/Help/command/set_source_files_properties.rst +++ b/Help/command/set_source_files_properties.rst @@ -16,4 +16,4 @@ See also the :command:`set_property(SOURCE)` command. See :ref:`Source File Properties` for the list of properties known to CMake. Source file properties are visible only to targets added -in the same directory (CMakeLists.txt). +in the same directory (``CMakeLists.txt``). diff --git a/Help/command/string.rst b/Help/command/string.rst index 893fb43..2e89d7b 100644 --- a/Help/command/string.rst +++ b/Help/command/string.rst @@ -28,6 +28,7 @@ Synopsis string(`SUBSTRING`_ <string> <begin> <length> <out-var>) string(`STRIP`_ <string> <out-var>) string(`GENEX_STRIP`_ <string> <out-var>) + string(`REPEAT`_ <string> <count> <out-var>) `Comparison`_ string(`COMPARE`_ <op> <string1> <string2> <out-var>) @@ -269,6 +270,14 @@ trailing spaces removed. Strip any :manual:`generator expressions <cmake-generator-expressions(7)>` from the ``input string`` and store the result in the ``output variable``. +.. _REPEAT: + +.. code-block:: cmake + + string(REPEAT <input string> <count> <output variable>) + +Produce the output string as repetion of ``input string`` ``count`` times. + Comparison ^^^^^^^^^^ diff --git a/Help/command/try_compile.rst b/Help/command/try_compile.rst index ca8fc77..0bc2ca3 100644 --- a/Help/command/try_compile.rst +++ b/Help/command/try_compile.rst @@ -135,6 +135,7 @@ default values: * :variable:`CMAKE_ENABLE_EXPORTS` * :variable:`CMAKE_LINK_SEARCH_START_STATIC` * :variable:`CMAKE_LINK_SEARCH_END_STATIC` +* :variable:`CMAKE_MSVC_RUNTIME_LIBRARY` * :variable:`CMAKE_POSITION_INDEPENDENT_CODE` If :policy:`CMP0056` is set to ``NEW``, then diff --git a/Help/generator/Visual Studio 16 2019.rst b/Help/generator/Visual Studio 16 2019.rst index b456554..4aec7f7 100644 --- a/Help/generator/Visual Studio 16 2019.rst +++ b/Help/generator/Visual Studio 16 2019.rst @@ -28,7 +28,8 @@ by default. Platform Selection ^^^^^^^^^^^^^^^^^^ -The default target platform name (architecture) is that of the host. +The default target platform name (architecture) is that of the host +and is provided in the :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable. The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps via the :manual:`cmake(1)` ``-A`` option, to specify a target platform diff --git a/Help/manual/cmake-generator-expressions.7.rst b/Help/manual/cmake-generator-expressions.7.rst index e9b3f4c..3dc3221 100644 --- a/Help/manual/cmake-generator-expressions.7.rst +++ b/Help/manual/cmake-generator-expressions.7.rst @@ -387,14 +387,25 @@ Target-Dependent Queries ``$<TARGET_NAME_IF_EXISTS:tgt>`` Expands to the ``tgt`` if the given target exists, an empty string otherwise. -``$<TARGET_OUTPUT_NAME:tgt>`` +``$<TARGET_FILE:tgt>`` + Full path to main file (.exe, .so.1.2, .a) where ``tgt`` is the name of a + target. +``$<TARGET_FILE_BASE_NAME:tgt>`` Base name of main file where ``tgt`` is the name of a target. + The base name corresponds to the target file name (see + ``$<TARGET_FILE_NAME:tgt>``) without prefix and suffix. For example, if + target file name is ``libbase.so``, the base name is ``base``. + + See also the :prop_tgt:`OUTPUT_NAME`, :prop_tgt:`ARCHIVE_OUTPUT_NAME`, + :prop_tgt:`LIBRARY_OUTPUT_NAME` and :prop_tgt:`RUNTIME_OUTPUT_NAME` + target properties and their configuration specific variants + :prop_tgt:`OUTPUT_NAME_<CONFIG>`, :prop_tgt:`ARCHIVE_OUTPUT_NAME_<CONFIG>`, + :prop_tgt:`LIBRARY_OUTPUT_NAME_<CONFIG>` and + :prop_tgt:`RUNTIME_OUTPUT_NAME_<CONFIG>`. + Note that ``tgt`` is not added as a dependency of the target this expression is evaluated on. -``$<TARGET_FILE:tgt>`` - Full path to main file (.exe, .so.1.2, .a) where ``tgt`` is the name of a - target. ``$<TARGET_FILE_PREFIX:tgt>`` Prefix of main file where ``tgt`` is the name of a target. @@ -409,13 +420,23 @@ Target-Dependent Queries Name of main file (.exe, .so.1.2, .a). ``$<TARGET_FILE_DIR:tgt>`` Directory of main file (.exe, .so.1.2, .a). -``$<TARGET_LINKER_OUTPUT_NAME:tgt>`` +``$<TARGET_LINKER_FILE:tgt>`` + File used to link (.a, .lib, .so) where ``tgt`` is the name of a target. +``$<TARGET_LINKER_FILE_BASE_NAME:tgt>`` Base name of file used to link where ``tgt`` is the name of a target. + The base name corresponds to the target linker file name (see + ``$<TARGET_LINKER_FILE_NAME:tgt>``) without prefix and suffix. For example, + if target file name is ``libbase.a``, the base name is ``base``. + + See also the :prop_tgt:`OUTPUT_NAME`, :prop_tgt:`ARCHIVE_OUTPUT_NAME`, + and :prop_tgt:`LIBRARY_OUTPUT_NAME` target properties and their configuration + specific variants :prop_tgt:`OUTPUT_NAME_<CONFIG>`, + :prop_tgt:`ARCHIVE_OUTPUT_NAME_<CONFIG>` and + :prop_tgt:`LIBRARY_OUTPUT_NAME_<CONFIG>`. + Note that ``tgt`` is not added as a dependency of the target this expression is evaluated on. -``$<TARGET_LINKER_FILE:tgt>`` - File used to link (.a, .lib, .so) where ``tgt`` is the name of a target. ``$<TARGET_LINKER_FILE_PREFIX:tgt>`` Prefix of file used to link where ``tgt`` is the name of a target. @@ -436,22 +457,26 @@ Target-Dependent Queries Name of file with soname (.so.3). ``$<TARGET_SONAME_FILE_DIR:tgt>`` Directory of with soname (.so.3). -``$<TARGET_PDB_OUTPUT_NAME:tgt>`` +``$<TARGET_PDB_FILE:tgt>`` + Full path to the linker generated program database file (.pdb) + where ``tgt`` is the name of a target. + + See also the :prop_tgt:`PDB_NAME` and :prop_tgt:`PDB_OUTPUT_DIRECTORY` + target properties and their configuration specific variants + :prop_tgt:`PDB_NAME_<CONFIG>` and :prop_tgt:`PDB_OUTPUT_DIRECTORY_<CONFIG>`. +``$<TARGET_PDB_FILE_BASE_NAME:tgt>`` Base name of the linker generated program database file (.pdb) where ``tgt`` is the name of a target. + The base name corresponds to the target PDB file name (see + ``$<TARGET_PDB_FILE_NAME:tgt>``) without prefix and suffix. For example, + if target file name is ``base.pdb``, the base name is ``base``. + See also the :prop_tgt:`PDB_NAME` target property and its configuration specific variant :prop_tgt:`PDB_NAME_<CONFIG>`. Note that ``tgt`` is not added as a dependency of the target this expression is evaluated on. -``$<TARGET_PDB_FILE:tgt>`` - Full path to the linker generated program database file (.pdb) - where ``tgt`` is the name of a target. - - See also the :prop_tgt:`PDB_NAME` and :prop_tgt:`PDB_OUTPUT_DIRECTORY` - target properties and their configuration specific variants - :prop_tgt:`PDB_NAME_<CONFIG>` and :prop_tgt:`PDB_OUTPUT_DIRECTORY_<CONFIG>`. ``$<TARGET_PDB_FILE_NAME:tgt>`` Name of the linker generated program database file (.pdb). ``$<TARGET_PDB_FILE_DIR:tgt>`` @@ -505,8 +530,7 @@ Output-Related Expressions Content of ``...`` converted to a C identifier. The conversion follows the same behavior as :command:`string(MAKE_C_IDENTIFIER)`. ``$<TARGET_OBJECTS:objLib>`` - List of objects resulting from build of ``objLib``. ``objLib`` must be an - object of type ``OBJECT_LIBRARY``. + List of objects resulting from build of ``objLib``. ``$<SHELL_PATH:...>`` Content of ``...`` converted to shell path style. For example, slashes are converted to backslashes in Windows shells and drive letters are converted diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst index e89ea3da..8fcd386 100644 --- a/Help/manual/cmake-policies.7.rst +++ b/Help/manual/cmake-policies.7.rst @@ -57,6 +57,8 @@ Policies Introduced by CMake 3.15 .. toctree:: :maxdepth: 1 + CMP0092: MSVC warning flags are not in CMAKE_{C,CXX}_FLAGS by default. </policy/CMP0092> + CMP0091: MSVC runtime library flags are selected by an abstraction. </policy/CMP0091> CMP0090: export(PACKAGE) does not populate package registry by default. </policy/CMP0090> CMP0089: Compiler id for IBM Clang-based XL compilers is now XLClang. </policy/CMP0089> diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst index 4d4b9ff..c11496c 100644 --- a/Help/manual/cmake-properties.7.rst +++ b/Help/manual/cmake-properties.7.rst @@ -280,6 +280,7 @@ Properties on Targets /prop_tgt/MACOSX_RPATH /prop_tgt/MANUALLY_ADDED_DEPENDENCIES /prop_tgt/MAP_IMPORTED_CONFIG_CONFIG + /prop_tgt/MSVC_RUNTIME_LIBRARY /prop_tgt/NAME /prop_tgt/NO_SONAME /prop_tgt/NO_SYSTEM_FROM_IMPORTED @@ -335,6 +336,7 @@ Properties on Targets /prop_tgt/VS_KEYWORD /prop_tgt/VS_MOBILE_EXTENSIONS_VERSION /prop_tgt/VS_NO_SOLUTION_DEPLOY + /prop_tgt/VS_PROJECT_IMPORT /prop_tgt/VS_SCC_AUXPATH /prop_tgt/VS_SCC_LOCALPATH /prop_tgt/VS_SCC_PROJECTNAME diff --git a/Help/manual/cmake-server.7.rst b/Help/manual/cmake-server.7.rst index 25d364c..8f10b9f 100644 --- a/Help/manual/cmake-server.7.rst +++ b/Help/manual/cmake-server.7.rst @@ -7,6 +7,11 @@ cmake-server(7) .. contents:: +.. deprecated:: 3.15 + + This will be removed from a future version of CMake. + Clients should use the :manual:`cmake-file-api(7)` instead. + Introduction ============ diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst index 18dd9d7..6d93ae9 100644 --- a/Help/manual/cmake-variables.7.rst +++ b/Help/manual/cmake-variables.7.rst @@ -105,6 +105,7 @@ Variables that Provide Information /variable/CMAKE_VS_MSBUILD_COMMAND /variable/CMAKE_VS_NsightTegra_VERSION /variable/CMAKE_VS_PLATFORM_NAME + /variable/CMAKE_VS_PLATFORM_NAME_DEFAULT /variable/CMAKE_VS_PLATFORM_TOOLSET /variable/CMAKE_VS_PLATFORM_TOOLSET_CUDA /variable/CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE @@ -158,6 +159,7 @@ Variables that Change Behavior /variable/CMAKE_ECLIPSE_VERSION /variable/CMAKE_ERROR_DEPRECATED /variable/CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION + /variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO /variable/CMAKE_EXPORT_COMPILE_COMMANDS /variable/CMAKE_EXPORT_PACKAGE_REGISTRY /variable/CMAKE_EXPORT_NO_PACKAGE_REGISTRY @@ -386,6 +388,7 @@ Variables that Control the Build /variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT /variable/CMAKE_MODULE_LINKER_FLAGS_INIT /variable/CMAKE_MSVCIDE_RUN_PATH + /variable/CMAKE_MSVC_RUNTIME_LIBRARY /variable/CMAKE_NINJA_OUTPUT_PATH_PREFIX /variable/CMAKE_NO_BUILTIN_CHRPATH /variable/CMAKE_NO_SYSTEM_FROM_IMPORTED diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst index 5b88694..3e1680c 100644 --- a/Help/manual/cmake.1.rst +++ b/Help/manual/cmake.1.rst @@ -200,6 +200,12 @@ Options from the top of a binary tree for a CMake project it will dump additional information such as the cache, log files etc. +``--loglevel=<error|warning|notice|status|verbose|debug|trace>`` + Set the log level. + + The :command:`message` command will only output messages of the specified + log level or higher. The default log level is ``status``. + ``--debug-trycompile`` Do not delete the :command:`try_compile` build tree. Only useful on one :command:`try_compile` at a time. diff --git a/Help/policy/CMP0091.rst b/Help/policy/CMP0091.rst new file mode 100644 index 0000000..5b7c4e3 --- /dev/null +++ b/Help/policy/CMP0091.rst @@ -0,0 +1,47 @@ +CMP0091 +------- + +MSVC runtime library flags are selected by an abstraction. + +Compilers targeting the MSVC ABI have flags to select the MSVC runtime library. +Runtime library selection typically varies with build configuration because +there is a separate runtime library for Debug builds. + +In CMake 3.14 and below, MSVC runtime library selection flags are added to +the default :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` cache entries by CMake +automatically. This allows users to edit their cache entries to adjust the +flags. However, the presence of such default flags is problematic for +projects that want to choose a different runtime library programmatically. +In particular, it requires string editing of the +:variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` variables with knowledge of the +CMake builtin defaults so they can be replaced. + +CMake 3.15 and above prefer to leave the MSVC runtime library selection flags +out of the default :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` values and instead +offer a first-class abstraction. The :variable:`CMAKE_MSVC_RUNTIME_LIBRARY` +variable and :prop_tgt:`MSVC_RUNTIME_LIBRARY` target property may be set to +select the MSVC runtime library. + +This policy provides compatibility with projects that have not been updated +to be aware of the abstraction. The policy setting takes effect as of the +first :command:`project` or :command:`enable_language` command that enables +a language whose compiler targets the MSVC ABI. + +.. note:: + + Once the policy has taken effect at the top of a project, that choice + must be used throughout the tree. In projects that have nested projects + in subdirectories, be sure to convert everything together. + +The ``OLD`` behavior for this policy is to place MSVC runtime library +flags in the default :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` cache +entries and ignore the :variable:`CMAKE_MSVC_RUNTIME_LIBRARY` abstraction. +The ``NEW`` behavior for this policy is to *not* place MSVC runtime +library flags in the default cache entries and use the abstraction instead. + +This policy was introduced in CMake version 3.15. Use the +:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly. +Unlike many policies, CMake version |release| does *not* warn +when this policy is not set and simply uses ``OLD`` behavior. + +.. include:: DEPRECATED.txt diff --git a/Help/policy/CMP0092.rst b/Help/policy/CMP0092.rst new file mode 100644 index 0000000..8d3a288 --- /dev/null +++ b/Help/policy/CMP0092.rst @@ -0,0 +1,38 @@ +CMP0092 +------- + +MSVC warning flags are not in :variable:`CMAKE_<LANG>_FLAGS` by default. + +When using MSVC-like compilers in CMake 3.14 and below, warning flags +like ``/W3`` are added to :variable:`CMAKE_<LANG>_FLAGS` by default. +This is problematic for projects that want to choose a different warning +level programmatically. In particular, it requires string editing of the +:variable:`CMAKE_<LANG>_FLAGS` variables with knowledge of the +CMake builtin defaults so they can be replaced. + +CMake 3.15 and above prefer to leave out warning flags from the value of +:variable:`CMAKE_<LANG>_FLAGS` by default. + +This policy provides compatibility with projects that have not been updated +to expect the lack of warning flags. The policy setting takes effect as of +the first :command:`project` or :command:`enable_language` command that +initializes :variable:`CMAKE_<LANG>_FLAGS` for a given lanuage ``<LANG>``. + +.. note:: + + Once the policy has taken effect at the top of a project for a given + language, that choice must be used throughout the tree for that language. + In projects that have nested projects in subdirectories, be sure to + convert everything together. + +The ``OLD`` behavior for this policy is to place MSVC warning flags in the +default :variable:`CMAKE_<LANG>_FLAGS` cache entries. The ``NEW`` behavior +for this policy is to *not* place MSVC warning flags in the default cache +entries. + +This policy was introduced in CMake version 3.15. Use the +:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly. +Unlike many policies, CMake version |release| does *not* warn +when this policy is not set and simply uses ``OLD`` behavior. + +.. include:: DEPRECATED.txt diff --git a/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt new file mode 100644 index 0000000..6c61341 --- /dev/null +++ b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt @@ -0,0 +1,20 @@ +``MultiThreaded`` + Compile with ``-MT`` or equivalent flag(s) to use a multi-threaded + statically-linked runtime library. +``MultiThreadedDLL`` + Compile with ``-MD`` or equivalent flag(s) to use a multi-threaded + dynamically-linked runtime library. +``MultiThreadedDebug`` + Compile with ``-MTd`` or equivalent flag(s) to use a multi-threaded + statically-linked runtime library. +``MultiThreadedDebugDLL`` + Compile with ``-MDd`` or equivalent flag(s) to use a multi-threaded + dynamically-linked runtime library. + +The value is ignored on non-MSVC compilers but an unsupported value will +be rejected as an error when using a compiler targeting the MSVC ABI. + +The value may also be the empty string (``""``) in which case no runtime +library selection flag will be added explicitly by CMake. Note that with +:ref:`Visual Studio Generators` the native build system may choose to +add its own default runtime library selection flag. diff --git a/Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst new file mode 100644 index 0000000..1e3f5e9 --- /dev/null +++ b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst @@ -0,0 +1,26 @@ +MSVC_RUNTIME_LIBRARY +-------------------- + +Select the MSVC runtime library for use by compilers targeting the MSVC ABI. + +The allowed values are: + +.. include:: MSVC_RUNTIME_LIBRARY-VALUES.txt + +Use :manual:`generator expressions <cmake-generator-expressions(7)>` to +support per-configuration specification. For example, the code: + +.. code-block:: cmake + + add_executable(foo foo.c) + set_property(TARGET foo PROPERTY + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + +selects for the target ``foo`` a multi-threaded statically-linked runtime +library with or without debug information depending on the configuration. + +.. note:: + + This property has effect only when policy :policy:`CMP0091` is set to ``NEW`` + prior to the first :command:`project` or :command:`enable_language` command + that enables a language using a compiler targeting the MSVC ABI. diff --git a/Help/prop_tgt/VS_PROJECT_IMPORT.rst b/Help/prop_tgt/VS_PROJECT_IMPORT.rst new file mode 100644 index 0000000..569c8ea --- /dev/null +++ b/Help/prop_tgt/VS_PROJECT_IMPORT.rst @@ -0,0 +1,8 @@ +VS_PROJECT_IMPORT +----------------- + +Visual Studio managed project imports + +Adds to a generated Visual Studio project one or more semicolon-delimited paths +to .props files needed when building projects from some NuGet packages. +For example, ``my_packages_path/MyPackage.1.0.0/build/MyPackage.props``. diff --git a/Help/release/3.14.rst b/Help/release/3.14.rst index f2a91c6..c208304 100644 --- a/Help/release/3.14.rst +++ b/Help/release/3.14.rst @@ -137,6 +137,10 @@ Variables relocatable and reproducible builds that are invariant of the build directory. +* A :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable was added for + :ref:`Visual Studio Generators` to report their default platform used + when :variable:`CMAKE_GENERATOR_PLATFORM` is not set explicitly. + Properties ---------- @@ -391,3 +395,10 @@ Changes made since CMake 3.14.0 include the following. our conventions. 3.14.1 revises the module to use ``Fontconfig_*`` variable names. This is incompatible with 3.14.0 but since the module is new in the 3.14 series usage should not yet be widespread. + +3.14.3 +------ + +* The :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable was added + to help toolchain files work with the :generator:`Visual Studio 16 2019` + generator where the default platform now depends on the host platform. diff --git a/Help/release/dev/add-execute_process-command-echo.rst b/Help/release/dev/add-execute_process-command-echo.rst new file mode 100644 index 0000000..a44e40e --- /dev/null +++ b/Help/release/dev/add-execute_process-command-echo.rst @@ -0,0 +1,6 @@ +add-execute_process-command-echo +-------------------------------- + +* The :command:`execute_process` command gained a `COMMAND_ECHO` option + and supporting :variable:`CMAKE_EXECUTE_PROCESS_COMMAND_ECHO` variable + to enable echoing of the command-line string before execution. diff --git a/Help/release/dev/genex-TARGET_FILE_BASE_NAME.rst b/Help/release/dev/genex-TARGET_FILE_BASE_NAME.rst new file mode 100644 index 0000000..d8b2b21 --- /dev/null +++ b/Help/release/dev/genex-TARGET_FILE_BASE_NAME.rst @@ -0,0 +1,7 @@ +genex-TARGET_FILE_BASE_NAME +--------------------------- + +* New ``$<TARGET_FILE_BASE_NAME:...>``, ``$<TARGET_LINKER_FILE_BASE_NAME:...>`` + and ``$<TARGET_PDB_FILE_BASE_NAME:...>`` + :manual:`generator expressions <cmake-generator-expressions(7)>` have been + added to retrieve the base name of various artifacts. diff --git a/Help/release/dev/genex-TARGET_OUTPUT_NAME.rst b/Help/release/dev/genex-TARGET_OUTPUT_NAME.rst deleted file mode 100644 index e3ffe57..0000000 --- a/Help/release/dev/genex-TARGET_OUTPUT_NAME.rst +++ /dev/null @@ -1,7 +0,0 @@ -genex-TARGET_OUTPUT_NAME ------------------------- - -* New ``$<TARGET_OUTPUT_NAME:...>``, ``$<TARGET_LINKER_OUTPUT_NAME:...>`` and - ``$<TARGET_PDB_OUTPUT_NAME:...>`` - :manual:`generator expressions <cmake-generator-expressions(7)>` have been - added to retrieve the base name of various artifacts. diff --git a/Help/release/dev/ghs-custom-commands.rst b/Help/release/dev/ghs-custom-commands.rst new file mode 100644 index 0000000..a29ef88 --- /dev/null +++ b/Help/release/dev/ghs-custom-commands.rst @@ -0,0 +1,5 @@ +ghs_custom_commands +------------------- + +* The :generator:`Green Hills MULTI` generator now supports + :command:`add_custom_command` and :command:`add_custom_target` diff --git a/Help/release/dev/msvc-runtime-library.rst b/Help/release/dev/msvc-runtime-library.rst new file mode 100644 index 0000000..4dddac2 --- /dev/null +++ b/Help/release/dev/msvc-runtime-library.rst @@ -0,0 +1,7 @@ +msvc-runtime-library +-------------------- + +* The :variable:`CMAKE_MSVC_RUNTIME_LIBRARY` variable and + :prop_tgt:`MSVC_RUNTIME_LIBRARY` target property were introduced to + select the runtime library used by compilers targeting the MSVC ABI. + See policy :policy:`CMP0091`. diff --git a/Help/release/dev/msvc-warning-flags.rst b/Help/release/dev/msvc-warning-flags.rst new file mode 100644 index 0000000..b89d6fa --- /dev/null +++ b/Help/release/dev/msvc-warning-flags.rst @@ -0,0 +1,6 @@ +msvc-warning-flags +------------------ + +* With MSVC-like compilers the value of :variable:`CMAKE_<LANG>_FLAGS` + no longer contains warning flags like ``/W3`` by default. + See policy :policy:`CMP0092`. diff --git a/Help/release/dev/new-message-types-and-logging.rst b/Help/release/dev/new-message-types-and-logging.rst new file mode 100644 index 0000000..cd470bb --- /dev/null +++ b/Help/release/dev/new-message-types-and-logging.rst @@ -0,0 +1,7 @@ +new-message-types-and-logging +----------------------------- + +* The :command:`message` command learned new types: ``NOTICE``, ``VERBOSE``, + ``DEBUG`` and ``TRACE``. + +* The :manual:`cmake(1)` command learned a new CLI option ``--loglevel``. diff --git a/Help/release/dev/relax-TARGET_OBJECTS-generator-expression.rst b/Help/release/dev/relax-TARGET_OBJECTS-generator-expression.rst new file mode 100644 index 0000000..25ca0c9 --- /dev/null +++ b/Help/release/dev/relax-TARGET_OBJECTS-generator-expression.rst @@ -0,0 +1,5 @@ +relax-TARGET_OBJECTS-generator-expression +----------------------------------------- + +* The ``TARGET_OBJECTS`` :manual:`generator expression <cmake-generator-expressions(7)>` + is now supported on ``SHARED``, ``STATIC``, ``MODULE`` libraries and executables. diff --git a/Help/release/dev/server-deprecate.rst b/Help/release/dev/server-deprecate.rst new file mode 100644 index 0000000..65c86e1 --- /dev/null +++ b/Help/release/dev/server-deprecate.rst @@ -0,0 +1,6 @@ +server-deprecate +---------------- + +* The :manual:`cmake-server(7)` mode has been deprecated and will be + removed from a future version of CMake. Please port clients to use + the :manual:`cmake-file-api(7)` instead. diff --git a/Help/release/dev/string-repeat.rst b/Help/release/dev/string-repeat.rst new file mode 100644 index 0000000..4be0d5c --- /dev/null +++ b/Help/release/dev/string-repeat.rst @@ -0,0 +1,4 @@ +string-repeat +-------------- + +* The :command:`string` learned a new sub-command ``REPEAT``. diff --git a/Help/release/dev/vs-project-import.rst b/Help/release/dev/vs-project-import.rst new file mode 100644 index 0000000..de6024d --- /dev/null +++ b/Help/release/dev/vs-project-import.rst @@ -0,0 +1,5 @@ +vs-project-import +----------------- + +* The :prop_tgt:`VS_PROJECT_IMPORT` target property was added which allows + to import external .props files in managed Visual Studio targets. diff --git a/Help/release/dev/xl-supports-cxx14.rst b/Help/release/dev/xl-supports-cxx14.rst new file mode 100644 index 0000000..a18e0ad --- /dev/null +++ b/Help/release/dev/xl-supports-cxx14.rst @@ -0,0 +1,4 @@ +xlc-supports-cxx14 +---------------------- + +* IBM AIX XL compiler have learned how to compile C++14. diff --git a/Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst b/Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst new file mode 100644 index 0000000..4a3121c --- /dev/null +++ b/Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst @@ -0,0 +1,6 @@ +CMAKE_EXECUTE_PROCESS_COMMAND_ECHO +---------------------------------- + +If this variable is set to ``STDERR``|``STDOUT``|``NONE`` then commands in +:command:`execute_process` calls will be printed to either stderr or stdout +or not at all. diff --git a/Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst b/Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst new file mode 100644 index 0000000..6ed68c9 --- /dev/null +++ b/Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst @@ -0,0 +1,27 @@ +CMAKE_MSVC_RUNTIME_LIBRARY +-------------------------- + +Select the MSVC runtime library for use by compilers targeting the MSVC ABI. +This variable is used to initialize the :prop_tgt:`MSVC_RUNTIME_LIBRARY` +property on all targets as they are created. It is also propagated by +calls to the :command:`try_compile` command into the test project. + +The allowed values are: + +.. include:: ../prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt + +Use :manual:`generator expressions <cmake-generator-expressions(7)>` to +support per-configuration specification. For example, the code: + +.. code-block:: cmake + + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + +selects for all following targets a multi-threaded statically-linked runtime +library with or without debug information depending on the configuration. + +.. note:: + + This variable has effect only when policy :policy:`CMP0091` is set to ``NEW`` + prior to the first :command:`project` or :command:`enable_language` command + that enables a language using a compiler targeting the MSVC ABI. diff --git a/Help/variable/CMAKE_VS_PLATFORM_NAME.rst b/Help/variable/CMAKE_VS_PLATFORM_NAME.rst index a532743..7a4642a 100644 --- a/Help/variable/CMAKE_VS_PLATFORM_NAME.rst +++ b/Help/variable/CMAKE_VS_PLATFORM_NAME.rst @@ -1,8 +1,10 @@ CMAKE_VS_PLATFORM_NAME ---------------------- -Visual Studio target platform name. +Visual Studio target platform name used by the current generator. VS 8 and above allow project files to specify a target platform. CMake provides the name of the chosen platform in this variable. See the :variable:`CMAKE_GENERATOR_PLATFORM` variable for details. + +See also the :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable. diff --git a/Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst b/Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst new file mode 100644 index 0000000..c18e6fd --- /dev/null +++ b/Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst @@ -0,0 +1,9 @@ +CMAKE_VS_PLATFORM_NAME_DEFAULT +------------------------------ + +Default for the Visual Studio target platform name for the current generator +without considering the value of the :variable:`CMAKE_GENERATOR_PLATFORM` +variable. For :ref:`Visual Studio Generators` for VS 2017 and below this is +always ``Win32``. For VS 2019 and above this is based on the host platform. + +See also the :variable:`CMAKE_VS_PLATFORM_NAME` variable. diff --git a/Modules/CMakeAddFortranSubdirectory.cmake b/Modules/CMakeAddFortranSubdirectory.cmake index 50b2807..2613569 100644 --- a/Modules/CMakeAddFortranSubdirectory.cmake +++ b/Modules/CMakeAddFortranSubdirectory.cmake @@ -16,7 +16,7 @@ build with the MinGW tools. It will also create imported targets for the libraries created. This will only work if the fortran code is built into a dll, so :variable:`BUILD_SHARED_LIBS` is turned on in the project. In addition the :variable:`CMAKE_GNUtoMS` option is set -to on, so that Microsoft .lib files are created. Usage is as follows: +to on, so that Microsoft ``.lib`` files are created. Usage is as follows: :: @@ -32,15 +32,15 @@ to on, so that Microsoft .lib files are created. Usage is as follows: NO_EXTERNAL_INSTALL # skip installation of external project ) -Relative paths in ARCHIVE_DIR and RUNTIME_DIR are interpreted with +Relative paths in ``ARCHIVE_DIR`` and ``RUNTIME_DIR`` are interpreted with respect to the build directory corresponding to the source directory in which the function is invoked. Limitations: -NO_EXTERNAL_INSTALL is required for forward compatibility with a +``NO_EXTERNAL_INSTALL`` is required for forward compatibility with a future version that supports installation of the external project -binaries during "make install". +binaries during ``make install``. #]=======================================================================] set(_MS_MINGW_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}) diff --git a/Modules/CMakeAddNewLanguage.txt b/Modules/CMakeAddNewLanguage.txt index 612e1a3..6baadc3 100644 --- a/Modules/CMakeAddNewLanguage.txt +++ b/Modules/CMakeAddNewLanguage.txt @@ -1,7 +1,7 @@ This file provides a few notes to CMake developers about how to add support for a new language to CMake. It is also possible to place -these files in CMAKE_MODULE_PATH within an outside project to add -languages not supported by upstream CMake. However, this is not +these files in :variable:`CMAKE_MODULE_PATH` within an outside project +to add languages not supported by upstream CMake. However, this is not a fully supported use case. The implementation behind the scenes of project/enable_language, @@ -29,5 +29,3 @@ CMake(LANG)Information.cmake -> set up rule variables for LANG : CMAKE_(LANG)_CREATE_STATIC_LIBRARY CMAKE_(LANG)_COMPILE_OBJECT CMAKE_(LANG)_LINK_EXECUTABLE - - diff --git a/Modules/CMakeDetermineASMCompiler.cmake b/Modules/CMakeDetermineASMCompiler.cmake index b8c8c5d..eabb8b5 100644 --- a/Modules/CMakeDetermineASMCompiler.cmake +++ b/Modules/CMakeDetermineASMCompiler.cmake @@ -119,35 +119,40 @@ if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER_ID) CMAKE_DETERMINE_COMPILER_ID_VENDOR(ASM${ASM_DIALECT} "${userflags}") if("x${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}" STREQUAL "xIAR") # primary necessary to detect architecture, so the right archiver and linker can be picked - # eg. IAR Assembler V8.10.1.12857/W32 for ARM + # eg. "IAR Assembler V8.10.1.12857/W32 for ARM" or "IAR Assembler V4.11.1.4666 for Renesas RX" # Cut out identification first, newline handling is a pain string(REGEX MATCH "IAR Assembler[^\r\n]*" _compileid "${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_OUTPUT}") if("${_compileid}" MATCHES "V([0-9]+\\.[0-9]+\\.[0-9]+)") set(CMAKE_ASM${ASM_DIALECT}_COMPILER_VERSION ${CMAKE_MATCH_1}) endif() - if("${_compileid}" MATCHES "for[ ]+([A-Za-z0-9]+)") - set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID ${CMAKE_MATCH_1}) + string(REGEX MATCHALL "([A-Za-z0-9]+)" _all_compileid_matches "${_compileid}") + if(_all_compileid_matches) + list(GET _all_compileid_matches "-1" CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID) endif() endif() unset(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_OUTPUT) + unset(_all_compileid_matches) unset(_compileid) endif() - if(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID) if(CMAKE_ASM${ASM_DIALECT}_COMPILER_VERSION) set(_version " ${CMAKE_ASM${ASM_DIALECT}_COMPILER_VERSION}") else() set(_version "") endif() - message(STATUS "The ASM${ASM_DIALECT} compiler identification is ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}${_version}") + if(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID) + set(_archid " ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID}") + else() + set(_archid "") + endif() + message(STATUS "The ASM${ASM_DIALECT} compiler identification is ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}${_archid}${_version}") + unset(_archid) unset(_version) else() message(STATUS "The ASM${ASM_DIALECT} compiler identification is unknown") endif() - - # If we have a gas/as cross compiler, they have usually some prefix, like # e.g. powerpc-linux-gas, arm-elf-gas or i586-mingw32msvc-gas , optionally # with a 3-component version number at the end diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake index 594f85b..c1c9982 100644 --- a/Modules/CMakeDetermineCompilerId.cmake +++ b/Modules/CMakeDetermineCompilerId.cmake @@ -110,8 +110,15 @@ function(CMAKE_DETERMINE_COMPILER_ID lang flagvar src) else() set(_version "") endif() + if(CMAKE_${lang}_COMPILER_ARCHITECTURE_ID) + set(_archid " ${CMAKE_${lang}_COMPILER_ARCHITECTURE_ID}") + else() + set(_archid "") + endif() message(STATUS "The ${lang} compiler identification is " - "${CMAKE_${lang}_COMPILER_ID}${_version}") + "${CMAKE_${lang}_COMPILER_ID}${_archid}${_version}") + unset(_archid) + unset(_version) else() message(STATUS "The ${lang} compiler identification is unknown") endif() diff --git a/Modules/CMakeForceCompiler.cmake b/Modules/CMakeForceCompiler.cmake index 7ac09dc..7048806 100644 --- a/Modules/CMakeForceCompiler.cmake +++ b/Modules/CMakeForceCompiler.cmake @@ -25,38 +25,41 @@ toolchain file instead. ------------------------------------------------------------------------- -Macro CMAKE_FORCE_C_COMPILER has the following signature: +Macro ``CMAKE_FORCE_C_COMPILER`` has the following signature: :: CMAKE_FORCE_C_COMPILER(<compiler> <compiler-id>) -It sets CMAKE_C_COMPILER to the given compiler and the cmake internal -variable CMAKE_C_COMPILER_ID to the given compiler-id. It also -bypasses the check for working compiler and basic compiler information -tests. +It sets :variable:`CMAKE_C_COMPILER <CMAKE_<LANG>_COMPILER>` to +the given compiler and the cmake internal variable +:variable:`CMAKE_C_COMPILER_ID <CMAKE_<LANG>_COMPILER_ID>` to the given +compiler-id. It also bypasses the check for working compiler and basic +compiler information tests. -Macro CMAKE_FORCE_CXX_COMPILER has the following signature: +Macro ``CMAKE_FORCE_CXX_COMPILER`` has the following signature: :: CMAKE_FORCE_CXX_COMPILER(<compiler> <compiler-id>) -It sets CMAKE_CXX_COMPILER to the given compiler and the cmake -internal variable CMAKE_CXX_COMPILER_ID to the given compiler-id. It -also bypasses the check for working compiler and basic compiler -information tests. +It sets :variable:`CMAKE_CXX_COMPILER <CMAKE_<LANG>_COMPILER>` to +the given compiler and the cmake internal variable +:variable:`CMAKE_CXX_COMPILER_ID <CMAKE_<LANG>_COMPILER_ID>` to the given +compiler-id. It also bypasses the check for working compiler and basic +compiler information tests. -Macro CMAKE_FORCE_Fortran_COMPILER has the following signature: +Macro ``CMAKE_FORCE_Fortran_COMPILER`` has the following signature: :: CMAKE_FORCE_Fortran_COMPILER(<compiler> <compiler-id>) -It sets CMAKE_Fortran_COMPILER to the given compiler and the cmake -internal variable CMAKE_Fortran_COMPILER_ID to the given compiler-id. -It also bypasses the check for working compiler and basic compiler -information tests. +It sets :variable:`CMAKE_Fortran_COMPILER <CMAKE_<LANG>_COMPILER>` to +the given compiler and the cmake internal variable +:variable:`CMAKE_Fortran_COMPILER_ID <CMAKE_<LANG>_COMPILER_ID>` to the given +compiler-id. It also bypasses the check for working compiler and basic +compiler information tests. So a simple toolchain file could look like this: diff --git a/Modules/CMakePlatformId.h.in b/Modules/CMakePlatformId.h.in index 3cb7f24..c88094a 100644 --- a/Modules/CMakePlatformId.h.in +++ b/Modules/CMakePlatformId.h.in @@ -156,6 +156,9 @@ # if defined(__ICCARM__) # define ARCHITECTURE_ID "ARM" +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + # elif defined(__ICCAVR__) # define ARCHITECTURE_ID "AVR" diff --git a/Modules/CheckLanguage.cmake b/Modules/CheckLanguage.cmake index efa88bd..d096849 100644 --- a/Modules/CheckLanguage.cmake +++ b/Modules/CheckLanguage.cmake @@ -13,11 +13,11 @@ Usage: check_language(<lang>) -where <lang> is a language that may be passed to enable_language() -such as "Fortran". If CMAKE_<lang>_COMPILER is already defined the -check does nothing. Otherwise it tries enabling the language in a -test project. The result is cached in CMAKE_<lang>_COMPILER as the -compiler that was found, or NOTFOUND if the language cannot be +where ``<lang>`` is a language that may be passed to :command:`enable_language` +such as ``Fortran``. If :variable:`CMAKE_<LANG>_COMPILER` is already defined +the check does nothing. Otherwise it tries enabling the language in a +test project. The result is cached in :variable:`CMAKE_<LANG>_COMPILER` +as the compiler that was found, or ``NOTFOUND`` if the language cannot be enabled. Example: diff --git a/Modules/CheckPIESupported.cmake b/Modules/CheckPIESupported.cmake index 720217d..6d63f0b 100644 --- a/Modules/CheckPIESupported.cmake +++ b/Modules/CheckPIESupported.cmake @@ -5,8 +5,8 @@ CheckPIESupported ----------------- -Check whether the linker supports position independent code (PIE) or no -position independent code (NO_PIE) for executables. +Check whether the linker supports Position Independent Code (PIE) or No +Position Independent Code (NO_PIE) for executables. Use this to ensure that the :prop_tgt:`POSITION_INDEPENDENT_CODE` target property for executables will be honored at link time. diff --git a/Modules/Compiler/Clang-C.cmake b/Modules/Compiler/Clang-C.cmake index ff51d30..0448965 100644 --- a/Modules/Compiler/Clang-C.cmake +++ b/Modules/Compiler/Clang-C.cmake @@ -23,12 +23,15 @@ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4) # clang-cl doesn't have any of these set(CMAKE_C90_STANDARD_COMPILE_OPTION "") set(CMAKE_C90_EXTENSION_COMPILE_OPTION "") + set(CMAKE_C90_STANDARD__HAS_FULL_SUPPORT ON) set(CMAKE_C99_STANDARD_COMPILE_OPTION "") set(CMAKE_C99_EXTENSION_COMPILE_OPTION "") + set(CMAKE_C99_STANDARD__HAS_FULL_SUPPORT ON) set(CMAKE_C11_STANDARD_COMPILE_OPTION "") set(CMAKE_C11_EXTENSION_COMPILE_OPTION "") + set(CMAKE_C11_STANDARD__HAS_FULL_SUPPORT ON) endif() endif() diff --git a/Modules/Compiler/IAR-ASM.cmake b/Modules/Compiler/IAR-ASM.cmake index e12bfd1..f9c0ced 100644 --- a/Modules/Compiler/IAR-ASM.cmake +++ b/Modules/Compiler/IAR-ASM.cmake @@ -3,21 +3,20 @@ include(Compiler/IAR) if("${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM") -set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> -S <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>") - __compiler_iar_ARM(ASM) + set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> -S <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>") + __compiler_iar_ilink(ASM) set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s;asm;msa) - string(APPEND CMAKE_ASM_FLAGS_INIT " ") - string(APPEND CMAKE_ASM_FLAGS_DEBUG_INIT " -r") - string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -DNDEBUG") - string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -DNDEBUG") - string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -r -DNDEBUG") +elseif("${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID}" STREQUAL "RX") + set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>") + __compiler_iar_ilink(ASM) + set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s;asm;msa) elseif("${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> -S <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>") - __compiler_iar_AVR(ASM) + __compiler_iar_xlink(ASM) set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s90;asm;msa) else() - message(FATAL_ERROR "CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID not detected as \"AVR\" or \"ARM\". This should be automatic.") + message(FATAL_ERROR "CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID not detected. This should be automatic.") endif() diff --git a/Modules/Compiler/IAR-C.cmake b/Modules/Compiler/IAR-C.cmake index b5e61f0..cb10020 100644 --- a/Modules/Compiler/IAR-C.cmake +++ b/Modules/Compiler/IAR-C.cmake @@ -3,44 +3,39 @@ include(Compiler/IAR) include(Compiler/CMakeCommonCompilerMacros) -# The toolchains for ARM and AVR are quite different: -if("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM") - if(NOT CMAKE_C_COMPILER_VERSION) - message(FATAL_ERROR "CMAKE_C_COMPILER_VERSION not detected. This should be automatic.") - endif() +# Common +if(NOT CMAKE_C_COMPILER_VERSION) + message(FATAL_ERROR "CMAKE_C_COMPILER_VERSION not detected. This should be automatic.") +endif() - set(CMAKE_C_EXTENSION_COMPILE_OPTION -e) +set(CMAKE_C_EXTENSION_COMPILE_OPTION -e) +if(CMAKE_CXX_COMPILER_VERSION_INTERNAL VERSION_GREATER 7) + set(CMAKE_C90_STANDARD_COMPILE_OPTION --c89) + set(CMAKE_C90_EXTENSION_COMPILE_OPTION --c89 -e) + set(CMAKE_C99_STANDARD_COMPILE_OPTION "") + set(CMAKE_C99_EXTENSION_COMPILE_OPTION -e) +elseif() set(CMAKE_C90_STANDARD_COMPILE_OPTION "") set(CMAKE_C90_EXTENSION_COMPILE_OPTION -e) +endif() - if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 6.10) - set(CMAKE_C90_STANDARD_COMPILE_OPTION --c89) - set(CMAKE_C90_EXTENSION_COMPILE_OPTION --c89 -e) - set(CMAKE_C99_STANDARD_COMPILE_OPTION "") - set(CMAKE_C99_EXTENSION_COMPILE_OPTION -e) - endif() - if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 8.10) - set(CMAKE_C11_STANDARD_COMPILE_OPTION "") - set(CMAKE_C11_EXTENSION_COMPILE_OPTION -e) - endif() +if(CMAKE_CXX_COMPILER_VERSION_INTERNAL VERSION_GREATER 8) + set(CMAKE_C11_STANDARD_COMPILE_OPTION "") + set(CMAKE_C11_EXTENSION_COMPILE_OPTION -e) +endif() - __compiler_iar_ARM(C) +# Architecture specific +if("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM") + __compiler_iar_ilink(C) __compiler_check_default_language_standard(C 1.10 90 6.10 99 8.10 11) -elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") - if(NOT CMAKE_C_COMPILER_VERSION) - message(FATAL_ERROR "CMAKE_C_COMPILER_VERSION not detected. This should be automatic.") - endif() - - set(CMAKE_C_EXTENSION_COMPILE_OPTION -e) - - set(CMAKE_C90_STANDARD_COMPILE_OPTION --c89) - set(CMAKE_C90_EXTENSION_COMPILE_OPTION -e) - set(CMAKE_C99_STANDARD_COMPILE_OPTION "") - set(CMAKE_C99_EXTENSION_COMPILE_OPTION -e) +elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "RX") + __compiler_iar_ilink(C) + __compiler_check_default_language_standard(C 1.10 90 2.10 99 4.10 11) - __compiler_iar_AVR(C) +elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") + __compiler_iar_xlink(C) __compiler_check_default_language_standard(C 7.10 99) set(CMAKE_C_OUTPUT_EXTENSION ".r90") @@ -48,9 +43,6 @@ elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") set(CMAKE_C_LINK_FLAGS "-Fmotorola") endif() - set(CMAKE_C_LINK_EXECUTABLE "<CMAKE_LINKER> <OBJECTS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>") - set(CMAKE_C_CREATE_STATIC_LIBRARY "<CMAKE_AR> -o <TARGET> <OBJECTS> ") - # add the target specific include directory: get_filename_component(_compilerDir "${CMAKE_C_COMPILER}" PATH) get_filename_component(_compilerDir "${_compilerDir}" PATH) @@ -58,5 +50,5 @@ elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") include_directories("${_compilerDir}/inc/Atmel" ) else() - message(FATAL_ERROR "CMAKE_C_COMPILER_ARCHITECTURE_ID not detected as \"AVR\" or \"ARM\". This should be automatic.") + message(FATAL_ERROR "CMAKE_C_COMPILER_ARCHITECTURE_ID not detected. This should be automatic.") endif() diff --git a/Modules/Compiler/IAR-CXX.cmake b/Modules/Compiler/IAR-CXX.cmake index b7076f5..eb27e3c 100644 --- a/Modules/Compiler/IAR-CXX.cmake +++ b/Modules/Compiler/IAR-CXX.cmake @@ -3,60 +3,45 @@ include(Compiler/IAR) include(Compiler/CMakeCommonCompilerMacros) -if("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM") - # "(extended) embedded C++" Mode - # old version: --ec++ or --eec++ - # since 8.10: --c++ --no_exceptions --no_rtti - # - # --c++ is full C++ and supported since 6.10 - if(NOT CMAKE_IAR_CXX_FLAG) - if(NOT CMAKE_CXX_COMPILER_VERSION) - message(FATAL_ERROR "CMAKE_CXX_COMPILER_VERSION not detected. This should be automatic.") - endif() - if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.10) - set(CMAKE_IAR_CXX_FLAG --c++) - else() - set(CMAKE_IAR_CXX_FLAG --eec++) - endif() +# Common +if(NOT CMAKE_IAR_CXX_FLAG) + if(NOT CMAKE_CXX_COMPILER_VERSION) + message(FATAL_ERROR "CMAKE_CXX_COMPILER_VERSION not detected. This should be automatic.") + endif() + if(CMAKE_CXX_COMPILER_VERSION_INTERNAL VERSION_GREATER 8) + set(CMAKE_IAR_CXX_FLAG --c++) + else() + set(CMAKE_IAR_CXX_FLAG --eec++) endif() +endif() - set(CMAKE_CXX_EXTENSION_COMPILE_OPTION -e) +set(CMAKE_CXX_EXTENSION_COMPILE_OPTION -e) +if(CMAKE_CXX_COMPILER_VERSION_INTERNAL VERSION_GREATER 7) set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION -e) - - if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 8.10) set(CMAKE_CXX03_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX03_EXTENSION_COMPILE_OPTION -e) +endif() + +if(CMAKE_CXX_COMPILER_VERSION_INTERNAL VERSION_GREATER 8) set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION -e) set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION -e) - endif() +endif() - __compiler_iar_ARM(CXX) +# Architecture specific +if("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM") + __compiler_iar_ilink(CXX) __compiler_check_default_language_standard(CXX 6.10 98 8.10 14) -elseif("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") - # "embedded C++" --EC++ is probably closest to CXX98 but with no support for: - # Templates, multiple inheritance, virtual inheritance, exceptions, RTTI, C++ style casts, - # Namespaces, the mutable attribute, no STL, any library features related to the above features. - # - # "(extended) embedded C++" --EEC++ Mode but DOES NOT support any normal C++ standard - # probably closest to CXX98 but with no RTTI and no exceptions, and the library - # provided is not in the standard namespace - if(NOT CMAKE_IAR_CXX_FLAG) - if(NOT CMAKE_CXX_COMPILER_VERSION) - message(FATAL_ERROR "CMAKE_CXX_COMPILER_VERSION not detected. This should be automatic.") - endif() - set(CMAKE_IAR_CXX_FLAG --eec++) - endif() +elseif("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "RX") + __compiler_iar_ilink(CXX) + __compiler_check_default_language_standard(CXX 2.10 98 4.10 14) - set(CMAKE_CXX_EXTENSION_COMPILE_OPTION -e) - set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "") - set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION -e) - - __compiler_iar_AVR(CXX) +elseif("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") + __compiler_iar_xlink(CXX) __compiler_check_default_language_standard(CXX 7.10 98) set(CMAKE_CXX_OUTPUT_EXTENSION ".r90") @@ -64,15 +49,12 @@ elseif("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") set(CMAKE_CXX_LINK_FLAGS "-Fmotorola") endif() - set(CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_LINKER> <OBJECTS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>") - set(CMAKE_CXX_CREATE_STATIC_LIBRARY "<CMAKE_AR> -o <TARGET> <OBJECTS> ") - # add the target specific include directory: get_filename_component(_compilerDir "${CMAKE_C_COMPILER}" PATH) get_filename_component(_compilerDir "${_compilerDir}" PATH) - include_directories("${_compilerDir}/inc") - include_directories("${_compilerDir}/inc/Atmel") + include_directories("${_compilerDir}/inc" ) + include_directories("${_compilerDir}/inc/Atmel" ) else() - message(FATAL_ERROR "CMAKE_CXX_COMPILER_ARCHITECTURE_ID not detected as \"AVR\" or \"ARM\". This should be automatic." ) + message(FATAL_ERROR "CMAKE_CXX_COMPILER_ARCHITECTURE_ID not detected. This should be automatic." ) endif() diff --git a/Modules/Compiler/IAR-DetermineCompiler.cmake b/Modules/Compiler/IAR-DetermineCompiler.cmake index 43477ac..cdfb095 100644 --- a/Modules/Compiler/IAR-DetermineCompiler.cmake +++ b/Modules/Compiler/IAR-DetermineCompiler.cmake @@ -31,7 +31,7 @@ set(_compiler_id_version_compute " # define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(((__VER__) / 1000) % 1000) # define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@((__VER__) % 1000) # define @PREFIX@COMPILER_VERSION_INTERNAL @MACRO_DEC@(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && defined(__ICCAVR__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__)) # define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@((__VER__) / 100) # define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@((__VER__) - (((__VER__) / 100)*100)) # define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__SUBVERSION__) diff --git a/Modules/Compiler/IAR-FindBinUtils.cmake b/Modules/Compiler/IAR-FindBinUtils.cmake index 5fecb26..e8f5e6b 100644 --- a/Modules/Compiler/IAR-FindBinUtils.cmake +++ b/Modules/Compiler/IAR-FindBinUtils.cmake @@ -10,39 +10,39 @@ get_filename_component(__iar_hint_2 "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPI set(__iar_hints "${__iar_hint_1}" "${__iar_hint_2}") -if("${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM") - # could allow using normal binutils ar, since objects are normal ELF files? - find_program(CMAKE_IAR_LINKARM ilinkarm.exe HINTS ${__iar_hints} - DOC "The IAR ARM linker") +if("${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM" OR + "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "RX") + # could allow using normal binutils ar, since objects are normal ELF files? + find_program(CMAKE_IAR_LINKER ilink${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}.exe HINTS ${__iar_hints} + DOC "The IAR ILINK linker") find_program(CMAKE_IAR_ARCHIVE iarchive.exe HINTS ${__iar_hints} DOC "The IAR archiver") # find auxiliary tools find_program(CMAKE_IAR_ELFTOOL ielftool.exe HINTS ${__iar_hints} DOC "The IAR ELF Tool") - find_program(CMAKE_IAR_ELFDUMP ielfdumparm.exe HINTS ${__iar_hints} + find_program(CMAKE_IAR_ELFDUMP ielfdump${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}.exe HINTS ${__iar_hints} DOC "The IAR ELF Dumper") find_program(CMAKE_IAR_OBJMANIP iobjmanip.exe HINTS ${__iar_hints} DOC "The IAR ELF Object Tool") find_program(CMAKE_IAR_SYMEXPORT isymexport.exe HINTS ${__iar_hints} DOC "The IAR Absolute Symbol Exporter") - mark_as_advanced(CMAKE_IAR_LINKARM CMAKE_IAR_ARCHIVE CMAKE_IAR_ELFTOOL CMAKE_IAR_ELFDUMP CMAKE_IAR_OBJMANIP CMAKE_IAR_SYMEXPORT) + mark_as_advanced(CMAKE_IAR_LINKER CMAKE_IAR_ARCHIVE CMAKE_IAR_ELFTOOL CMAKE_IAR_ELFDUMP CMAKE_IAR_OBJMANIP CMAKE_IAR_SYMEXPORT) set(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_CUSTOM_CODE -"set(CMAKE_IAR_LINKARM \"${CMAKE_IAR_LINKARM}\") +"set(CMAKE_IAR_LINKER \"${CMAKE_IAR_LINKER}\") set(CMAKE_IAR_ARCHIVE \"${CMAKE_IAR_ARCHIVE}\") set(CMAKE_IAR_ELFTOOL \"${CMAKE_IAR_ELFTOOL}\") set(CMAKE_IAR_ELFDUMP \"${CMAKE_IAR_ELFDUMP}\") set(CMAKE_IAR_OBJMANIP \"${CMAKE_IAR_OBJMANIP}\") -set(CMAKE_IAR_LINKARM \"${CMAKE_IAR_LINKARM}\") +set(CMAKE_IAR_LINKER \"${CMAKE_IAR_LINKER}\") ") - elseif("${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR") # For AVR and AVR32, IAR uses the "xlink" linker and the "xar" archiver: find_program(CMAKE_IAR_LINKER xlink.exe HINTS ${__iar_hints} - DOC "The IAR AVR linker") + DOC "The IAR XLINK linker") find_program(CMAKE_IAR_AR xar.exe HINTS ${__iar_hints} DOC "The IAR archiver") mark_as_advanced(CMAKE_IAR_LINKER CMAKE_IAR_AR) diff --git a/Modules/Compiler/IAR.cmake b/Modules/Compiler/IAR.cmake index bbcdea2..8e75caa 100644 --- a/Modules/Compiler/IAR.cmake +++ b/Modules/Compiler/IAR.cmake @@ -2,11 +2,16 @@ # Documentation can be downloaded here: http://www.iar.com/website1/1.0.1.0/675/1/ # The initial feature request is here: https://gitlab.kitware.com/cmake/cmake/issues/10176 # It also contains additional links and information. -# See USER GUIDES -> C/C++ Development Guide and ReleaseNotes for: +# See USER GUIDES -> C/C++ Development Guide and ReleaseNotes for EWARM: # version 6.30.8: http://supp.iar.com/FilesPublic/UPDINFO/006607/arm/doc/infocenter/index.ENU.html # version 7.60.1: http://supp.iar.com/FilesPublic/UPDINFO/011006/arm/doc/infocenter/index.ENU.html # version 8.10.1: http://netstorage.iar.com/SuppDB/Public/UPDINFO/011854/arm/doc/infocenter/index.ENU.html +# The IAR internal compiler platform generations (Predefined symbol __IAR_SYSTEMS_ICC__): +# 9 and higher means C11 and C++14 as language default (EWARM v8.x, EWRX v4.x and higher) +# 8 means C99 and C++03 as language default (EWARM v6.x, v7.x. EWRX v2.x, 3.x) +# 7 and lower means C89 and EC++ as language default. (EWARM v5.x and lower) + # C/C++ Standard versions # # IAR typically only supports one C and C++ Standard version, @@ -33,15 +38,11 @@ # code and data size printouts (that can be inspected with common tools). # This module is shared by multiple languages; use include blocker. -if(_IARARM_CMAKE_LOADED) - return() -endif() -set(_IARARM_CMAKE_LOADED 1) +include_guard() -macro(__compiler_iar_ARM lang) +macro(__compiler_iar_ilink lang) set(CMAKE_EXECUTABLE_SUFFIX ".elf") if (${lang} STREQUAL "C" OR ${lang} STREQUAL "CXX") - set(CMAKE_${lang}_COMPILE_OBJECT "<CMAKE_${lang}_COMPILER> ${CMAKE_IAR_${lang}_FLAG} --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>") set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> ${CMAKE_IAR_${lang}_FLAG} --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> --preprocess=cnl <PREPROCESSED_SOURCE>") set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE "<CMAKE_${lang}_COMPILER> ${CMAKE_IAR_${lang}_FLAG} --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -lAH <ASSEMBLY_SOURCE> -o <OBJECT>.dummy") @@ -56,17 +57,25 @@ macro(__compiler_iar_ARM lang) string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -Oh -r -DNDEBUG") endif() - set(CMAKE_${lang}_LINK_EXECUTABLE "\"${CMAKE_IAR_LINKARM}\" --silent <OBJECTS> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>") + if (${lang} STREQUAL "ASM") + string(APPEND CMAKE_ASM_FLAGS_INIT " ") + string(APPEND CMAKE_ASM_FLAGS_DEBUG_INIT " -r") + string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -DNDEBUG") + string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -DNDEBUG") + string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -r -DNDEBUG") + endif() + + set(CMAKE_${lang}_LINK_EXECUTABLE "\"${CMAKE_IAR_LINKER}\" --silent <OBJECTS> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>") set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "\"${CMAKE_IAR_ARCHIVE}\" <TARGET> --create <LINK_FLAGS> <OBJECTS>") set(CMAKE_${lang}_ARCHIVE_CREATE "\"${CMAKE_IAR_ARCHIVE}\" <TARGET> --create <LINK_FLAGS> <OBJECTS>") set(CMAKE_${lang}_ARCHIVE_APPEND "\"${CMAKE_IAR_ARCHIVE}\" <TARGET> --replace <LINK_FLAGS> <OBJECTS>") set(CMAKE_${lang}_ARCHIVE_FINISH "") - set(CMAKE_LINKER "${CMAKE_IAR_LINKARM}" CACHE FILEPATH "The IAR linker" FORCE) + set(CMAKE_LINKER "${CMAKE_IAR_LINKER}" CACHE FILEPATH "The IAR linker" FORCE) set(CMAKE_AR "${CMAKE_IAR_ARCHIVE}" CACHE FILEPATH "The IAR archiver" FORCE) endmacro() -macro(__compiler_iar_AVR lang) +macro(__compiler_iar_xlink lang) set(CMAKE_EXECUTABLE_SUFFIX ".bin") if (${lang} STREQUAL "C" OR ${lang} STREQUAL "CXX") @@ -84,6 +93,14 @@ macro(__compiler_iar_AVR lang) string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -Oh -r -DNDEBUG") endif() + if (${lang} STREQUAL "ASM") + string(APPEND CMAKE_ASM_FLAGS_INIT " ") + string(APPEND CMAKE_ASM_FLAGS_DEBUG_INIT " -r") + string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -DNDEBUG") + string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -DNDEBUG") + string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -r -DNDEBUG") + endif() + set(CMAKE_${lang}_LINK_EXECUTABLE "\"${CMAKE_IAR_LINKER}\" -S <OBJECTS> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>") set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "\"${CMAKE_IAR_AR}\" <TARGET> <LINK_FLAGS> <OBJECTS>") set(CMAKE_${lang}_ARCHIVE_CREATE "\"${CMAKE_IAR_AR}\" <TARGET> <LINK_FLAGS> <OBJECTS>") diff --git a/Modules/Compiler/Intel-DetermineCompiler.cmake b/Modules/Compiler/Intel-DetermineCompiler.cmake index d7e4532..c31aa77 100644 --- a/Modules/Compiler/Intel-DetermineCompiler.cmake +++ b/Modules/Compiler/Intel-DetermineCompiler.cmake @@ -18,9 +18,23 @@ set(_compiler_id_version_compute " /* _MSC_VER = VVRR */ # define @PREFIX@SIMULATE_VERSION_MAJOR @MACRO_DEC@(_MSC_VER / 100) # define @PREFIX@SIMULATE_VERSION_MINOR @MACRO_DEC@(_MSC_VER % 100) +# endif +# if defined(__GNUC__) +# define @PREFIX@SIMULATE_VERSION_MAJOR @MACRO_DEC@(__GNUC__) +# elif defined(__GNUG__) +# define @PREFIX@SIMULATE_VERSION_MAJOR @MACRO_DEC@(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define @PREFIX@SIMULATE_VERSION_MINOR @MACRO_DEC@(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define @PREFIX@SIMULATE_VERSION_PATCH @MACRO_DEC@(__GNUC_PATCHLEVEL__) # endif") set(_compiler_id_simulate " # if defined(_MSC_VER) # define @PREFIX@SIMULATE_ID \"MSVC\" +# endif +# if defined(__GNUC__) +# define @PREFIX@SIMULATE_ID \"GNU\" # endif") diff --git a/Modules/Compiler/MSVC-C.cmake b/Modules/Compiler/MSVC-C.cmake index 22c34f8..f56227b 100644 --- a/Modules/Compiler/MSVC-C.cmake +++ b/Modules/Compiler/MSVC-C.cmake @@ -11,8 +11,8 @@ set(CMAKE_C11_EXTENSION_COMPILE_OPTION "") # There is no meaningful default for this set(CMAKE_C_STANDARD_DEFAULT "") -# There are no C compiler modes so we only need to test features once. -# Override the default macro for this special case. Pretend that +# There are no C compiler modes so we hard-code the known compiler supported +# features. Override the default macro for this special case. Pretend that # all language standards are available so that at least compilation # can be attempted. macro(cmake_record_c_compile_features) @@ -20,6 +20,14 @@ macro(cmake_record_c_compile_features) c_std_90 c_std_99 c_std_11 + c_function_prototypes ) - _record_compiler_features(C "" CMAKE_C_COMPILE_FEATURES) + list(APPEND CMAKE_C90_COMPILE_FEATURES c_std_90 c_function_prototypes) + list(APPEND CMAKE_C99_COMPILE_FEATURES c_std_99) + list(APPEND CMAKE_C11_COMPILE_FEATURES c_std_11) + if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 14.0) + list(APPEND CMAKE_C_COMPILE_FEATURES c_variadic_macros) + list(APPEND CMAKE_C99_COMPILE_FEATURES c_variadic_macros) + endif() + set(_result 0) # expected by cmake_determine_compile_features endmacro() diff --git a/Modules/Compiler/SunPro-CXX-FeatureTests.cmake b/Modules/Compiler/SunPro-CXX-FeatureTests.cmake index 279d875..e7133c1 100644 --- a/Modules/Compiler/SunPro-CXX-FeatureTests.cmake +++ b/Modules/Compiler/SunPro-CXX-FeatureTests.cmake @@ -6,6 +6,14 @@ set(_cmake_oldestSupported "__SUNPRO_CC >= 0x5130") +set(SolarisStudio126_CXX14 "(__SUNPRO_CC >= 0x5150) && __cplusplus >= 201402L") +set(_cmake_feature_test_cxx_aggregate_default_initializers "${SolarisStudio126_CXX14}") +set(_cmake_feature_test_cxx_digit_separators "${SolarisStudio126_CXX14}") +set(_cmake_feature_test_cxx_generic_lambdas "${SolarisStudio126_CXX14}") +set(_cmake_feature_test_cxx_lambda_init_captures "${SolarisStudio126_CXX14}") +set(_cmake_feature_test_cxx_return_type_deduction "${SolarisStudio126_CXX14}") +set(_cmake_feature_test_cxx_variable_templates "${SolarisStudio126_CXX14}") + set(SolarisStudio126_CXX11 "(__SUNPRO_CC >= 0x5150) && __cplusplus >= 201103L") set(_cmake_feature_test_cxx_decltype_auto "${SolarisStudio126_CXX11}") diff --git a/Modules/Compiler/SunPro-CXX.cmake b/Modules/Compiler/SunPro-CXX.cmake index c2f6d1d..c946c64 100644 --- a/Modules/Compiler/SunPro-CXX.cmake +++ b/Modules/Compiler/SunPro-CXX.cmake @@ -52,6 +52,11 @@ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13) set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++11") set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=c++11") set(CMAKE_CXX_LINK_WITH_STANDARD_COMPILE_OPTION 1) + + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.14) + set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14") + set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=c++14") + endif() else() set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "-library=stlport4") set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "-library=stlport4") diff --git a/Modules/Compiler/XL-CXX.cmake b/Modules/Compiler/XL-CXX.cmake index ec3f1f8..3037851 100644 --- a/Modules/Compiler/XL-CXX.cmake +++ b/Modules/Compiler/XL-CXX.cmake @@ -18,6 +18,11 @@ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 10.1) set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-qlanglvl=extended0x") set(CMAKE_CXX98_STANDARD__HAS_FULL_SUPPORT ON) set(CMAKE_CXX11_STANDARD__HAS_FULL_SUPPORT ON) + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.1.0) + set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-qlanglvl=extended1y") + set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-qlanglvl=extended1y") + set(CMAKE_CXX14_STANDARD__HAS_FULL_SUPPORT ON) + endif() endif () __compiler_check_default_language_standard(CXX 10.1 98) diff --git a/Modules/Compiler/XLClang-CXX.cmake b/Modules/Compiler/XLClang-CXX.cmake index 03c7c7b..9ea3d7c 100644 --- a/Modules/Compiler/XLClang-CXX.cmake +++ b/Modules/Compiler/XLClang-CXX.cmake @@ -15,6 +15,10 @@ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 13.1.1) set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y") set(CMAKE_CXX14_STANDARD__HAS_FULL_SUPPORT ON) endif () + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.1.0) + set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14") + set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++14") + endif() endif() __compiler_check_default_language_standard(CXX 13.1.1 98) diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake index 8f1e194..20b37d2 100644 --- a/Modules/ExternalProject.cmake +++ b/Modules/ExternalProject.cmake @@ -422,6 +422,10 @@ External Project Definition different behavior depending on whether the build starts from a fresh build directory or re-uses previous build contents. + If the CMake generator is the ``Green Hills MULTI`` and not overridden then + the orginal projects settings for the GHS toolset and target system + customization cache variables are propagated into the external project. + ``SOURCE_SUBDIR <dir>`` When no ``CONFIGURE_COMMAND`` option is specified, the configure step assumes the external project has a ``CMakeLists.txt`` file at the top of @@ -2850,18 +2854,6 @@ function(_ep_extract_configure_command var name) set(has_cmake_cache_default_args 1) endif() - if(has_cmake_cache_args OR has_cmake_cache_default_args) - set(_ep_cache_args_script "<TMP_DIR>/${name}-cache-$<CONFIG>.cmake") - if(has_cmake_cache_args) - _ep_command_line_to_initial_cache(script_initial_cache_force "${cmake_cache_args}" 1) - endif() - if(has_cmake_cache_default_args) - _ep_command_line_to_initial_cache(script_initial_cache_default "${cmake_cache_default_args}" 0) - endif() - _ep_write_initial_cache(${name} "${_ep_cache_args_script}" "${script_initial_cache_force}${script_initial_cache_default}") - list(APPEND cmd "-C${_ep_cache_args_script}") - endif() - get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR) get_target_property(cmake_generator_instance ${name} _EP_CMAKE_GENERATOR_INSTANCE) get_target_property(cmake_generator_platform ${name} _EP_CMAKE_GENERATOR_PLATFORM) @@ -2882,6 +2874,16 @@ function(_ep_extract_configure_command var name) list(APPEND cmd "-G${CMAKE_EXTRA_GENERATOR} - ${CMAKE_GENERATOR}") else() list(APPEND cmd "-G${CMAKE_GENERATOR}") + if("${CMAKE_GENERATOR}" MATCHES "Green Hills MULTI") + set(has_cmake_cache_default_args 1) + set(cmake_cache_default_args ${cmake_cache_default_args} + "-DGHS_TARGET_PLATFORM:STRING=${GHS_TARGET_PLATFORM}" + "-DGHS_PRIMARY_TARGET:STRING=${GHS_PRIMARY_TARGET}" + "-DGHS_TOOLSET_ROOT:STRING=${GHS_TOOLSET_ROOT}" + "-DGHS_OS_ROOT:STRING=${GHS_OS_ROOT}" + "-DGHS_OS_DIR:STRING=${GHS_OS_DIR}" + "-DGHS_BSP_NAME:STRING=${GHS_BSP_NAME}") + endif() endif() if(cmake_generator_platform) message(FATAL_ERROR "Option CMAKE_GENERATOR_PLATFORM not allowed without CMAKE_GENERATOR.") @@ -2903,6 +2905,18 @@ function(_ep_extract_configure_command var name) endif() endif() + if(has_cmake_cache_args OR has_cmake_cache_default_args) + set(_ep_cache_args_script "<TMP_DIR>/${name}-cache-$<CONFIG>.cmake") + if(has_cmake_cache_args) + _ep_command_line_to_initial_cache(script_initial_cache_force "${cmake_cache_args}" 1) + endif() + if(has_cmake_cache_default_args) + _ep_command_line_to_initial_cache(script_initial_cache_default "${cmake_cache_default_args}" 0) + endif() + _ep_write_initial_cache(${name} "${_ep_cache_args_script}" "${script_initial_cache_force}${script_initial_cache_default}") + list(APPEND cmd "-C${_ep_cache_args_script}") + endif() + list(APPEND cmd "<SOURCE_DIR><SOURCE_SUBDIR>") endif() diff --git a/Modules/FindALSA.cmake b/Modules/FindALSA.cmake index f27d7fe..88e2681 100644 --- a/Modules/FindALSA.cmake +++ b/Modules/FindALSA.cmake @@ -5,9 +5,9 @@ FindALSA -------- -Find alsa +Find Advanced Linux Sound Architecture (ALSA) -Find the alsa libraries (asound) +Find the alsa libraries (``asound``) IMPORTED Targets ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindAVIFile.cmake b/Modules/FindAVIFile.cmake index c12512f..9655440 100644 --- a/Modules/FindAVIFile.cmake +++ b/Modules/FindAVIFile.cmake @@ -7,7 +7,7 @@ FindAVIFile Locate AVIFILE library and include paths -AVIFILE (http://avifile.sourceforge.net/)is a set of libraries for +AVIFILE (http://avifile.sourceforge.net/) is a set of libraries for i386 machines to use various AVI codecs. Support is limited beyond Linux. Windows provides native AVI support, and so doesn't need this library. This module defines diff --git a/Modules/FindArmadillo.cmake b/Modules/FindArmadillo.cmake index ce76c99..c4e55ce 100644 --- a/Modules/FindArmadillo.cmake +++ b/Modules/FindArmadillo.cmake @@ -5,9 +5,8 @@ FindArmadillo ------------- -Find Armadillo - -Find the Armadillo C++ library +Find the Armadillo C++ library. +Armadillo is library for linear algebra & scientific computing. Using Armadillo: diff --git a/Modules/FindBISON.cmake b/Modules/FindBISON.cmake index b0e25dc..e75981c 100644 --- a/Modules/FindBISON.cmake +++ b/Modules/FindBISON.cmake @@ -16,7 +16,7 @@ The module defines the following variables: version of ``bison`` ``BISON_FOUND`` - true if the program was found + "True" if the program was found The minimum required version of ``bison`` can be specified using the standard CMake syntax, e.g. :command:`find_package(BISON 2.1.3)`. diff --git a/Modules/FindBacktrace.cmake b/Modules/FindBacktrace.cmake index e1f45f7..cf1632a 100644 --- a/Modules/FindBacktrace.cmake +++ b/Modules/FindBacktrace.cmake @@ -5,30 +5,30 @@ FindBacktrace ------------- -Find provider for backtrace(3). +Find provider for `backtrace(3) <http://man7.org/linux/man-pages/man3/backtrace.3.html>`__. -Checks if OS supports backtrace(3) via either libc or custom library. +Checks if OS supports ``backtrace(3)`` via either ``libc`` or custom library. This module defines the following variables: ``Backtrace_HEADER`` - The header file needed for backtrace(3). Cached. + The header file needed for ``backtrace(3)``. Cached. Could be forcibly set by user. ``Backtrace_INCLUDE_DIRS`` - The include directories needed to use backtrace(3) header. + The include directories needed to use ``backtrace(3)`` header. ``Backtrace_LIBRARIES`` - The libraries (linker flags) needed to use backtrace(3), if any. + The libraries (linker flags) needed to use ``backtrace(3)``, if any. ``Backtrace_FOUND`` - Is set if and only if backtrace(3) support detected. + Is set if and only if ``backtrace(3)`` support detected. The following cache variables are also available to set or use: ``Backtrace_LIBRARY`` The external library providing backtrace, if any. ``Backtrace_INCLUDE_DIR`` - The directory holding the backtrace(3) header. + The directory holding the ``backtrace(3)`` header. -Typical usage is to generate of header file using configure_file() with the -contents like the following:: +Typical usage is to generate of header file using :command:`configure_file` +with the contents like the following:: #cmakedefine01 Backtrace_FOUND #if Backtrace_FOUND diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake index 53be493..023cc8d 100644 --- a/Modules/FindBoost.cmake +++ b/Modules/FindBoost.cmake @@ -466,8 +466,17 @@ function(_Boost_GUESS_COMPILER_PREFIX _ret) elseif (GHSMULTI) set(_boost_COMPILER "-ghs") elseif("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC" OR "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC") - if(MSVC_TOOLSET_VERSION GREATER_EQUAL 141) - set(_boost_COMPILER "-vc141;-vc140") + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 150) + # Not yet known. + set(_boost_COMPILER "") + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 140) + # MSVC toolset 14.x versions are forward compatible. + set(_boost_COMPILER "") + foreach(v 9 8 7 6 5 4 3 2 1 0) + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 14${v}) + list(APPEND _boost_COMPILER "-vc14${v}") + endif() + endforeach() elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 80) set(_boost_COMPILER "-vc${MSVC_TOOLSET_VERSION}") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.10) @@ -1045,11 +1054,17 @@ endfunction() # Some boost libraries may require particular set of compler features. # The very first one was `boost::fiber` introduced in Boost 1.62. # One can check required compiler features of it in -# `${Boost_ROOT}/libs/fiber/build/Jamfile.v2`. +# - `${Boost_ROOT}/libs/fiber/build/Jamfile.v2`; +# - `${Boost_ROOT}/libs/context/build/Jamfile.v2`. +# +# TODO (Re)Check compiler features on (every?) release ??? +# One may use the following command to get the files to check: +# +# $ find . -name Jamfile.v2 | grep build | xargs grep -l cxx1 # function(_Boost_COMPILER_FEATURES component _ret) - # Boost >= 1.62 and < 1.67 - if(NOT Boost_VERSION VERSION_LESS 106200 AND Boost_VERSION VERSION_LESS 106700) + # Boost >= 1.62 + if(NOT Boost_VERSION VERSION_LESS 106200) set(_Boost_FIBER_COMPILER_FEATURES cxx_alias_templates cxx_auto_type @@ -1063,6 +1078,8 @@ function(_Boost_COMPILER_FEATURES component _ret) cxx_thread_local cxx_variadic_templates ) + # Compiler feature for `context` same as for `fiber`. + set(_Boost_CONTEXT_COMPILER_FEATURES ${_Boost_FIBER_COMPILER_FEATURES}) endif() string(TOUPPER ${component} uppercomponent) set(${_ret} ${_Boost_${uppercomponent}_COMPILER_FEATURES} PARENT_SCOPE) @@ -1083,9 +1100,15 @@ function(_Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS component else() set(_arch_suffix 32) endif() - if(MSVC_TOOLSET_VERSION GREATER_EQUAL 141) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.1) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.0) + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 150) + # Not yet known. + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 140) + # MSVC toolset 14.x versions are forward compatible. + foreach(v 9 8 7 6 5 4 3 2 1 0) + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 14${v}) + list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.${v}) + endif() + endforeach() elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 80) math(EXPR _toolset_major_version "${MSVC_TOOLSET_VERSION} / 10") list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-${_toolset_major_version}.0) @@ -1762,7 +1785,7 @@ foreach(COMPONENT ${Boost_FIND_COMPONENTS}) list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT_NAME "${COMPONENT_UNVERSIONED}${COMPONENT_PYTHON_VERSION_MAJOR}-py${COMPONENT_PYTHON_VERSION_MAJOR}${COMPONENT_PYTHON_VERSION_MINOR}") list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT_NAME "${COMPONENT_UNVERSIONED}-py${COMPONENT_PYTHON_VERSION_MAJOR}${COMPONENT_PYTHON_VERSION_MINOR}") # Gentoo - list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT_NAME "${COMPONENT_UNVERSIONED}-${COMPONENT_PYTHON_VERSION_MAJOR}${COMPONENT_PYTHON_VERSION_MINOR}") + list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT_NAME "${COMPONENT_UNVERSIONED}-${COMPONENT_PYTHON_VERSION_MAJOR}.${COMPONENT_PYTHON_VERSION_MINOR}") # RPMs list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT_NAME "${COMPONENT_UNVERSIONED}-${COMPONENT_PYTHON_VERSION_MAJOR}${COMPONENT_PYTHON_VERSION_MINOR}") endif() diff --git a/Modules/FindCURL.cmake b/Modules/FindCURL.cmake index b1989b1..aeebc84 100644 --- a/Modules/FindCURL.cmake +++ b/Modules/FindCURL.cmake @@ -27,16 +27,16 @@ Result Variables This module defines the following variables: ``CURL_FOUND`` - True if curl found. + "True" if ``curl`` found. ``CURL_INCLUDE_DIRS`` - where to find curl/curl.h, etc. + where to find ``curl``/``curl.h``, etc. ``CURL_LIBRARIES`` - List of libraries when using curl. + List of libraries when using ``curl``. ``CURL_VERSION_STRING`` - The version of curl found. + The version of ``curl`` found. #]=======================================================================] find_package(PkgConfig QUIET) diff --git a/Modules/FindCVS.cmake b/Modules/FindCVS.cmake index 89dbc0e..f819800 100644 --- a/Modules/FindCVS.cmake +++ b/Modules/FindCVS.cmake @@ -5,7 +5,7 @@ FindCVS ------- - +Find the Concurrent Versions System (CVS). The module defines the following variables: diff --git a/Modules/FindCups.cmake b/Modules/FindCups.cmake index 2c79911..4e8232d 100644 --- a/Modules/FindCups.cmake +++ b/Modules/FindCups.cmake @@ -5,7 +5,7 @@ FindCups -------- -Find the CUPS printing system. +Find the Common UNIX Printing System (CUPS). Set ``CUPS_REQUIRE_IPP_DELETE_ATTRIBUTE`` to ``TRUE`` if you need a version which features this function (i.e. at least ``1.1.19``) diff --git a/Modules/FindCxxTest.cmake b/Modules/FindCxxTest.cmake index 4eec5fc..321f004 100644 --- a/Modules/FindCxxTest.cmake +++ b/Modules/FindCxxTest.cmake @@ -5,7 +5,7 @@ FindCxxTest ----------- -Find CxxTest +Find CxxTest unit testing framework. Find the CxxTest suite and declare a helper macro for creating unit tests and integrating them with CTest. For more details on CxxTest diff --git a/Modules/FindCygwin.cmake b/Modules/FindCygwin.cmake index 8811623..5bbc802 100644 --- a/Modules/FindCygwin.cmake +++ b/Modules/FindCygwin.cmake @@ -5,7 +5,8 @@ FindCygwin ---------- -this module looks for Cygwin +Find Cygwin, a POSIX-compatible environment that runs natively +on Microsoft Windows #]=======================================================================] if (WIN32) diff --git a/Modules/FindDCMTK.cmake b/Modules/FindDCMTK.cmake index 111e0ff..d48de08 100644 --- a/Modules/FindDCMTK.cmake +++ b/Modules/FindDCMTK.cmake @@ -5,7 +5,7 @@ FindDCMTK --------- -Find DCMTK libraries and applications +Find DICOM ToolKit (DCMTK) libraries and applications The module defines the following variables:: diff --git a/Modules/FindEXPAT.cmake b/Modules/FindEXPAT.cmake index 58e0841..15b419a 100644 --- a/Modules/FindEXPAT.cmake +++ b/Modules/FindEXPAT.cmake @@ -6,6 +6,7 @@ FindEXPAT --------- Find the native Expat headers and library. +Expat is a stream-oriented XML parser library written in C. Imported Targets ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindFLEX.cmake b/Modules/FindFLEX.cmake index 68eb9c8..09d57d2 100644 --- a/Modules/FindFLEX.cmake +++ b/Modules/FindFLEX.cmake @@ -5,7 +5,8 @@ FindFLEX -------- -Find flex executable and provides a macro to generate custom build rules +Find Fast Lexical Analyzer (Flex) executable and provides a macro +to generate custom build rules @@ -22,7 +23,7 @@ The module defines the following variables: The minimum required version of flex can be specified using the -standard syntax, e.g. find_package(FLEX 2.5.13) +standard syntax, e.g. :command:`find_package(FLEX 2.5.13)` diff --git a/Modules/FindFLTK.cmake b/Modules/FindFLTK.cmake index 89122c0..e273642 100644 --- a/Modules/FindFLTK.cmake +++ b/Modules/FindFLTK.cmake @@ -5,14 +5,14 @@ FindFLTK -------- -Find the FLTK library +Find the Fast Light Toolkit (FLTK) library Input Variables ^^^^^^^^^^^^^^^ By default this module will search for all of the FLTK components and -add them to the FLTK_LIBRARIES variable. You can limit the components -which get placed in FLTK_LIBRARIES by defining one or more of the +add them to the ``FLTK_LIBRARIES`` variable. You can limit the components +which get placed in ``FLTK_LIBRARIES`` by defining one or more of the following three options: ``FLTK_SKIP_OPENGL`` diff --git a/Modules/FindFLTK2.cmake b/Modules/FindFLTK2.cmake index 161d15c..a43f7a4 100644 --- a/Modules/FindFLTK2.cmake +++ b/Modules/FindFLTK2.cmake @@ -5,7 +5,7 @@ FindFLTK2 --------- -Find the native FLTK2 includes and library +Find the native FLTK 2.0 includes and library The following settings are defined @@ -243,4 +243,3 @@ else() endif() endif() endif() - diff --git a/Modules/FindGDAL.cmake b/Modules/FindGDAL.cmake index 8522f9b..fde84d4 100644 --- a/Modules/FindGDAL.cmake +++ b/Modules/FindGDAL.cmake @@ -5,7 +5,7 @@ FindGDAL -------- -Find GDAL. +Find Geospatial Data Abstraction Library (GDAL). IMPORTED Targets ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindGIF.cmake b/Modules/FindGIF.cmake index 9687b57..d5a143e 100644 --- a/Modules/FindGIF.cmake +++ b/Modules/FindGIF.cmake @@ -5,7 +5,7 @@ FindGIF ------- -This finds the GIF library (giflib) +This finds the Graphics Interchange Format (GIF) library (``giflib``) Imported targets ^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ Imported targets This module defines the following :prop_tgt:`IMPORTED` target: ``GIF::GIF`` - The giflib library, if found. + The ``giflib`` library, if found. Result variables ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindGLU.cmake b/Modules/FindGLU.cmake index dbec6d1..9892805 100644 --- a/Modules/FindGLU.cmake +++ b/Modules/FindGLU.cmake @@ -15,4 +15,3 @@ if (OPENGL_GLU_FOUND) set (GLU_LIBRARY ${OPENGL_LIBRARIES}) set (GLU_INCLUDE_PATH ${OPENGL_INCLUDE_DIR}) endif () - diff --git a/Modules/FindGLUT.cmake b/Modules/FindGLUT.cmake index d42db53..a22bf5b 100644 --- a/Modules/FindGLUT.cmake +++ b/Modules/FindGLUT.cmake @@ -5,7 +5,7 @@ FindGLUT -------- -try to find glut library and include files. +Find OpenGL Utility Toolkit (GLUT) library and include files. IMPORTED Targets ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindGSL.cmake b/Modules/FindGSL.cmake index db05121..da1b3c4 100644 --- a/Modules/FindGSL.cmake +++ b/Modules/FindGSL.cmake @@ -5,7 +5,7 @@ FindGSL -------- -Find the native GSL includes and libraries. +Find the native GNU Scientific Library (GSL) includes and libraries. The GNU Scientific Library (GSL) is a numerical library for C and C++ programmers. It is free software under the GNU General Public diff --git a/Modules/FindGTK.cmake b/Modules/FindGTK.cmake index 8cc6c97..552b19a 100644 --- a/Modules/FindGTK.cmake +++ b/Modules/FindGTK.cmake @@ -5,7 +5,7 @@ FindGTK ------- -try to find GTK (and glib) and GTKGLArea +Find GTK, glib and GTKGLArea :: @@ -151,6 +151,3 @@ if(UNIX) ) endif() - - - diff --git a/Modules/FindGTK2.cmake b/Modules/FindGTK2.cmake index 3bd61a9..02e96c6 100644 --- a/Modules/FindGTK2.cmake +++ b/Modules/FindGTK2.cmake @@ -5,10 +5,8 @@ FindGTK2 -------- -FindGTK2.cmake - -This module can find the GTK2 widget libraries and several of its -other optional components like gtkmm, glade, and glademm. +Find the GTK2 widget libraries and several of its +other optional components like ``gtkmm``, ``glade``, and ``glademm``. NOTE: If you intend to use version checking, CMake 2.6.2 or later is diff --git a/Modules/FindGnuTLS.cmake b/Modules/FindGnuTLS.cmake index 9c07444..4b4019c 100644 --- a/Modules/FindGnuTLS.cmake +++ b/Modules/FindGnuTLS.cmake @@ -5,7 +5,7 @@ FindGnuTLS ---------- -Try to find the GNU Transport Layer Security library (gnutls) +Find the GNU Transport Layer Security library (gnutls) diff --git a/Modules/FindHDF5.cmake b/Modules/FindHDF5.cmake index 70bfc96..08863c8 100644 --- a/Modules/FindHDF5.cmake +++ b/Modules/FindHDF5.cmake @@ -5,43 +5,44 @@ FindHDF5 -------- -Find HDF5, a library for reading and writing self describing array data. +Find Hierarchical Data Format (HDF5), a library for reading and writing +self describing array data. -This module invokes the HDF5 wrapper compiler that should be installed -alongside HDF5. Depending upon the HDF5 Configuration, the wrapper -compiler is called either h5cc or h5pcc. If this succeeds, the module -will then call the compiler with the -show argument to see what flags -are used when compiling an HDF5 client application. +This module invokes the ``HDF5`` wrapper compiler that should be installed +alongside ``HDF5``. Depending upon the ``HDF5`` Configuration, the wrapper +compiler is called either ``h5cc`` or ``h5pcc``. If this succeeds, the module +will then call the compiler with the show argument to see what flags +are used when compiling an ``HDF5`` client application. -The module will optionally accept the COMPONENTS argument. If no -COMPONENTS are specified, then the find module will default to finding -only the HDF5 C library. If one or more COMPONENTS are specified, the +The module will optionally accept the ``COMPONENTS`` argument. If no +``COMPONENTS`` are specified, then the find module will default to finding +only the ``HDF5`` C library. If one or more ``COMPONENTS`` are specified, the module will attempt to find the language bindings for the specified -components. The only valid components are C, CXX, Fortran, HL, and -Fortran_HL. If the COMPONENTS argument is not given, the module will +components. The only valid components are ``C``, ``CXX``, ``Fortran``, ``HL``, +and ``Fortran_HL``. If the ``COMPONENTS`` argument is not given, the module will attempt to find only the C bindings. This module will read the variable -HDF5_USE_STATIC_LIBRARIES to determine whether or not to prefer a -static link to a dynamic link for HDF5 and all of it's dependencies. -To use this feature, make sure that the HDF5_USE_STATIC_LIBRARIES +``HDF5_USE_STATIC_LIBRARIES`` to determine whether or not to prefer a +static link to a dynamic link for ``HDF5`` and all of it's dependencies. +To use this feature, make sure that the ``HDF5_USE_STATIC_LIBRARIES`` variable is set before the call to find_package. -To provide the module with a hint about where to find your HDF5 -installation, you can set the environment variable HDF5_ROOT. The -Find module will then look in this path when searching for HDF5 +To provide the module with a hint about where to find your ``HDF5`` +installation, you can set the environment variable ``HDF5_ROOT``. The +Find module will then look in this path when searching for ``HDF5`` executables, paths, and libraries. -Both the serial and parallel HDF5 wrappers are considered and the first +Both the serial and parallel ``HDF5`` wrappers are considered and the first directory to contain either one will be used. In the event that both appear in the same directory the serial version is preferentially selected. This -behavior can be reversed by setting the variable HDF5_PREFER_PARALLEL to -true. +behavior can be reversed by setting the variable ``HDF5_PREFER_PARALLEL`` to +``True``. In addition to finding the includes and libraries required to compile -an HDF5 client application, this module also makes an effort to find -tools that come with the HDF5 distribution that may be useful for +an ``HDF5`` client application, this module also makes an effort to find +tools that come with the ``HDF5`` distribution that may be useful for regression testing. Result Variables diff --git a/Modules/FindHSPELL.cmake b/Modules/FindHSPELL.cmake index ec077a5..9724d2c 100644 --- a/Modules/FindHSPELL.cmake +++ b/Modules/FindHSPELL.cmake @@ -5,7 +5,7 @@ FindHSPELL ---------- -Try to find Hspell +Try to find Hebrew spell-checker (Hspell) and morphology engine. Once done this will define diff --git a/Modules/FindIcotool.cmake b/Modules/FindIcotool.cmake index 32fc4ae..d19c145 100644 --- a/Modules/FindIcotool.cmake +++ b/Modules/FindIcotool.cmake @@ -7,8 +7,8 @@ FindIcotool Find icotool -This module looks for icotool. This module defines the following -values: +This module looks for icotool. Convert and create Win32 icon and cursor files. +This module defines the following values: :: diff --git a/Modules/FindImageMagick.cmake b/Modules/FindImageMagick.cmake index 2ddd11c..8bf5123 100644 --- a/Modules/FindImageMagick.cmake +++ b/Modules/FindImageMagick.cmake @@ -5,11 +5,11 @@ FindImageMagick --------------- -Find the ImageMagick binary suite. +Find ImageMagick binary suite. This module will search for a set of ImageMagick tools specified as -components in the FIND_PACKAGE call. Typical components include, but -are not limited to (future versions of ImageMagick might have +components in the :command:`find_package` call. Typical components include, +but are not limited to (future versions of ImageMagick might have additional components not listed here): :: @@ -28,7 +28,7 @@ additional components not listed here): -If no component is specified in the FIND_PACKAGE call, then it only +If no component is specified in the :command:`find_package` call, then it only searches for the ImageMagick executable directory. This code defines the following variables: @@ -43,7 +43,7 @@ the following variables: -ImageMagick_VERSION_STRING will not work for old versions like 5.2.3. +``ImageMagick_VERSION_STRING`` will not work for old versions like 5.2.3. There are also components for the following ImageMagick APIs: @@ -80,8 +80,8 @@ Example Usages: -Note that the standard FIND_PACKAGE features are supported (i.e., -QUIET, REQUIRED, etc.). +Note that the standard :command:`find_package` features are supported (i.e., +``QUIET``, ``REQUIRED``, etc.). #]=======================================================================] find_package(PkgConfig QUIET) diff --git a/Modules/FindJPEG.cmake b/Modules/FindJPEG.cmake index f50f79e..0bb6989 100644 --- a/Modules/FindJPEG.cmake +++ b/Modules/FindJPEG.cmake @@ -5,7 +5,7 @@ FindJPEG -------- -Find the JPEG library (libjpeg) +Find the Joint Photographic Experts Group (JPEG) library (``libjpeg``) Imported targets ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindKDE3.cmake b/Modules/FindKDE3.cmake index c7ad6e1..f916359 100644 --- a/Modules/FindKDE3.cmake +++ b/Modules/FindKDE3.cmake @@ -35,7 +35,7 @@ The following user adjustable options are provided: ``KDE3_BUILD_TESTS`` enable this to build KDE testcases -It also adds the following macros (from KDE3Macros.cmake) SRCS_VAR is +It also adds the following macros (from ``KDE3Macros.cmake``) ``SRCS_VAR`` is always the variable which contains the list of source files for your application or library. @@ -358,4 +358,3 @@ endif () #add the found Qt and KDE include directories to the current include path set(KDE3_INCLUDE_DIRS ${QT_INCLUDE_DIR} ${KDE3_INCLUDE_DIR}) - diff --git a/Modules/FindKDE4.cmake b/Modules/FindKDE4.cmake index c04804b..2a1838f 100644 --- a/Modules/FindKDE4.cmake +++ b/Modules/FindKDE4.cmake @@ -19,7 +19,7 @@ the given order: -Please look in FindKDE4Internal.cmake and KDE4Macros.cmake for more +Please look in ``FindKDE4Internal.cmake`` and ``KDE4Macros.cmake`` for more information. They are installed with the KDE 4 libraries in $KDEDIRS/share/apps/cmake/modules/. diff --git a/Modules/FindLAPACK.cmake b/Modules/FindLAPACK.cmake index d6646ea..6582eea 100644 --- a/Modules/FindLAPACK.cmake +++ b/Modules/FindLAPACK.cmake @@ -5,13 +5,13 @@ FindLAPACK ---------- -Find LAPACK library +Find Linear Algebra PACKage (LAPACK) library This module finds an installed fortran library that implements the LAPACK linear-algebra interface (see http://www.netlib.org/lapack/). The approach follows that taken for the autoconf macro file, -acx_lapack.m4 (distributed at +``acx_lapack.m4`` (distributed at http://ac-archive.sourceforge.net/ac-archive/acx_lapack.html). Input Variables diff --git a/Modules/FindLATEX.cmake b/Modules/FindLATEX.cmake index 01f4793..b365d63 100644 --- a/Modules/FindLATEX.cmake +++ b/Modules/FindLATEX.cmake @@ -5,9 +5,9 @@ FindLATEX --------- -Find Latex +Find LaTeX -This module finds an installed Latex and determines the location +This module finds an installed LaTeX and determines the location of the compiler. Additionally the module looks for Latex-related software like BibTeX. diff --git a/Modules/FindLTTngUST.cmake b/Modules/FindLTTngUST.cmake index a074187..9cd17eb 100644 --- a/Modules/FindLTTngUST.cmake +++ b/Modules/FindLTTngUST.cmake @@ -5,7 +5,8 @@ FindLTTngUST ------------ -This module finds the `LTTng-UST <http://lttng.org/>`__ library. +Find +`Linux Trace Toolkit Next Generation (LTTng-UST) <http://lttng.org/>`__ library. Imported target ^^^^^^^^^^^^^^^ diff --git a/Modules/FindLibArchive.cmake b/Modules/FindLibArchive.cmake index 34fc2e2..ef27b7d 100644 --- a/Modules/FindLibArchive.cmake +++ b/Modules/FindLibArchive.cmake @@ -5,7 +5,8 @@ FindLibArchive -------------- -Find libarchive library and headers +Find libarchive library and headers. +Libarchive is multi-format archive and compression library. The module defines the following variables: diff --git a/Modules/FindLibXslt.cmake b/Modules/FindLibXslt.cmake index 4cca64f..01a9d8b 100644 --- a/Modules/FindLibXslt.cmake +++ b/Modules/FindLibXslt.cmake @@ -5,7 +5,8 @@ FindLibXslt ----------- -Try to find the LibXslt library +Find the XSL Transformations, Extensible Stylesheet Language +Transformations (XSLT) library (LibXslt) Once done this will define diff --git a/Modules/FindLua.cmake b/Modules/FindLua.cmake index eb3b5fb..d229e18 100644 --- a/Modules/FindLua.cmake +++ b/Modules/FindLua.cmake @@ -7,7 +7,9 @@ FindLua -Locate Lua library This module defines +Locate Lua library. + +This module defines:: :: diff --git a/Modules/FindLua50.cmake b/Modules/FindLua50.cmake index 52a54e7..0575caa 100644 --- a/Modules/FindLua50.cmake +++ b/Modules/FindLua50.cmake @@ -7,7 +7,8 @@ FindLua50 -Locate Lua library This module defines +Locate Lua library. +This module defines:: :: @@ -87,4 +88,3 @@ include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua50 DEFAULT_MSG LUA_LIBRARIES LUA_INCLUDE_DIR) mark_as_advanced(LUA_INCLUDE_DIR LUA_LIBRARIES) - diff --git a/Modules/FindLua51.cmake b/Modules/FindLua51.cmake index 1c9029b..283a3eb 100644 --- a/Modules/FindLua51.cmake +++ b/Modules/FindLua51.cmake @@ -7,7 +7,8 @@ FindLua51 -Locate Lua library This module defines +Locate Lua library. +This module defines:: :: @@ -81,4 +82,3 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua51 VERSION_VAR LUA_VERSION_STRING) mark_as_advanced(LUA_INCLUDE_DIR LUA_LIBRARIES LUA_LIBRARY LUA_MATH_LIBRARY) - diff --git a/Modules/FindMFC.cmake b/Modules/FindMFC.cmake index 9738ac5..e366619 100644 --- a/Modules/FindMFC.cmake +++ b/Modules/FindMFC.cmake @@ -5,7 +5,7 @@ FindMFC ------- -Find MFC on Windows +Find Microsoft Foundation Class Library (MFC) on Windows Find the native MFC - i.e. decide if an application can link to the MFC libraries. diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake index 8c45a8c..5288640 100644 --- a/Modules/FindMPI.cmake +++ b/Modules/FindMPI.cmake @@ -770,18 +770,20 @@ function (_MPI_interrogate_compiler LANG) endforeach() # Add the link directories given explicitly that we haven't used back as linker directories. - foreach(_MPI_LINK_DIRECTORY IN LISTS MPI_LINK_DIRECTORIES_LEFTOVER) - file(TO_NATIVE_PATH "${_MPI_LINK_DIRECTORY}" _MPI_LINK_DIRECTORY_ACTUAL) - string(FIND "${_MPI_LINK_DIRECTORY_ACTUAL}" " " _MPI_LINK_DIRECTORY_CONTAINS_SPACE) - if(NOT _MPI_LINK_DIRECTORY_CONTAINS_SPACE EQUAL -1) - set(_MPI_LINK_DIRECTORY_ACTUAL "\"${_MPI_LINK_DIRECTORY_ACTUAL}\"") - endif() - if(MPI_LINK_FLAGS_WORK) - string(APPEND MPI_LINK_FLAGS_WORK " ${CMAKE_LIBRARY_PATH_FLAG}${_MPI_LINK_DIRECTORY_ACTUAL}") - else() - set(MPI_LINK_FLAGS_WORK "${CMAKE_LIBRARY_PATH_FLAG}${_MPI_LINK_DIRECTORY_ACTUAL}") - endif() - endforeach() + if(NOT WIN32) + foreach(_MPI_LINK_DIRECTORY IN LISTS MPI_LINK_DIRECTORIES_LEFTOVER) + file(TO_NATIVE_PATH "${_MPI_LINK_DIRECTORY}" _MPI_LINK_DIRECTORY_ACTUAL) + string(FIND "${_MPI_LINK_DIRECTORY_ACTUAL}" " " _MPI_LINK_DIRECTORY_CONTAINS_SPACE) + if(NOT _MPI_LINK_DIRECTORY_CONTAINS_SPACE EQUAL -1) + set(_MPI_LINK_DIRECTORY_ACTUAL "\"${_MPI_LINK_DIRECTORY_ACTUAL}\"") + endif() + if(MPI_LINK_FLAGS_WORK) + string(APPEND MPI_LINK_FLAGS_WORK " ${CMAKE_LIBRARY_PATH_FLAG}${_MPI_LINK_DIRECTORY_ACTUAL}") + else() + set(MPI_LINK_FLAGS_WORK "${CMAKE_LIBRARY_PATH_FLAG}${_MPI_LINK_DIRECTORY_ACTUAL}") + endif() + endforeach() + endif() # Deal with the libraries given with full path next unset(MPI_DIRECT_LIB_NAMES_WORK) diff --git a/Modules/FindOpenAL.cmake b/Modules/FindOpenAL.cmake index 18f3ff6..27dcaf5 100644 --- a/Modules/FindOpenAL.cmake +++ b/Modules/FindOpenAL.cmake @@ -6,15 +6,15 @@ FindOpenAL ---------- +Finds Open Audio Library (OpenAL). +This module defines ``OPENAL_LIBRARY OPENAL_FOUND``, if +false, do not try to link to OpenAL ``OPENAL_INCLUDE_DIR``, where to find +the headers. -Locate OpenAL This module defines OPENAL_LIBRARY OPENAL_FOUND, if -false, do not try to link to OpenAL OPENAL_INCLUDE_DIR, where to find -the headers +``$OPENALDIR`` is an environment variable that would correspond to the +``./configure --prefix=$OPENALDIR`` used in building OpenAL. -$OPENALDIR is an environment variable that would correspond to the -./configure --prefix=$OPENALDIR used in building OpenAL. - -Created by Eric Wing. This was influenced by the FindSDL.cmake +Created by Eric Wing. This was influenced by the ``FindSDL.cmake`` module. #]=======================================================================] diff --git a/Modules/FindOpenCL.cmake b/Modules/FindOpenCL.cmake index 79c0382..9891724 100644 --- a/Modules/FindOpenCL.cmake +++ b/Modules/FindOpenCL.cmake @@ -5,7 +5,7 @@ FindOpenCL ---------- -Try to find OpenCL +Finds Open Computing Language (OpenCL) IMPORTED Targets ^^^^^^^^^^^^^^^^ diff --git a/Modules/FindOpenGL.cmake b/Modules/FindOpenGL.cmake index 832dca2..23bb001d 100644 --- a/Modules/FindOpenGL.cmake +++ b/Modules/FindOpenGL.cmake @@ -5,7 +5,7 @@ FindOpenGL ---------- -FindModule for OpenGL and GLU. +FindModule for OpenGL and OpenGL Utility Library (GLU). Optional COMPONENTS ^^^^^^^^^^^^^^^^^^^ @@ -23,9 +23,9 @@ This module defines the :prop_tgt:`IMPORTED` targets: ``OpenGL::OpenGL`` Defined to libOpenGL if the system is GLVND-based. ``OpenGL::GLU`` - Defined if the system has GLU. + Defined if the system has OpenGL Utility Library (GLU). ``OpenGL::GLX`` - Defined if the system has GLX. + Defined if the system has OpenGL Extension to the X Window System (GLX). ``OpenGL::EGL`` Defined if the system has EGL. @@ -205,11 +205,13 @@ else() find_library(OPENGL_glx_LIBRARY NAMES GLX PATHS ${_OPENGL_LIB_PATH} + PATH_SUFFIXES libglvnd ) find_library(OPENGL_egl_LIBRARY NAMES EGL PATHS ${_OPENGL_LIB_PATH} + PATH_SUFFIXES libglvnd ) find_library(OPENGL_glu_LIBRARY @@ -264,6 +266,7 @@ else() /usr/openwin/lib /usr/shlib ${_OPENGL_LIB_PATH} + PATH_SUFFIXES libglvnd ) endif() diff --git a/Modules/FindOpenMP.cmake b/Modules/FindOpenMP.cmake index 5a34b9e..b909db8 100644 --- a/Modules/FindOpenMP.cmake +++ b/Modules/FindOpenMP.cmake @@ -5,7 +5,7 @@ FindOpenMP ---------- -Finds OpenMP support +Finds Open Multi-Processing (OpenMP) support. This module can be used to detect OpenMP support in a compiler. If the compiler supports OpenMP, the flags required to compile with diff --git a/Modules/FindOpenSceneGraph.cmake b/Modules/FindOpenSceneGraph.cmake index 6f7d3c8..27909bc 100644 --- a/Modules/FindOpenSceneGraph.cmake +++ b/Modules/FindOpenSceneGraph.cmake @@ -5,11 +5,11 @@ FindOpenSceneGraph ------------------ -Find OpenSceneGraph +Find OpenSceneGraph (3D graphics application programming interface) This module searches for the OpenSceneGraph core "osg" library as well -as OpenThreads, and whatever additional COMPONENTS (nodekits) that you -specify. +as :module:`FindOpenThreads`, and whatever additional ``COMPONENTS`` +(nodekits) that you specify. :: @@ -17,10 +17,11 @@ specify. -NOTE: To use this module effectively you must either require CMake >= -2.6.3 with cmake_minimum_required(VERSION 2.6.3) or download and place -FindOpenThreads.cmake, Findosg_functions.cmake, Findosg.cmake, and -Find<etc>.cmake files into your CMAKE_MODULE_PATH. +NOTE: To use this module effectively you must either require ``CMake >= +2.6.3`` with :command:`cmake_minimum_required(VERSION 2.6.3)` or download +and place :module:`FindOpenThreads`, :module:`Findosg` functions, +:module:`Findosg` and ``Find<etc>.cmake`` files into your +:variable:`CMAKE_MODULE_PATH`. ================================== @@ -40,11 +41,12 @@ This module accepts the following variables (note mixed case) The following environment variables are also respected for finding the -OSG and it's various components. CMAKE_PREFIX_PATH can also be used -for this (see find_library() CMake documentation). +OSG and it's various components. :variable:`CMAKE_PREFIX_PATH` can also be +used for this (see :command:`find_library` CMake documentation). ``<MODULE>_DIR`` - (where MODULE is of the form "OSGVOLUME" and there is a FindosgVolume.cmake file) + (where ``MODULE`` is of the form "OSGVOLUME" and there is + a :module:`FindosgVolume`.cmake` file) ``OSG_DIR`` .. ``OSGDIR`` @@ -53,7 +55,7 @@ for this (see find_library() CMake documentation). .. -[CMake 2.8.10]: The CMake variable OSG_DIR can now be used as well to +[CMake 2.8.10]: The CMake variable ``OSG_DIR`` can now be used as well to influence detection, instead of needing to specify an environment variable. diff --git a/Modules/FindPython/Support.cmake b/Modules/FindPython/Support.cmake index 0868989..8bd5eb3 100644 --- a/Modules/FindPython/Support.cmake +++ b/Modules/FindPython/Support.cmake @@ -321,9 +321,9 @@ unset (_${_PYTHON_PREFIX}_CACHED_VARS) # first step, search for the interpreter if ("Interpreter" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS) + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_EXECUTABLE) if (${_PYTHON_PREFIX}_FIND_REQUIRED_Interpreter) list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_EXECUTABLE) - list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_EXECUTABLE) endif() set (_${_PYTHON_PREFIX}_HINTS "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR) @@ -589,9 +589,9 @@ endif() # second step, search for compiler (IronPython) if ("Compiler" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS) + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_COMPILER) if (${_PYTHON_PREFIX}_FIND_REQUIRED_Compiler) list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_COMPILER) - list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_COMPILER) endif() # IronPython specific artifacts @@ -700,15 +700,15 @@ endif() ## Development environment is not compatible with IronPython interpreter if ("Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS AND NOT ${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "IronPython") + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_LIBRARY + ${_PYTHON_PREFIX}_LIBRARY_RELEASE + ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE + ${_PYTHON_PREFIX}_LIBRARY_DEBUG + ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG + ${_PYTHON_PREFIX}_INCLUDE_DIR) if (${_PYTHON_PREFIX}_FIND_REQUIRED_Development) list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_LIBRARY ${_PYTHON_PREFIX}_INCLUDE_DIR) - list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_LIBRARY - ${_PYTHON_PREFIX}_LIBRARY_RELEASE - ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE - ${_PYTHON_PREFIX}_LIBRARY_DEBUG - ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG - ${_PYTHON_PREFIX}_INCLUDE_DIR) endif() # Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES @@ -1182,9 +1182,9 @@ if ("Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS endif() if ("NumPy" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS AND ${_PYTHON_PREFIX}_Interpreter_FOUND) + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR) if (${_PYTHON_PREFIX}_FIND_REQUIRED_NumPy) list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR) - list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR) endif() execute_process( COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c @@ -1213,6 +1213,10 @@ if ("NumPy" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS AND ${_PYTHON_PREFIX}_Inte set(${_PYTHON_PREFIX}_NumPy_VERSION "${_${_PYTHON_PREFIX}_NumPy_VERSION}") endif() endif() + # final step: set NumPy founded only if Development component is founded as well + if (NOT ${_PYTHON_PREFIX}_Development_FOUND) + set(${_PYTHON_PREFIX}_NumPy_FOUND FALSE) + endif() endif() # final validation diff --git a/Modules/FindQt3.cmake b/Modules/FindQt3.cmake index 4a8e28b..563ed46 100644 --- a/Modules/FindQt3.cmake +++ b/Modules/FindQt3.cmake @@ -101,7 +101,7 @@ if (QT_MT_REQUIRED) /usr/share/qt3 C:/Progra~1/qt PATH_SUFFIXES - lib/qt lib/qt3 qt qt3 qt/lib qt3/lib + lib lib/qt lib/qt3 qt qt3 qt/lib qt3/lib ) else () @@ -119,7 +119,7 @@ else () /usr/share/qt3 C:/Progra~1/qt/lib PATH_SUFFIXES - lib/qt lib/qt3 qt qt3 qt/lib qt3/lib + lib lib/qt lib/qt3 qt qt3 qt/lib qt3/lib ) endif () @@ -135,7 +135,7 @@ find_library(QT_QASSISTANTCLIENT_LIBRARY /usr/share/qt3 C:/Progra~1/qt PATH_SUFFIXES - lib/qt lib/qt3 qt qt3 qt/lib qt3/lib + lib lib/qt lib/qt3 qt qt3 qt/lib qt3/lib ) # Qt 3 should prefer QTDIR over the PATH @@ -151,7 +151,7 @@ find_program(QT_MOC_EXECUTABLE /usr/share/qt3 C:/Progra~1/qt PATH_SUFFIXES - lib/qt lib/qt3 qt qt3 qt/lib qt3/lib + bin lib/qt lib/qt3 qt qt3 qt/bin qt3/bin lib/qt/bin lib/qt3/bin ) if(QT_MOC_EXECUTABLE) @@ -171,7 +171,7 @@ find_program(QT_UIC_EXECUTABLE /usr/share/qt3 C:/Progra~1/qt PATH_SUFFIXES - lib/qt lib/qt3 qt qt3 qt/lib qt3/lib + bin lib/qt lib/qt3 qt qt3 qt/bin qt3/bin lib/qt/bin lib/qt3/bin ) if(QT_UIC_EXECUTABLE) @@ -188,6 +188,8 @@ if (WIN32) PATHS "$ENV{ProgramFiles}/qt" "C:/Program Files/qt" + PATH_SUFFIXES + lib DOC "This Library is only needed by and included with Qt3 on MSWindows. It should be NOTFOUND, undefined or IGNORE otherwise." ) endif () diff --git a/Modules/FindSWIG.cmake b/Modules/FindSWIG.cmake index 49f303e..a5e3a37 100644 --- a/Modules/FindSWIG.cmake +++ b/Modules/FindSWIG.cmake @@ -5,13 +5,13 @@ FindSWIG -------- -Find SWIG +Find Simplified Wrapper and Interface Generator (SWIG) This module finds an installed SWIG. It sets the following variables: :: - SWIG_FOUND - set to true if SWIG is found + SWIG_FOUND - set to "True" if SWIG is found SWIG_DIR - the directory where swig is installed SWIG_EXECUTABLE - the path to the swig executable SWIG_VERSION - the version number of the swig executable diff --git a/Modules/FindVulkan.cmake b/Modules/FindVulkan.cmake index b1201b4..ae8d72d 100644 --- a/Modules/FindVulkan.cmake +++ b/Modules/FindVulkan.cmake @@ -5,7 +5,8 @@ FindVulkan ---------- -Try to find Vulkan +Find Vulkan, which isis a low-overhead, cross-platform 3D graphics +and computing API. IMPORTED Targets ^^^^^^^^^^^^^^^^ @@ -18,7 +19,7 @@ Result Variables This module defines the following variables:: - Vulkan_FOUND - True if Vulkan was found + Vulkan_FOUND - "True" if Vulkan was found Vulkan_INCLUDE_DIRS - include directories for Vulkan Vulkan_LIBRARIES - link against this library to use Vulkan diff --git a/Modules/Findosg.cmake b/Modules/Findosg.cmake index bb28454..027f315 100644 --- a/Modules/Findosg.cmake +++ b/Modules/Findosg.cmake @@ -7,8 +7,6 @@ Findosg - - NOTE: It is highly recommended that you use the new FindOpenSceneGraph.cmake introduced in CMake 2.6.3 and not use this Find module directly. diff --git a/Modules/FindosgDB.cmake b/Modules/FindosgDB.cmake index d0789ba..a28f650 100644 --- a/Modules/FindosgDB.cmake +++ b/Modules/FindosgDB.cmake @@ -7,30 +7,38 @@ FindosgDB -This is part of the Findosg* suite used to find OpenSceneGraph +This is part of the ``Findosg*`` suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular -module (perhaps because the default FindOpenGL.cmake module doesn't +module (perhaps because the default :module:`FindOpenGL` module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the -FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules. +:module:`FindOpenSceneGraph` instead of the ``Findosg*.cmake`` modules. -Locate osgDB This module defines +Locate osgDB This module defines: -OSGDB_FOUND - Was osgDB found? OSGDB_INCLUDE_DIR - Where to find the -headers OSGDB_LIBRARIES - The libraries to link against for the osgDB -(use this) +``OSGDB_FOUND`` + Was osgDB found? -OSGDB_LIBRARY - The osgDB library OSGDB_LIBRARY_DEBUG - The osgDB -debug library +``OSGDB_INCLUDE_DIR`` + Where to find the headers -$OSGDIR is an environment variable that would correspond to the -./configure --prefix=$OSGDIR used in building osg. +``OSGDB_LIBRARIES`` + The libraries to link against for the osgDB + +``OSGDB_LIBRARY`` + The osgDB library + +``OSGDB_LIBRARY_DEBUG`` + The osgDB debug library + +``$OSGDIR`` is an environment variable that would correspond to:: + + ./configure --prefix=$OSGDIR used in building osg. -Created by Eric Wing. #]=======================================================================] # Header files are presumed to be included like diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake index 2f34a7a..0a98895 100644 --- a/Modules/InstallRequiredSystemLibraries.cmake +++ b/Modules/InstallRequiredSystemLibraries.cmake @@ -213,10 +213,13 @@ if(MSVC) elseif(MSVC_VERSION_VERSION GREATER_EQUAL 143) message(WARNING "MSVC toolset v${MSVC_VERSION_VERSION} not yet supported.") elseif(MSVC_TOOLSET_VERSION EQUAL 142) - # FIXME: VS 2019 RC 4 uses VC141 but an update will fix it to be VC142. - set(MSVC_REDIST_NAME VC141) + set(MSVC_REDIST_NAME VC142) set(_MSVC_DLL_VERSION 140) set(_MSVC_IDE_VERSION 16) + if(MSVC_VERSION EQUAL 1920) + # VS2019 named this differently prior to update 1. + set(MSVC_REDIST_NAME VC141) + endif() elseif(MSVC_TOOLSET_VERSION EQUAL 141) set(MSVC_REDIST_NAME VC141) set(_MSVC_DLL_VERSION 140) diff --git a/Modules/Platform/Windows-Intel-Fortran.cmake b/Modules/Platform/Windows-Intel-Fortran.cmake index 3981a09..e3804fb 100644 --- a/Modules/Platform/Windows-Intel-Fortran.cmake +++ b/Modules/Platform/Windows-Intel-Fortran.cmake @@ -4,8 +4,41 @@ set(_COMPILE_Fortran " /fpp") set(CMAKE_Fortran_MODDIR_FLAG "-module:") set(CMAKE_Fortran_STANDARD_LIBRARIES_INIT "user32.lib") __windows_compiler_intel(Fortran) -string(APPEND CMAKE_Fortran_FLAGS_INIT " /W1 /nologo /fpp /libs:dll /threads") -string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " /Od /debug:full /dbglibs") +if(CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT) + set(_LIBSDLL "") + set(_DBGLIBS "") + set(_THREADS "") +else() + set(_LIBSDLL " /libs:dll") + set(_DBGLIBS " /dbglibs") + set(_THREADS " /threads") +endif() + +cmake_policy(GET CMP0092 _cmp0092) +if(NOT _cmp0092 STREQUAL "NEW") + string(APPEND CMAKE_Fortran_FLAGS_INIT " /W1") +endif() +unset(_cmp0092) + +string(APPEND CMAKE_Fortran_FLAGS_INIT " /nologo /fpp${_LIBSDLL}${_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") +unset(_LIBSDLL) +unset(_DBGLIBS) +unset(_THREADS) + +set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreaded -threads -libs:static) +set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDLL -threads -libs:dll) +set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebug -threads -libs:static -dbglibs) +set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebugDLL -threads -libs:dll -dbglibs) + +# Intel Fortran for Windows supports single-threaded RTL but it is +# not implemented by the Visual Studio integration. +if(NOT CMAKE_GENERATOR MATCHES "Visual Studio") + set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_SingleThreaded -libs:static) + set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_SingleThreadedDLL -libs:dll) + set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_SingleThreadedDebug -libs:static -dbglibs) + set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_SingleThreadedDebugDLL -libs:dll -dbglibs) +endif() diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake index df3bd1e..ed0e7fb 100644 --- a/Modules/Platform/Windows-MSVC.cmake +++ b/Modules/Platform/Windows-MSVC.cmake @@ -298,6 +298,14 @@ endforeach() string(APPEND CMAKE_STATIC_LINKER_FLAGS_INIT " ${_MACHINE_ARCH_FLAG}") unset(_MACHINE_ARCH_FLAG) +cmake_policy(GET CMP0091 __WINDOWS_MSVC_CMP0091) +if(__WINDOWS_MSVC_CMP0091 STREQUAL "NEW") + set(CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL") +else() + set(CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT "") +endif() +unset(__WINDOWS_MSVC_CMP0091) + macro(__windows_compiler_msvc lang) if(NOT MSVC_VERSION LESS 1400) # for 2005 make sure the manifest is put in the dll with mt @@ -351,21 +359,48 @@ macro(__windows_compiler_msvc lang) if("x${lang}" STREQUAL "xC" OR "x${lang}" STREQUAL "xCXX") + if(CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT) + set(_MDd "") + set(_MD "") + else() + set(_MDd " /MDd") + set(_MD " /MD") + endif() + + cmake_policy(GET CMP0092 _cmp0092) + if(_cmp0092 STREQUAL "NEW") + set(_W3 "") + set(_Wall "") + else() + set(_W3 " /W3") + set(_Wall " -Wall") + endif() + unset(_cmp0092) + 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 " /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 + 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 "${_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 " /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") + string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} /D_WINDOWS${_W3}${_FLAGS_${lang}}") + string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT "${_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() + unset(_Wall) + unset(_W3) + unset(_MDd) + unset(_MD) + + set(CMAKE_${lang}_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreaded -MT) + set(CMAKE_${lang}_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDLL -MD) + set(CMAKE_${lang}_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebug -MTd) + set(CMAKE_${lang}_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebugDLL -MDd) endif() set(CMAKE_${lang}_LINKER_SUPPORTS_PDB ON) set(CMAKE_NINJA_DEPTYPE_${lang} msvc) diff --git a/Modules/Platform/Windows-NVIDIA-CUDA.cmake b/Modules/Platform/Windows-NVIDIA-CUDA.cmake index 6a2667a..f160c7b 100644 --- a/Modules/Platform/Windows-NVIDIA-CUDA.cmake +++ b/Modules/Platform/Windows-NVIDIA-CUDA.cmake @@ -60,11 +60,20 @@ unset(__IMPLICT_DLINK_FLAGS) string(REPLACE "/D" "-D" _PLATFORM_DEFINES_CUDA "${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_CXX}") -string(APPEND CMAKE_CUDA_FLAGS_INIT " ${PLATFORM_DEFINES_CUDA} -D_WINDOWS -Xcompiler=\"/W3${_FLAGS_CXX}\"") +cmake_policy(GET CMP0092 _cmp0092) +if(_cmp0092 STREQUAL "NEW") + set(_W3 "") +else() + set(_W3 "/W3") +endif() +unset(_cmp0092) + +string(APPEND CMAKE_CUDA_FLAGS_INIT " ${PLATFORM_DEFINES_CUDA} -D_WINDOWS -Xcompiler=\"${_W3}${_FLAGS_CXX}\"") string(APPEND CMAKE_CUDA_FLAGS_DEBUG_INIT " -Xcompiler=\"-MDd -Zi -Ob0 -Od ${_RTC1}\"") string(APPEND CMAKE_CUDA_FLAGS_RELEASE_INIT " -Xcompiler=\"-MD -O2 -Ob2\" -DNDEBUG") string(APPEND CMAKE_CUDA_FLAGS_RELWITHDEBINFO_INIT " -Xcompiler=\"-MD -Zi -O2 -Ob1\" -DNDEBUG") string(APPEND CMAKE_CUDA_FLAGS_MINSIZEREL_INIT " -Xcompiler=\"-MD -O1 -Ob1\" -DNDEBUG") +unset(_W3) set(CMAKE_CUDA_STANDARD_LIBRARIES_INIT "${CMAKE_C_STANDARD_LIBRARIES_INIT}") diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index 924d997..01c6cd7 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -264,6 +264,8 @@ set(SRCS cmGeneratorExpression.h cmGeneratorTarget.cxx cmGeneratorTarget.h + cmGetPipes.cxx + cmGetPipes.h cmGlobalCommonGenerator.cxx cmGlobalCommonGenerator.h cmGlobalGenerator.cxx @@ -350,8 +352,8 @@ set(SRCS cmQtAutoGenGlobalInitializer.h cmQtAutoGenInitializer.cxx cmQtAutoGenInitializer.h - cmQtAutoGeneratorMocUic.cxx - cmQtAutoGeneratorMocUic.h + cmQtAutoMocUic.cxx + cmQtAutoMocUic.h cmQtAutoRcc.cxx cmQtAutoRcc.h cmRST.cxx @@ -386,11 +388,14 @@ set(SRCS cmUuid.cxx cmUVHandlePtr.cxx cmUVHandlePtr.h + cmUVStreambuf.h cmUVSignalHackRAII.h cmVariableWatch.cxx cmVariableWatch.h cmVersion.cxx cmVersion.h + cmWorkerPool.cxx + cmWorkerPool.h cmWorkingDirectory.cxx cmWorkingDirectory.h cmXMLParser.cxx diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake index 70c44e1..dd166e0 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 14) -set(CMake_VERSION_PATCH 20190412) +set(CMake_VERSION_PATCH 20190501) #set(CMake_VERSION_RC 1) diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx index a7d4455..9ad9669 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.cxx +++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx @@ -126,11 +126,12 @@ public: cmSystemTools::SetStdoutCallback([&s](std::string const& m) { s += m; }); cmSystemTools::SetStderrCallback([&s](std::string const& m) { s += m; }); - this->CM.SetProgressCallback( - [&s](const std::string& msg, float /*unused*/) { + this->CM.SetProgressCallback([&s](const std::string& msg, float prog) { + if (prog < 0) { s += msg; s += "\n"; - }); + } + }); } ~cmCTestBuildAndTestCaptureRAII() diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx index e3b7e9e..5cfc4a7 100644 --- a/Source/CTest/cmCTestUpdateHandler.cxx +++ b/Source/CTest/cmCTestUpdateHandler.cxx @@ -199,6 +199,10 @@ int cmCTestUpdateHandler::ProcessHandler() xml.Element("UpdateCommand", vc->GetUpdateCommandLine()); xml.Element("UpdateType", cmCTestUpdateHandlerUpdateToString(this->UpdateType)); + std::string changeId = this->CTest->GetCTestConfiguration("ChangeId"); + if (!changeId.empty()) { + xml.Element("ChangeId", changeId); + } bool loadedMods = vc->WriteXML(xml); diff --git a/Source/CTest/cmCTestUploadHandler.cxx b/Source/CTest/cmCTestUploadHandler.cxx index ee9ee91..9efdf70 100644 --- a/Source/CTest/cmCTestUploadHandler.cxx +++ b/Source/CTest/cmCTestUploadHandler.cxx @@ -51,7 +51,7 @@ int cmCTestUploadHandler::ProcessHandler() this->CTest->GetTestModelString()); xml.Attribute("Name", this->CTest->GetCTestConfiguration("Site")); xml.Attribute("Generator", - std::string("ctest") + cmVersion::GetCMakeVersion()); + std::string("ctest-") + cmVersion::GetCMakeVersion()); this->CTest->AddSiteProperties(xml); xml.StartElement("Upload"); diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx index bfe8d70..a2c30bb 100644 --- a/Source/CTest/cmProcess.cxx +++ b/Source/CTest/cmProcess.cxx @@ -5,61 +5,19 @@ #include "cmCTest.h" #include "cmCTestRunTest.h" #include "cmCTestTestHandler.h" +#include "cmGetPipes.h" #include "cmsys/Process.h" -#include <fcntl.h> #include <iostream> #include <signal.h> #include <string> #if defined(_WIN32) # include "cm_kwiml.h" -#else -# include <unistd.h> #endif #include <utility> #define CM_PROCESS_BUF_SIZE 65536 -#if defined(_WIN32) && !defined(__CYGWIN__) -# include <io.h> - -static int cmProcessGetPipes(int* fds) -{ - SECURITY_ATTRIBUTES attr; - HANDLE readh, writeh; - attr.nLength = sizeof(attr); - attr.lpSecurityDescriptor = nullptr; - attr.bInheritHandle = FALSE; - if (!CreatePipe(&readh, &writeh, &attr, 0)) - return uv_translate_sys_error(GetLastError()); - fds[0] = _open_osfhandle((intptr_t)readh, 0); - fds[1] = _open_osfhandle((intptr_t)writeh, 0); - if (fds[0] == -1 || fds[1] == -1) { - CloseHandle(readh); - CloseHandle(writeh); - return uv_translate_sys_error(GetLastError()); - } - return 0; -} -#else -# include <errno.h> - -static int cmProcessGetPipes(int* fds) -{ - if (pipe(fds) == -1) { - return uv_translate_sys_error(errno); - } - - if (fcntl(fds[0], F_SETFD, FD_CLOEXEC) == -1 || - fcntl(fds[1], F_SETFD, FD_CLOEXEC) == -1) { - close(fds[0]); - close(fds[1]); - return uv_translate_sys_error(errno); - } - return 0; -} -#endif - cmProcess::cmProcess(cmCTestRunTest& runner) : Runner(runner) , Conv(cmProcessOutput::UTF8, CM_PROCESS_BUF_SIZE) @@ -120,7 +78,7 @@ bool cmProcess::StartProcess(uv_loop_t& loop, std::vector<size_t>* affinity) pipe_reader.init(loop, 0, this); int fds[2] = { -1, -1 }; - status = cmProcessGetPipes(fds); + status = cmGetPipes(fds); if (status != 0) { cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE, "Error initializing pipe: " << uv_strerror(status) diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx index 709feac..003ebdc 100644 --- a/Source/cmCTest.cxx +++ b/Source/cmCTest.cxx @@ -1523,7 +1523,7 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml, this->Impl->CurrentTag + "-" + this->GetTestModelString()); xml.Attribute("Name", this->GetCTestConfiguration("Site")); xml.Attribute("Generator", - std::string("ctest") + cmVersion::GetCMakeVersion()); + std::string("ctest-") + cmVersion::GetCMakeVersion()); this->AddSiteProperties(xml); xml.StartElement("Notes"); diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx index dcb1ff5..897f7a8 100644 --- a/Source/cmCoreTryCompile.cxx +++ b/Source/cmCoreTryCompile.cxx @@ -20,6 +20,7 @@ #include "cmSystemTools.h" #include "cmTarget.h" #include "cmVersion.h" +#include "cm_static_string_view.hxx" #include "cmake.h" static std::string const kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN = @@ -42,6 +43,8 @@ static std::string const kCMAKE_LINK_SEARCH_END_STATIC = "CMAKE_LINK_SEARCH_END_STATIC"; static std::string const kCMAKE_LINK_SEARCH_START_STATIC = "CMAKE_LINK_SEARCH_START_STATIC"; +static std::string const kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT = + "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT"; static std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES"; static std::string const kCMAKE_OSX_DEPLOYMENT_TARGET = "CMAKE_OSX_DEPLOYMENT_TARGET"; @@ -500,6 +503,13 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def); } + /* Set MSVC runtime library policy to match our selection. */ + if (const char* msvcRuntimeLibraryDefault = + this->Makefile->GetDefinition(kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)) { + fprintf(fout, "cmake_policy(SET CMP0091 %s)\n", + *msvcRuntimeLibraryDefault ? "NEW" : "OLD"); + } + std::string projectLangs; for (std::string const& li : testLangs) { projectLangs += " " + li; @@ -660,6 +670,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, vars.insert(kCMAKE_SYSROOT_COMPILE); vars.insert(kCMAKE_SYSROOT_LINK); vars.insert(kCMAKE_WARN_DEPRECATED); + vars.emplace("CMAKE_MSVC_RUNTIME_LIBRARY"_s); if (const char* varListStr = this->Makefile->GetDefinition( kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) { diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx index ff6340f..0d9859e 100644 --- a/Source/cmExecuteProcessCommand.cxx +++ b/Source/cmExecuteProcessCommand.cxx @@ -6,11 +6,13 @@ #include "cmsys/Process.h" #include <algorithm> #include <ctype.h> /* isspace */ +#include <iostream> #include <stdio.h> #include "cmAlgorithms.h" #include "cmArgumentParser.h" #include "cmMakefile.h" +#include "cmMessageType.h" #include "cmProcessOutput.h" #include "cmSystemTools.h" @@ -47,6 +49,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, std::string OutputFile; std::string ErrorFile; std::string Timeout; + std::string CommandEcho; bool OutputQuiet = false; bool ErrorQuiet = false; bool OutputStripTrailingWhitespace = false; @@ -57,6 +60,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, static auto const parser = cmArgumentParser<Arguments>{} .Bind("COMMAND"_s, &Arguments::Commands) + .Bind("COMMAND_ECHO"_s, &Arguments::CommandEcho) .Bind("OUTPUT_VARIABLE"_s, &Arguments::OutputVariable) .Bind("ERROR_VARIABLE"_s, &Arguments::ErrorVariable) .Bind("RESULT_VARIABLE"_s, &Arguments::ResultVariable) @@ -117,9 +121,10 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, return false; } } - // Create a process instance. - cmsysProcess* cp = cmsysProcess_New(); + std::unique_ptr<cmsysProcess, void (*)(cmsysProcess*)> cp_ptr( + cmsysProcess_New(), cmsysProcess_Delete); + cmsysProcess* cp = cp_ptr.get(); // Set the command sequence. for (std::vector<std::string> const& cmd : arguments.Commands) { @@ -169,6 +174,51 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, cmsysProcess_SetTimeout(cp, timeout); } + bool echo_stdout = false; + bool echo_stderr = false; + bool echo_output_from_variable = true; + std::string echo_output = + this->Makefile->GetSafeDefinition("CMAKE_EXECUTE_PROCESS_COMMAND_ECHO"); + if (!arguments.CommandEcho.empty()) { + echo_output_from_variable = false; + echo_output = arguments.CommandEcho; + } + + if (!echo_output.empty()) { + if (echo_output == "STDERR") { + echo_stderr = true; + } else if (echo_output == "STDOUT") { + echo_stdout = true; + } else if (echo_output != "NONE") { + std::string error; + if (echo_output_from_variable) { + error = "CMAKE_EXECUTE_PROCESS_COMMAND_ECHO set to '"; + } else { + error = " called with '"; + } + error += echo_output; + error += "' expected STDERR|STDOUT|NONE"; + if (!echo_output_from_variable) { + error += " for COMMAND_ECHO."; + } + this->Makefile->IssueMessage(MessageType::FATAL_ERROR, error); + return true; + } + } + if (echo_stdout || echo_stderr) { + std::string command; + for (auto& cmd : arguments.Commands) { + command += "'"; + command += cmJoin(cmd, "' '"); + command += "'"; + command += "\n"; + } + if (echo_stdout) { + std::cout << command; + } else if (echo_stderr) { + std::cerr << command; + } + } // Start the process. cmsysProcess_Execute(cp); @@ -297,9 +347,6 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, } } - // Delete the process instance. - cmsysProcess_Delete(cp); - return true; } diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx index af409e4..8803830 100644 --- a/Source/cmGeneratorExpressionNode.cxx +++ b/Source/cmGeneratorExpressionNode.cxx @@ -1600,10 +1600,16 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode reportError(context, content->GetOriginalExpression(), e.str()); return std::string(); } - if (gt->GetType() != cmStateEnums::OBJECT_LIBRARY) { + cmStateEnums::TargetType type = gt->GetType(); + if (type != cmStateEnums::EXECUTABLE && + type != cmStateEnums::STATIC_LIBRARY && + type != cmStateEnums::SHARED_LIBRARY && + type != cmStateEnums::MODULE_LIBRARY && + type != cmStateEnums::OBJECT_LIBRARY) { std::ostringstream e; e << "Objects of target \"" << tgtName - << "\" referenced but is not an OBJECT library."; + << "\" referenced but is not an allowed library types (EXECUTABLE, " + << "STATIC, SHARED, MODULE, OBJECT)."; reportError(context, content->GetOriginalExpression(), e.str()); return std::string(); } @@ -2210,8 +2216,8 @@ struct TargetOutputNameArtifactResultGetter<ArtifactLinkerTag> // The file used to link to the target (.so, .lib, .a). if (!target->IsLinkable()) { ::reportError(context, content->GetOriginalExpression(), - "TARGET_LINKER_OUTPUT_NAME is allowed only for libraries " - "and executables with ENABLE_EXPORTS."); + "TARGET_LINKER_FILE_BASE_NAME is allowed only for " + "libraries and executables with ENABLE_EXPORTS."); return std::string(); } cmStateEnums::ArtifactType artifact = @@ -2232,7 +2238,7 @@ struct TargetOutputNameArtifactResultGetter<ArtifactPdbTag> if (target->IsImported()) { ::reportError( context, content->GetOriginalExpression(), - "TARGET_PDB_OUTPUT_NAME not allowed for IMPORTED targets."); + "TARGET_PDB_FILE_BASE_NAME not allowed for IMPORTED targets."); return std::string(); } @@ -2243,7 +2249,7 @@ struct TargetOutputNameArtifactResultGetter<ArtifactPdbTag> if (!context->LG->GetMakefile()->IsOn(pdbSupportVar)) { ::reportError( context, content->GetOriginalExpression(), - "TARGET_PDB_OUTPUT_NAME is not supported by the target linker."); + "TARGET_PDB_FILE_BASE_NAME is not supported by the target linker."); return std::string(); } @@ -2253,7 +2259,7 @@ struct TargetOutputNameArtifactResultGetter<ArtifactPdbTag> targetType != cmStateEnums::MODULE_LIBRARY && targetType != cmStateEnums::EXECUTABLE) { ::reportError(context, content->GetOriginalExpression(), - "TARGET_PDB_OUTPUT_NAME is allowed only for " + "TARGET_PDB_FILE_BASE_NAME is allowed only for " "targets with linker created artifacts."); return std::string(); } @@ -2263,9 +2269,9 @@ struct TargetOutputNameArtifactResultGetter<ArtifactPdbTag> }; template <typename ArtifactT> -struct TargetOutputNameArtifact : public TargetArtifactBase +struct TargetFileBaseNameArtifact : public TargetArtifactBase { - TargetOutputNameArtifact() {} // NOLINT(modernize-use-equals-default) + TargetFileBaseNameArtifact() {} // NOLINT(modernize-use-equals-default) int NumExpectedParameters() const override { return 1; } @@ -2290,12 +2296,12 @@ struct TargetOutputNameArtifact : public TargetArtifactBase } }; -static const TargetOutputNameArtifact<ArtifactNameTag> targetOutputNameNode; - -static const TargetOutputNameArtifact<ArtifactLinkerTag> - targetLinkerOutputNameNode; - -static const TargetOutputNameArtifact<ArtifactPdbTag> targetPdbOutputNameNode; +static const TargetFileBaseNameArtifact<ArtifactNameTag> + targetFileBaseNameNode; +static const TargetFileBaseNameArtifact<ArtifactLinkerTag> + targetLinkerFileBaseNameNode; +static const TargetFileBaseNameArtifact<ArtifactPdbTag> + targetPdbFileBaseNameNode; class ArtifactFilePrefixTag; class ArtifactLinkerFilePrefixTag; @@ -2474,6 +2480,9 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode( { "TARGET_LINKER_FILE", &targetLinkerNodeGroup.File }, { "TARGET_SONAME_FILE", &targetSoNameNodeGroup.File }, { "TARGET_PDB_FILE", &targetPdbNodeGroup.File }, + { "TARGET_FILE_BASE_NAME", &targetFileBaseNameNode }, + { "TARGET_LINKER_FILE_BASE_NAME", &targetLinkerFileBaseNameNode }, + { "TARGET_PDB_FILE_BASE_NAME", &targetPdbFileBaseNameNode }, { "TARGET_FILE_PREFIX", &targetFilePrefixNode }, { "TARGET_LINKER_FILE_PREFIX", &targetLinkerFilePrefixNode }, { "TARGET_FILE_SUFFIX", &targetFileSuffixNode }, @@ -2488,9 +2497,6 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode( { "TARGET_PDB_FILE_DIR", &targetPdbNodeGroup.FileDir }, { "TARGET_BUNDLE_DIR", &targetBundleDirNode }, { "TARGET_BUNDLE_CONTENT_DIR", &targetBundleContentDirNode }, - { "TARGET_OUTPUT_NAME", &targetOutputNameNode }, - { "TARGET_LINKER_OUTPUT_NAME", &targetLinkerOutputNameNode }, - { "TARGET_PDB_OUTPUT_NAME", &targetPdbOutputNameNode }, { "STREQUAL", &strEqualNode }, { "EQUAL", &equalNode }, { "IN_LIST", &inListNode }, diff --git a/Source/cmGetPipes.cxx b/Source/cmGetPipes.cxx new file mode 100644 index 0000000..ad323f7 --- /dev/null +++ b/Source/cmGetPipes.cxx @@ -0,0 +1,48 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmGetPipes.h" + +#include "cm_uv.h" + +#include <fcntl.h> + +#if defined(_WIN32) && !defined(__CYGWIN__) +# include <io.h> + +int cmGetPipes(int* fds) +{ + SECURITY_ATTRIBUTES attr; + HANDLE readh, writeh; + attr.nLength = sizeof(attr); + attr.lpSecurityDescriptor = nullptr; + attr.bInheritHandle = FALSE; + if (!CreatePipe(&readh, &writeh, &attr, 0)) + return uv_translate_sys_error(GetLastError()); + fds[0] = _open_osfhandle((intptr_t)readh, 0); + fds[1] = _open_osfhandle((intptr_t)writeh, 0); + if (fds[0] == -1 || fds[1] == -1) { + CloseHandle(readh); + CloseHandle(writeh); + return uv_translate_sys_error(GetLastError()); + } + return 0; +} +#else +# include <errno.h> +# include <unistd.h> + +int cmGetPipes(int* fds) +{ + if (pipe(fds) == -1) { + return uv_translate_sys_error(errno); + } + + if (fcntl(fds[0], F_SETFD, FD_CLOEXEC) == -1 || + fcntl(fds[1], F_SETFD, FD_CLOEXEC) == -1) { + close(fds[0]); + close(fds[1]); + return uv_translate_sys_error(errno); + } + return 0; +} +#endif diff --git a/Source/cmGetPipes.h b/Source/cmGetPipes.h new file mode 100644 index 0000000..2a46b51 --- /dev/null +++ b/Source/cmGetPipes.h @@ -0,0 +1,8 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmGetPipes_h +#define cmGetPipes_h + +int cmGetPipes(int* fds); + +#endif diff --git a/Source/cmGhsMultiGpj.cxx b/Source/cmGhsMultiGpj.cxx index 8b69b51..da27971 100644 --- a/Source/cmGhsMultiGpj.cxx +++ b/Source/cmGhsMultiGpj.cxx @@ -9,7 +9,8 @@ static const char* GHS_TAG[] = { "[INTEGRITY Application]", "[Project]", "[Program]", "[Reference]", - "[Subproject]" }; + "[Subproject]", + "[Custom Target]" }; const char* GhsMultiGpj::GetGpjTag(Types gpjType) { @@ -21,6 +22,7 @@ const char* GhsMultiGpj::GetGpjTag(Types gpjType) case PROGRAM: case REFERENCE: case SUBPROJECT: + case CUSTOM_TARGET: tag = GHS_TAG[gpjType]; break; default: diff --git a/Source/cmGhsMultiGpj.h b/Source/cmGhsMultiGpj.h index 420eab1..e588150 100644 --- a/Source/cmGhsMultiGpj.h +++ b/Source/cmGhsMultiGpj.h @@ -16,7 +16,8 @@ public: PROJECT, PROGRAM, REFERENCE, - SUBPROJECT + SUBPROJECT, + CUSTOM_TARGET }; static void WriteGpjTag(Types gpjType, std::ostream& fout); diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx index 668bcbd..b80da72 100644 --- a/Source/cmGhsMultiTargetGenerator.cxx +++ b/Source/cmGhsMultiTargetGenerator.cxx @@ -3,7 +3,7 @@ #include "cmGhsMultiTargetGenerator.h" #include "cmCustomCommand.h" -#include "cmCustomCommandLines.h" +#include "cmCustomCommandGenerator.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" #include "cmGlobalGhsMultiGenerator.h" @@ -11,17 +11,17 @@ #include "cmLocalGenerator.h" #include "cmLocalGhsMultiGenerator.h" #include "cmMakefile.h" +#include "cmOutputConverter.h" #include "cmSourceFile.h" +#include "cmSourceFileLocation.h" #include "cmSourceGroup.h" #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmTarget.h" -#include "cmTargetDepend.h" #include <algorithm> -#include <assert.h> #include <ostream> #include <set> #include <utility> @@ -32,6 +32,11 @@ cmGhsMultiTargetGenerator::cmGhsMultiTargetGenerator(cmGeneratorTarget* target) static_cast<cmLocalGhsMultiGenerator*>(target->GetLocalGenerator())) , Makefile(target->Target->GetMakefile()) , Name(target->GetName()) +#ifdef _WIN32 + , CmdWindowsShell(true) +#else + , CmdWindowsShell(false) +#endif { // Store the configuration name that is being used if (const char* config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE")) { @@ -85,10 +90,19 @@ void cmGhsMultiTargetGenerator::Generate() return; } case cmStateEnums::UTILITY: { - std::string msg = "add_custom_target(<name> ...) not supported: "; - msg += this->Name; - cmSystemTools::Message(msg); - return; + this->TargetNameReal = this->GeneratorTarget->GetName(); + this->TagType = GhsMultiGpj::CUSTOM_TARGET; + break; + } + case cmStateEnums::GLOBAL_TARGET: { + this->TargetNameReal = this->GeneratorTarget->GetName(); + if (this->TargetNameReal == + this->GetGlobalGenerator()->GetInstallTargetName()) { + this->TagType = GhsMultiGpj::CUSTOM_TARGET; + } else { + return; + } + break; } default: return; @@ -105,29 +119,29 @@ void cmGhsMultiTargetGenerator::Generate() void cmGhsMultiTargetGenerator::GenerateTarget() { - // Open the filestream in copy-if-different mode. - std::string fname = this->LocalGenerator->GetCurrentBinaryDirectory(); - fname += "/"; - fname += this->Name; - fname += cmGlobalGhsMultiGenerator::FILE_EXTENSION; - cmGeneratedFileStream fout(fname); + // Open the target file in copy-if-different mode. + std::string fproj = this->LocalGenerator->GetCurrentBinaryDirectory(); + fproj += "/"; + fproj += this->Name; + fproj += cmGlobalGhsMultiGenerator::FILE_EXTENSION; + cmGeneratedFileStream fout(fproj); fout.SetCopyIfDifferent(true); this->GetGlobalGenerator()->WriteFileHeader(fout); GhsMultiGpj::WriteGpjTag(this->TagType, fout); - const std::string language( - this->GeneratorTarget->GetLinkerLanguage(this->ConfigName)); - - this->WriteTargetSpecifics(fout, this->ConfigName); - this->SetCompilerFlags(this->ConfigName, language); - this->WriteCompilerFlags(fout, this->ConfigName, language); - this->WriteCompilerDefinitions(fout, this->ConfigName, language); - this->WriteIncludes(fout, this->ConfigName, language); - this->WriteTargetLinkLine(fout, this->ConfigName); - this->WriteCustomCommands(fout); + if (this->TagType != GhsMultiGpj::CUSTOM_TARGET) { + const std::string language( + this->GeneratorTarget->GetLinkerLanguage(this->ConfigName)); + this->WriteTargetSpecifics(fout, this->ConfigName); + this->SetCompilerFlags(this->ConfigName, language); + this->WriteCompilerFlags(fout, this->ConfigName, language); + this->WriteCompilerDefinitions(fout, this->ConfigName, language); + this->WriteIncludes(fout, this->ConfigName, language); + this->WriteTargetLinkLine(fout, this->ConfigName); + this->WriteBuildEvents(fout); + } this->WriteSources(fout); - this->WriteReferences(fout); fout.Close(); } @@ -304,47 +318,145 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLine(std::ostream& fout, } } -void cmGhsMultiTargetGenerator::WriteCustomCommands(std::ostream& fout) +void cmGhsMultiTargetGenerator::WriteBuildEvents(std::ostream& fout) { - WriteCustomCommandsHelper(fout, this->GeneratorTarget->GetPreBuildCommands(), - cmTarget::PRE_BUILD); - WriteCustomCommandsHelper( - fout, this->GeneratorTarget->GetPostBuildCommands(), cmTarget::POST_BUILD); + this->WriteBuildEventsHelper( + fout, this->GeneratorTarget->GetPreBuildCommands(), + std::string("prebuild"), std::string("preexecShell")); + + if (this->TagType != GhsMultiGpj::CUSTOM_TARGET) { + this->WriteBuildEventsHelper( + fout, this->GeneratorTarget->GetPreLinkCommands(), + std::string("prelink"), std::string("preexecShell")); + } + + this->WriteBuildEventsHelper( + fout, this->GeneratorTarget->GetPostBuildCommands(), + std::string("postbuild"), std::string("postexecShell")); +} + +void cmGhsMultiTargetGenerator::WriteBuildEventsHelper( + std::ostream& fout, const std::vector<cmCustomCommand>& ccv, + std::string const& name, std::string const& cmd) +{ + int cmdcount = 0; + + for (cmCustomCommand const& cc : ccv) { + cmCustomCommandGenerator ccg(cc, this->ConfigName, this->LocalGenerator); + // Open the filestream for this custom command + std::string fname = this->LocalGenerator->GetCurrentBinaryDirectory(); + fname += + "/" + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); + fname += "/" + this->Name + "_" + name; + fname += std::to_string(cmdcount++); + fname += this->CmdWindowsShell ? ".bat" : ".sh"; + cmGeneratedFileStream f(fname); + f.SetCopyIfDifferent(true); + this->WriteCustomCommandsHelper(f, ccg); + f.Close(); + if (this->TagType != GhsMultiGpj::CUSTOM_TARGET) { + fout << " :" << cmd << "=\"" << fname << "\"" << std::endl; + } else { + fout << fname << std::endl; + fout << " :outputName=\"" << fname << ".rule\"" << std::endl; + } + for (auto& byp : ccg.GetByproducts()) { + fout << " :extraOutputFile=\"" << byp << "\"" << std::endl; + } + } } void cmGhsMultiTargetGenerator::WriteCustomCommandsHelper( - std::ostream& fout, std::vector<cmCustomCommand> const& commandsSet, - cmTarget::CustomCommandType const commandType) + std::ostream& fout, cmCustomCommandGenerator const& ccg) { - for (cmCustomCommand const& customCommand : commandsSet) { - cmCustomCommandLines const& commandLines = customCommand.GetCommandLines(); - for (cmCustomCommandLine const& command : commandLines) { - switch (commandType) { - case cmTarget::PRE_BUILD: - fout << " :preexecShellSafe="; - break; - case cmTarget::POST_BUILD: - fout << " :postexecShellSafe="; - break; - default: - assert("Only pre and post are supported"); + std::vector<std::string> cmdLines; + + // if the command specified a working directory use it. + std::string dir = this->LocalGenerator->GetCurrentBinaryDirectory(); + std::string currentBinDir = dir; + std::string workingDir = ccg.GetWorkingDirectory(); + if (!workingDir.empty()) { + dir = workingDir; + } + + // Line to check for error between commands. +#ifdef _WIN32 + std::string check_error = "if %errorlevel% neq 0 exit /b %errorlevel%"; +#else + std::string check_error = "if [[ $? -ne 0 ]]; then exit 1; fi"; +#endif + +#ifdef _WIN32 + cmdLines.push_back("@echo off"); +#endif + // Echo the custom command's comment text. + const char* comment = ccg.GetComment(); + if (comment && *comment) { + std::string echocmd = "echo "; + echocmd += comment; + cmdLines.push_back(std::move(echocmd)); + } + + // Switch to working directory + std::string cdCmd; +#ifdef _WIN32 + std::string cdStr = "cd /D "; +#else + std::string cdStr = "cd "; +#endif + cdCmd = cdStr + + this->LocalGenerator->ConvertToOutputFormat(dir, cmOutputConverter::SHELL); + cmdLines.push_back(std::move(cdCmd)); + + for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) { + // Build the command line in a single string. + std::string cmd = ccg.GetCommand(c); + if (!cmd.empty()) { + // Use "call " before any invocations of .bat or .cmd files + // invoked as custom commands in the WindowsShell. + // + bool useCall = false; + + if (this->CmdWindowsShell) { + std::string suffix; + if (cmd.size() > 4) { + suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4)); + if (suffix == ".bat" || suffix == ".cmd") { + useCall = true; + } + } } - bool firstIteration = true; - for (std::string const& commandLine : command) { - std::string subCommandE = - this->LocalGenerator->EscapeForShell(commandLine, true); - fout << (firstIteration ? "'" : " "); - // Need to double escape backslashes - cmSystemTools::ReplaceString(subCommandE, "\\", "\\\\"); - fout << subCommandE; - firstIteration = false; + cmSystemTools::ReplaceString(cmd, "/./", "/"); + // Convert the command to a relative path only if the current + // working directory will be the start-output directory. + bool had_slash = cmd.find('/') != std::string::npos; + if (workingDir.empty()) { + cmd = + this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, cmd); } - if (!command.empty()) { - fout << "'" << std::endl; + bool has_slash = cmd.find('/') != std::string::npos; + if (had_slash && !has_slash) { + // This command was specified as a path to a file in the + // current directory. Add a leading "./" so it can run + // without the current directory being in the search path. + cmd = "./" + cmd; } + cmd = this->LocalGenerator->ConvertToOutputFormat( + cmd, cmOutputConverter::SHELL); + if (useCall) { + cmd = "call " + cmd; + } + ccg.AppendArguments(c, cmd); + cmdLines.push_back(std::move(cmd)); } } + + // push back the custom commands + for (auto const& c : cmdLines) { + fout << c << std::endl; + fout << check_error << std::endl; + } } void cmGhsMultiTargetGenerator::WriteSourceProperty( @@ -385,7 +497,7 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) /* list of known groups and the order they are displayed in a project file */ const std::vector<std::string> standardGroups = { - "Header Files", "Source Files", "CMake Rules", + "CMake Rules", "Header Files", "Source Files", "Object Files", "Object Libraries", "Resources" }; @@ -403,6 +515,14 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) groupFilesList[i] = *n; i += 1; groupNames.erase(gn); + } else if (this->TagType == GhsMultiGpj::CUSTOM_TARGET && + gn == "CMake Rules") { + /* make sure that rules folder always exists in case of custom targets + * that have no custom commands except for pre or post build events. + */ + groupFilesList.resize(groupFilesList.size() + 1); + groupFilesList[i] = gn; + i += 1; } } @@ -433,7 +553,7 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) /* write files into the proper project file * -- groups go into main project file - * unless FOLDER property or variable is set. + * unless NO_SOURCE_GROUP_FILE property or variable is set. */ for (auto& sg : groupFilesList) { std::ostream* fout; @@ -472,33 +592,98 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) } else { *fout << "{comment} " << sg << std::endl; } + } else if (sg.empty()) { + *fout << "{comment} Others" << std::endl; } - /* output rule for each source file */ - for (const cmSourceFile* si : groupFiles[sg]) { - - // Convert filename to native system - // WORKAROUND: GHS MULTI 6.1.4 and 6.1.6 are known to need backslash on - // windows when opening some files from the search window. - std::string fname(si->GetFullPath()); - cmSystemTools::ConvertToOutputSlashes(fname); - *fout << fname << std::endl; - - if ("ld" != si->GetExtension() && "int" != si->GetExtension() && - "bsp" != si->GetExtension()) { - WriteObjectLangOverride(*fout, si); + if (sg != "CMake Rules") { + /* output rule for each source file */ + for (const cmSourceFile* si : groupFiles[sg]) { + bool compile = true; + // Convert filename to native system + // WORKAROUND: GHS MULTI 6.1.4 and 6.1.6 are known to need backslash on + // windows when opening some files from the search window. + std::string fname(si->GetFullPath()); + cmSystemTools::ConvertToOutputSlashes(fname); + + /* For custom targets list any associated sources, + * comment out source code to prevent it from being + * compiled when processing this target. + * Otherwise, comment out any custom command (main) dependencies that + * are listed as source files to prevent them from being considered + * part of the build. + */ + std::string comment; + if ((this->TagType == GhsMultiGpj::CUSTOM_TARGET && + !si->GetLanguage().empty()) || + si->GetCustomCommand()) { + comment = "{comment} "; + compile = false; + } + + *fout << comment << fname << std::endl; + if (compile) { + if ("ld" != si->GetExtension() && "int" != si->GetExtension() && + "bsp" != si->GetExtension()) { + WriteObjectLangOverride(*fout, si); + } + + this->WriteSourceProperty(*fout, si, "INCLUDE_DIRECTORIES", "-I"); + this->WriteSourceProperty(*fout, si, "COMPILE_DEFINITIONS", "-D"); + this->WriteSourceProperty(*fout, si, "COMPILE_OPTIONS", ""); + + /* to avoid clutter in the GUI only print out the objectName if it + * has been renamed */ + std::string objectName = this->GeneratorTarget->GetObjectName(si); + if (!objectName.empty() && + this->GeneratorTarget->HasExplicitObjectName(si)) { + *fout << " -o " << objectName << std::endl; + } + } } - - this->WriteSourceProperty(*fout, si, "INCLUDE_DIRECTORIES", "-I"); - this->WriteSourceProperty(*fout, si, "COMPILE_DEFINITIONS", "-D"); - this->WriteSourceProperty(*fout, si, "COMPILE_OPTIONS", ""); - - /* to avoid clutter in the gui only print out the objectName if it has - * been renamed */ - std::string objectName = this->GeneratorTarget->GetObjectName(si); - if (!objectName.empty() && - this->GeneratorTarget->HasExplicitObjectName(si)) { - *fout << " -o " << objectName << std::endl; + } else { + std::vector<cmSourceFile const*> customCommands; + if (ComputeCustomCommandOrder(customCommands)) { + std::string message = "The custom commands for target [" + + this->GeneratorTarget->GetName() + "] had a cycle.\n"; + cmSystemTools::Error(message); + } else { + /* Custom targets do not have a dependency on SOURCES files. + * Therefore the dependency list may include SOURCES files after the + * custom target. Because nothing can depend on the custom target just + * move it to the last item. + */ + for (auto sf = customCommands.begin(); sf != customCommands.end(); + ++sf) { + if (((*sf)->GetLocation()).GetName() == this->Name + ".rule") { + std::rotate(sf, sf + 1, customCommands.end()); + break; + } + } + int cmdcount = 0; + for (auto& sf : customCommands) { + const cmCustomCommand* cc = sf->GetCustomCommand(); + cmCustomCommandGenerator ccg(*cc, this->ConfigName, + this->LocalGenerator); + + // Open the filestream for this custom command + std::string fname = + this->LocalGenerator->GetCurrentBinaryDirectory(); + fname += "/" + + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); + fname += "/" + this->Name + "_cc"; + fname += std::to_string(cmdcount++) + "_"; + fname += (sf->GetLocation()).GetName(); + fname += this->CmdWindowsShell ? ".bat" : ".sh"; + cmGeneratedFileStream f(fname); + f.SetCopyIfDifferent(true); + this->WriteCustomCommandsHelper(f, ccg); + f.Close(); + this->WriteCustomCommandLine(*fout, fname, ccg); + } + } + if (this->TagType == GhsMultiGpj::CUSTOM_TARGET) { + this->WriteBuildEvents(*fout); } } } @@ -508,6 +693,33 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) } } +void cmGhsMultiTargetGenerator::WriteCustomCommandLine( + std::ostream& fout, std::string& fname, cmCustomCommandGenerator const& ccg) +{ + /* NOTE: Customization Files are not well documented. Testing showed + * that ":outputName=file" can only be used once per script. The + * script will only run if ":outputName=file" is missing or just run + * once if ":outputName=file" is not specified. If there are + * multiple outputs then the script needs to be listed multiple times + * for each output. Otherwise it won't rerun the script if one of + * the outputs is manually deleted. + */ + bool specifyExtra = true; + for (auto& out : ccg.GetOutputs()) { + fout << fname << std::endl; + fout << " :outputName=\"" << out << "\"" << std::endl; + if (specifyExtra) { + for (auto& byp : ccg.GetByproducts()) { + fout << " :extraOutputFile=\"" << byp << "\"" << std::endl; + } + for (auto& dep : ccg.GetDepends()) { + fout << " :depends=\"" << dep << "\"" << std::endl; + } + specifyExtra = false; + } + } +} + void cmGhsMultiTargetGenerator::WriteObjectLangOverride( std::ostream& fout, const cmSourceFile* sourceFile) { @@ -521,35 +733,6 @@ void cmGhsMultiTargetGenerator::WriteObjectLangOverride( } } -void cmGhsMultiTargetGenerator::WriteReferences(std::ostream& fout) -{ - // This only applies to INTEGRITY Applications - if (this->TagType != GhsMultiGpj::INTERGRITY_APPLICATION) { - return; - } - - // Get the targets that this one depends upon - cmTargetDependSet unordered = - this->GetGlobalGenerator()->GetTargetDirectDepends(this->GeneratorTarget); - cmGlobalGhsMultiGenerator::OrderedTargetDependSet ordered(unordered, - this->Name); - for (auto& t : ordered) { - std::string tname = t->GetName(); - std::string tpath = t->LocalGenerator->GetCurrentBinaryDirectory(); - std::string rootpath = this->LocalGenerator->GetCurrentBinaryDirectory(); - std::string outpath = - this->LocalGenerator->MaybeConvertToRelativePath(rootpath, tpath) + "/" + - tname + "REF" + cmGlobalGhsMultiGenerator::FILE_EXTENSION; - - fout << outpath; - fout << " "; - GhsMultiGpj::WriteGpjTag(GhsMultiGpj::REFERENCE, fout); - - // Tell the global generator that a refernce project needs to be created - t->Target->SetProperty("GHS_REFERENCE_PROJECT", "ON"); - } -} - bool cmGhsMultiTargetGenerator::DetermineIfIntegrityApp() { const char* p = this->GeneratorTarget->GetProperty("ghs_integrity_app"); @@ -566,3 +749,51 @@ bool cmGhsMultiTargetGenerator::DetermineIfIntegrityApp() } return false; } + +bool cmGhsMultiTargetGenerator::ComputeCustomCommandOrder( + std::vector<cmSourceFile const*>& order) +{ + std::set<cmSourceFile const*> temp; + std::set<cmSourceFile const*> perm; + + // Collect all custom commands for this target + std::vector<cmSourceFile const*> customCommands; + this->GeneratorTarget->GetCustomCommands(customCommands, this->ConfigName); + + for (cmSourceFile const* si : customCommands) { + bool r = VisitCustomCommand(temp, perm, order, si); + if (r) { + return r; + } + } + return false; +} + +bool cmGhsMultiTargetGenerator::VisitCustomCommand( + std::set<cmSourceFile const*>& temp, std::set<cmSourceFile const*>& perm, + std::vector<cmSourceFile const*>& order, cmSourceFile const* si) +{ + /* check if permanent mark is set*/ + if (perm.find(si) == perm.end()) { + /* set temporary mark; check if revisit*/ + if (temp.insert(si).second) { + for (auto& di : si->GetCustomCommand()->GetDepends()) { + cmSourceFile const* sf = this->GeneratorTarget->GetLocalGenerator() + ->GetMakefile() + ->GetSourceFileWithOutput(di); + /* if sf exists then visit */ + if (sf && this->VisitCustomCommand(temp, perm, order, sf)) { + return true; + } + } + /* mark as complete; insert into beginning of list*/ + perm.insert(si); + order.push_back(si); + return false; + } + /* revisiting item - not a DAG */ + return true; + } + /* already complete */ + return false; +} diff --git a/Source/cmGhsMultiTargetGenerator.h b/Source/cmGhsMultiTargetGenerator.h index a4e23d9..a131567 100644 --- a/Source/cmGhsMultiTargetGenerator.h +++ b/Source/cmGhsMultiTargetGenerator.h @@ -5,14 +5,14 @@ #include "cmGhsMultiGpj.h" -#include "cmTarget.h" - #include <iosfwd> #include <map> +#include <set> #include <string> #include <vector> class cmCustomCommand; +class cmCustomCommandGenerator; class cmGeneratorTarget; class cmGlobalGhsMultiGenerator; class cmLocalGhsMultiGenerator; @@ -49,15 +49,23 @@ private: void WriteIncludes(std::ostream& fout, const std::string& config, const std::string& language); void WriteTargetLinkLine(std::ostream& fout, std::string const& config); - void WriteCustomCommands(std::ostream& fout); - void WriteCustomCommandsHelper( - std::ostream& fout, std::vector<cmCustomCommand> const& commandsSet, - cmTarget::CustomCommandType commandType); + void WriteBuildEvents(std::ostream& fout); + void WriteBuildEventsHelper(std::ostream& fout, + const std::vector<cmCustomCommand>& ccv, + std::string const& name, std::string const& cmd); + void WriteCustomCommandsHelper(std::ostream& fout, + cmCustomCommandGenerator const& ccg); + void WriteCustomCommandLine(std::ostream& fout, std::string& fname, + cmCustomCommandGenerator const& ccg); + bool ComputeCustomCommandOrder(std::vector<cmSourceFile const*>& order); + bool VisitCustomCommand(std::set<cmSourceFile const*>& temp, + std::set<cmSourceFile const*>& perm, + std::vector<cmSourceFile const*>& order, + cmSourceFile const* sf); void WriteSources(std::ostream& fout_proj); void WriteSourceProperty(std::ostream& fout, const cmSourceFile* sf, std::string const& propName, std::string const& propFlag); - void WriteReferences(std::ostream& fout); static void WriteObjectLangOverride(std::ostream& fout, const cmSourceFile* sourceFile); @@ -71,7 +79,8 @@ private: std::string TargetNameReal; GhsMultiGpj::Types TagType; std::string const Name; - std::string ConfigName; /* CMAKE_BUILD_TYPE */ + std::string ConfigName; /* CMAKE_BUILD_TYPE */ + bool const CmdWindowsShell; /* custom commands run in cmd.exe or /bin/sh */ }; #endif // ! cmGhsMultiTargetGenerator_h diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx index 9f361f6..b69dea0 100644 --- a/Source/cmGlobalGhsMultiGenerator.cxx +++ b/Source/cmGlobalGhsMultiGenerator.cxx @@ -265,14 +265,68 @@ void cmGlobalGhsMultiGenerator::WriteFileHeader(std::ostream& fout) << std::endl; } -void cmGlobalGhsMultiGenerator::WriteTopLevelProject( - std::ostream& fout, cmLocalGenerator* root, - std::vector<cmLocalGenerator*>& generators) +void cmGlobalGhsMultiGenerator::WriteCustomRuleBOD(std::ostream& fout) { - WriteFileHeader(fout); + fout << "Commands {\n" + " Custom_Rule_Command {\n" + " name = \"Custom Rule Command\"\n" + " exec = \""; +#ifdef _WIN32 + fout << "cmd.exe"; +#else + fout << "/bin/sh"; +#endif + fout << "\"\n" + " options = {\"SpecialOptions\"}\n" + " }\n" + "}\n"; + + fout << "\n\n"; + fout << "FileTypes {\n" + " CmakeRule {\n" + " name = \"Custom Rule\"\n" + " action = \"&Run\"\n" + " extensions = {\""; +#ifdef _WIN32 + fout << "bat"; +#else + fout << "sh"; +#endif + fout << "\"}\n" + " grepable = false\n" + " command = \"Custom Rule Command\"\n" + " commandLine = \"$COMMAND "; +#ifdef _WIN32 + fout << "/c"; +#endif + fout << " $INPUTFILE\"\n" + " progress = \"Processing Custom Rule\"\n" + " promoteToFirstPass = true\n" + " outputType = \"None\"\n" + " color = \"#800080\"\n" + " }\n" + "}\n"; +} - this->WriteMacros(fout); - this->WriteHighLevelDirectives(fout); +void cmGlobalGhsMultiGenerator::WriteCustomTargetBOD(std::ostream& fout) +{ + fout << "FileTypes {\n" + " CmakeTarget {\n" + " name = \"Custom Target\"\n" + " action = \"&Execute\"\n" + " grepable = false\n" + " outputType = \"None\"\n" + " color = \"#800080\"\n" + " }\n" + "}\n"; +} + +void cmGlobalGhsMultiGenerator::WriteTopLevelProject(std::ostream& fout, + cmLocalGenerator* root) +{ + this->WriteFileHeader(fout); + this->WriteMacros(fout, root); + this->WriteHighLevelDirectives(root, fout); GhsMultiGpj::WriteGpjTag(GhsMultiGpj::PROJECT, fout); fout << "# Top Level Project File" << std::endl; @@ -298,71 +352,152 @@ void cmGlobalGhsMultiGenerator::WriteTopLevelProject( } fout << "\"" << this->OsDir << "\"" << std::endl; } - - WriteSubProjects(fout, root, generators); } -void cmGlobalGhsMultiGenerator::WriteSubProjects( - std::ostream& fout, cmLocalGenerator* root, - std::vector<cmLocalGenerator*>& generators) +void cmGlobalGhsMultiGenerator::WriteSubProjects(std::ostream& fout, + std::string& all_target) { - // Collect all targets under this root generator and the transitive - // closure of their dependencies. - TargetDependSet projectTargets; - TargetDependSet originalTargets; - this->GetTargetSets(projectTargets, originalTargets, root, generators); - OrderedTargetDependSet orderedProjectTargets(projectTargets, ""); - - // write out all the sub-projects - std::string rootBinaryDir = root->GetCurrentBinaryDirectory(); - for (cmGeneratorTarget const* target : orderedProjectTargets) { - if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + fout << "CMakeFiles/" << all_target << " [Project]" << std::endl; + // All known targets + for (cmGeneratorTarget const* target : this->ProjectTargets) { + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY || + target->GetType() == cmStateEnums::MODULE_LIBRARY || + target->GetType() == cmStateEnums::SHARED_LIBRARY || + (target->GetType() == cmStateEnums::GLOBAL_TARGET && + target->GetName() != GetInstallTargetName())) { continue; } + fout << "CMakeFiles/" << target->GetName() + ".tgt" + FILE_EXTENSION + << " [Project]" << std::endl; + } +} - const char* projName = target->GetProperty("GENERATOR_FILE_NAME"); - const char* projType = target->GetProperty("GENERATOR_FILE_NAME_EXT"); - if (projName && projType) { - cmLocalGenerator* lg = target->GetLocalGenerator(); - std::string dir = lg->GetCurrentBinaryDirectory(); - dir = root->MaybeConvertToRelativePath(rootBinaryDir, dir); - if (dir == ".") { - dir.clear(); - } else { - if (dir.back() != '/') { - dir += "/"; - } +void cmGlobalGhsMultiGenerator::WriteProjectLine( + std::ostream& fout, cmGeneratorTarget const* target, cmLocalGenerator* root, + std::string& rootBinaryDir) +{ + const char* projName = target->GetProperty("GENERATOR_FILE_NAME"); + const char* projType = target->GetProperty("GENERATOR_FILE_NAME_EXT"); + if (projName && projType) { + cmLocalGenerator* lg = target->GetLocalGenerator(); + std::string dir = lg->GetCurrentBinaryDirectory(); + dir = root->MaybeConvertToRelativePath(rootBinaryDir, dir); + if (dir == ".") { + dir.clear(); + } else { + if (dir.back() != '/') { + dir += "/"; } + } - if (cmSystemTools::IsOn(target->GetProperty("EXCLUDE_FROM_ALL"))) { - fout << "{comment} "; - } - std::string projFile = dir + projName + FILE_EXTENSION; - fout << projFile; - fout << " " << projType << std::endl; + std::string projFile = dir + projName + FILE_EXTENSION; + fout << projFile; + fout << " " << projType << std::endl; + } else { + /* Should never happen */ + std::string message = + "The project file for target [" + target->GetName() + "] is missing.\n"; + cmSystemTools::Error(message); + fout << "{comment} " << target->GetName() << " [missing project file]\n"; + } +} - if (cmSystemTools::IsOn(target->GetProperty("GHS_REFERENCE_PROJECT"))) { - // create reference project - std::string fname = dir; - fname += target->GetName(); - fname += "REF"; - fname += FILE_EXTENSION; +void cmGlobalGhsMultiGenerator::WriteTargets(cmLocalGenerator* root) +{ + std::string rootBinaryDir = root->GetCurrentBinaryDirectory(); + rootBinaryDir += "/CMakeFiles"; + + // All known targets + for (cmGeneratorTarget const* target : this->ProjectTargets) { + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY || + target->GetType() == cmStateEnums::MODULE_LIBRARY || + target->GetType() == cmStateEnums::SHARED_LIBRARY || + (target->GetType() == cmStateEnums::GLOBAL_TARGET && + target->GetName() != GetInstallTargetName())) { + continue; + } - cmGeneratedFileStream fref(fname); - fref.SetCopyIfDifferent(true); + // create target build file + std::string name = target->GetName() + ".tgt" + FILE_EXTENSION; + std::string fname = rootBinaryDir + "/" + name; + cmGeneratedFileStream fbld(fname); + fbld.SetCopyIfDifferent(true); + this->WriteFileHeader(fbld); + GhsMultiGpj::WriteGpjTag(GhsMultiGpj::PROJECT, fbld); + std::vector<cmGeneratorTarget const*> build; + if (ComputeTargetBuildOrder(target, build)) { + std::string message = "The inter-target dependency graph for target [" + + target->GetName() + "] had a cycle.\n"; + cmSystemTools::Error(message); + } else { + for (auto& tgt : build) { + WriteProjectLine(fbld, tgt, root, rootBinaryDir); + } + } + fbld.Close(); + } +} - this->WriteFileHeader(fref); - GhsMultiGpj::WriteGpjTag(GhsMultiGpj::REFERENCE, fref); - fref << " :reference=" << projFile << std::endl; +void cmGlobalGhsMultiGenerator::WriteAllTarget( + cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators, + std::string& all_target) +{ + this->ProjectTargets.clear(); + + // create target build file + all_target = root->GetProjectName() + "." + this->GetAllTargetName() + + ".tgt" + FILE_EXTENSION; + std::string fname = + root->GetCurrentBinaryDirectory() + "/CMakeFiles/" + all_target; + cmGeneratedFileStream fbld(fname); + fbld.SetCopyIfDifferent(true); + this->WriteFileHeader(fbld); + GhsMultiGpj::WriteGpjTag(GhsMultiGpj::PROJECT, fbld); - fref.Close(); + // Collect all targets under this root generator and the transitive + // closure of their dependencies. + TargetDependSet projectTargets; + TargetDependSet originalTargets; + this->GetTargetSets(projectTargets, originalTargets, root, generators); + OrderedTargetDependSet sortedProjectTargets(projectTargets, ""); + std::vector<cmGeneratorTarget const*> defaultTargets; + for (cmGeneratorTarget const* t : sortedProjectTargets) { + /* save list of all targets in sorted order */ + this->ProjectTargets.push_back(t); + } + for (cmGeneratorTarget const* t : sortedProjectTargets) { + if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + continue; + } + if (!cmSystemTools::IsOn(t->GetProperty("EXCLUDE_FROM_ALL"))) { + defaultTargets.push_back(t); + } + } + std::vector<cmGeneratorTarget const*> build; + if (ComputeTargetBuildOrder(defaultTargets, build)) { + std::string message = "The inter-target dependency graph for project [" + + root->GetProjectName() + "] had a cycle.\n"; + cmSystemTools::Error(message); + } else { + // determine the targets for ALL target + std::string rootBinaryDir = root->GetCurrentBinaryDirectory(); + rootBinaryDir += "/CMakeFiles"; + for (cmGeneratorTarget const* target : build) { + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY || + target->GetType() == cmStateEnums::MODULE_LIBRARY || + target->GetType() == cmStateEnums::SHARED_LIBRARY) { + continue; } + this->WriteProjectLine(fbld, target, root, rootBinaryDir); } } + fbld.Close(); } void cmGlobalGhsMultiGenerator::Generate() { + std::string fname; + // first do the superclass method this->cmGlobalGenerator::Generate(); @@ -370,11 +505,32 @@ void cmGlobalGhsMultiGenerator::Generate() for (auto& it : this->ProjectMap) { this->OutputTopLevelProject(it.second[0], it.second); } + + // create custom rule BOD file + fname = this->GetCMakeInstance()->GetHomeOutputDirectory() + + "/CMakeFiles/custom_rule.bod"; + cmGeneratedFileStream frule(fname); + frule.SetCopyIfDifferent(true); + this->WriteFileHeader(frule); + this->WriteCustomRuleBOD(frule); + frule.Close(); + + // create custom target BOD file + fname = this->GetCMakeInstance()->GetHomeOutputDirectory() + + "/CMakeFiles/custom_target.bod"; + cmGeneratedFileStream ftarget(fname); + ftarget.SetCopyIfDifferent(true); + this->WriteFileHeader(ftarget); + this->WriteCustomTargetBOD(ftarget); + ftarget.Close(); } void cmGlobalGhsMultiGenerator::OutputTopLevelProject( cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators) { + std::string fname; + std::string all_target; + if (generators.empty()) { return; } @@ -383,18 +539,21 @@ void cmGlobalGhsMultiGenerator::OutputTopLevelProject( * with target projects. This avoid the issue where the project has * the same name as the executable target. */ - std::string fname = root->GetCurrentBinaryDirectory(); + fname = root->GetCurrentBinaryDirectory(); fname += "/"; fname += root->GetProjectName(); fname += ".top"; fname += FILE_EXTENSION; - cmGeneratedFileStream fout(fname); - fout.SetCopyIfDifferent(true); + cmGeneratedFileStream top(fname); + top.SetCopyIfDifferent(true); + this->WriteTopLevelProject(top, root); - this->WriteTopLevelProject(fout, root, generators); + this->WriteAllTarget(root, generators, all_target); + this->WriteTargets(root); - fout.Close(); + this->WriteSubProjects(top, all_target); + top.Close(); } std::vector<cmGlobalGenerator::GeneratedMakeCommand> @@ -426,6 +585,9 @@ cmGlobalGhsMultiGenerator::GenerateBuildCommand( std::vector<std::string> files; cmSystemTools::Glob(projectDir, ".*\\.top\\.gpj", files); if (!files.empty()) { + /* if multiple top-projects are found in build directory + * then prefer projectName top-project. + */ auto p = std::find(files.begin(), files.end(), proj); if (p == files.end()) { proj = files.at(0); @@ -440,20 +602,24 @@ cmGlobalGhsMultiGenerator::GenerateBuildCommand( } else { for (const auto& tname : targetNames) { if (!tname.empty()) { - if (tname.compare(tname.size() - 4, 4, ".gpj") == 0) { - makeCommand.Add(tname); - } else { - makeCommand.Add(tname + ".gpj"); - } + makeCommand.Add(tname + ".tgt.gpj"); } } } + } else { + /* transform name to default build */; + std::string all = proj; + all.replace(all.end() - 7, all.end(), + std::string(this->GetAllTargetName()) + ".tgt.gpj"); + makeCommand.Add(all); } return { makeCommand }; } -void cmGlobalGhsMultiGenerator::WriteMacros(std::ostream& fout) +void cmGlobalGhsMultiGenerator::WriteMacros(std::ostream& fout, + cmLocalGenerator* root) { + fout << "macro PROJ_NAME=" << root->GetProjectName() << std::endl; char const* ghsGpjMacros = this->GetCMakeInstance()->GetCacheDefinition("GHS_GPJ_MACROS"); if (nullptr != ghsGpjMacros) { @@ -465,13 +631,14 @@ void cmGlobalGhsMultiGenerator::WriteMacros(std::ostream& fout) } } -void cmGlobalGhsMultiGenerator::WriteHighLevelDirectives(std::ostream& fout) +void cmGlobalGhsMultiGenerator::WriteHighLevelDirectives( + cmLocalGenerator* root, std::ostream& fout) { /* set primary target */ std::string tgt; const char* t = this->GetCMakeInstance()->GetCacheDefinition("GHS_PRIMARY_TARGET"); - if (t) { + if (t && *t != '\0') { tgt = t; this->GetCMakeInstance()->MarkCliAsUsed("GHS_PRIMARY_TARGET"); } else { @@ -486,16 +653,20 @@ void cmGlobalGhsMultiGenerator::WriteHighLevelDirectives(std::ostream& fout) } fout << "primaryTarget=" << tgt << std::endl; + fout << "customization=" << root->GetBinaryDirectory() + << "/CMakeFiles/custom_rule.bod" << std::endl; + fout << "customization=" << root->GetBinaryDirectory() + << "/CMakeFiles/custom_target.bod" << std::endl; char const* const customization = this->GetCMakeInstance()->GetCacheDefinition("GHS_CUSTOMIZATION"); if (nullptr != customization && strlen(customization) > 0) { - fout << "customization=" << trimQuotes(customization) << std::endl; + fout << "customization=" << this->TrimQuotes(customization) << std::endl; this->GetCMakeInstance()->MarkCliAsUsed("GHS_CUSTOMIZATION"); } } -std::string cmGlobalGhsMultiGenerator::trimQuotes(std::string const& str) +std::string cmGlobalGhsMultiGenerator::TrimQuotes(std::string const& str) { std::string result; result.reserve(str.size()); @@ -528,3 +699,56 @@ cmGlobalGhsMultiGenerator::OrderedTargetDependSet::OrderedTargetDependSet( { this->insert(targets.begin(), targets.end()); } + +bool cmGlobalGhsMultiGenerator::ComputeTargetBuildOrder( + cmGeneratorTarget const* tgt, std::vector<cmGeneratorTarget const*>& build) +{ + std::vector<cmGeneratorTarget const*> t{ tgt }; + return ComputeTargetBuildOrder(t, build); +} + +bool cmGlobalGhsMultiGenerator::ComputeTargetBuildOrder( + std::vector<cmGeneratorTarget const*>& tgt, + std::vector<cmGeneratorTarget const*>& build) +{ + std::set<cmGeneratorTarget const*> temp; + std::set<cmGeneratorTarget const*> perm; + + for (auto ti : tgt) { + bool r = VisitTarget(temp, perm, build, ti); + if (r) { + return r; + } + } + return false; +} + +bool cmGlobalGhsMultiGenerator::VisitTarget( + std::set<cmGeneratorTarget const*>& temp, + std::set<cmGeneratorTarget const*>& perm, + std::vector<cmGeneratorTarget const*>& order, cmGeneratorTarget const* ti) +{ + /* check if permanent mark is set*/ + if (perm.find(ti) == perm.end()) { + /* set temporary mark; check if revisit*/ + if (temp.insert(ti).second) { + /* sort targets lexicographically to ensure that nodes are always visited + * in the same order */ + OrderedTargetDependSet sortedTargets(this->GetTargetDirectDepends(ti), + ""); + for (auto& di : sortedTargets) { + if (this->VisitTarget(temp, perm, order, di)) { + return true; + } + } + /* mark as complete; insert into beginning of list*/ + perm.insert(ti); + order.push_back(ti); + return false; + } + /* revisiting item - not a DAG */ + return true; + } + /* already complete */ + return false; +} diff --git a/Source/cmGlobalGhsMultiGenerator.h b/Source/cmGlobalGhsMultiGenerator.h index 1aeb1dc..98358c7 100644 --- a/Source/cmGlobalGhsMultiGenerator.h +++ b/Source/cmGlobalGhsMultiGenerator.h @@ -78,23 +78,7 @@ public: // Write the common disclaimer text at the top of each build file. void WriteFileHeader(std::ostream& fout); - // Target dependency sorting - class TargetSet : public std::set<cmGeneratorTarget const*> - { - }; - class TargetCompare - { - std::string First; - - public: - TargetCompare(std::string first) - : First(std::move(first)) - { - } - bool operator()(cmGeneratorTarget const* l, - cmGeneratorTarget const* r) const; - }; - class OrderedTargetDependSet; + const char* GetInstallTargetName() const override { return "install"; } protected: void Generate() override; @@ -111,18 +95,53 @@ private: /* top-level project */ void OutputTopLevelProject(cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators); - void WriteTopLevelProject(std::ostream& fout, cmLocalGenerator* root, - std::vector<cmLocalGenerator*>& generators); - void WriteMacros(std::ostream& fout); - void WriteHighLevelDirectives(std::ostream& fout); - void WriteSubProjects(std::ostream& fout, cmLocalGenerator* root, - std::vector<cmLocalGenerator*>& generators); - - std::string trimQuotes(std::string const& str); + void WriteTopLevelProject(std::ostream& fout, cmLocalGenerator* root); + void WriteMacros(std::ostream& fout, cmLocalGenerator* root); + void WriteHighLevelDirectives(cmLocalGenerator* root, std::ostream& fout); + void WriteSubProjects(std::ostream& fout, std::string& all_target); + void WriteTargets(cmLocalGenerator* root); + void WriteProjectLine(std::ostream& fout, cmGeneratorTarget const* target, + cmLocalGenerator* root, std::string& rootBinaryDir); + void WriteCustomRuleBOD(std::ostream& fout); + void WriteCustomTargetBOD(std::ostream& fout); + void WriteAllTarget(cmLocalGenerator* root, + std::vector<cmLocalGenerator*>& generators, + std::string& all_target); + + std::string TrimQuotes(std::string const& str); std::string OsDir; static const char* DEFAULT_BUILD_PROGRAM; static const char* DEFAULT_TOOLSET_ROOT; + + bool ComputeTargetBuildOrder(cmGeneratorTarget const* tgt, + std::vector<cmGeneratorTarget const*>& build); + bool ComputeTargetBuildOrder(std::vector<cmGeneratorTarget const*>& tgt, + std::vector<cmGeneratorTarget const*>& build); + bool VisitTarget(std::set<cmGeneratorTarget const*>& temp, + std::set<cmGeneratorTarget const*>& perm, + std::vector<cmGeneratorTarget const*>& order, + cmGeneratorTarget const* ti); + + std::vector<cmGeneratorTarget const*> ProjectTargets; + + // Target sorting + class TargetSet : public std::set<cmGeneratorTarget const*> + { + }; + class TargetCompare + { + std::string First; + + public: + TargetCompare(std::string first) + : First(std::move(first)) + { + } + bool operator()(cmGeneratorTarget const* l, + cmGeneratorTarget const* r) const; + }; + class OrderedTargetDependSet; }; class cmGlobalGhsMultiGenerator::OrderedTargetDependSet diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index d7630e4..c31dbf4 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -101,7 +101,7 @@ void cmGlobalVisualStudio7Generator::EnableLanguage( } // Create list of configurations requested by user's cache, if any. - this->cmGlobalGenerator::EnableLanguage(lang, mf, optional); + this->cmGlobalVisualStudioGenerator::EnableLanguage(lang, mf, optional); // if this environment variable is set, then copy it to // a static cache entry. It will be used by diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx index 280c986..39c325c 100644 --- a/Source/cmGlobalVisualStudioGenerator.cxx +++ b/Source/cmGlobalVisualStudioGenerator.cxx @@ -53,6 +53,14 @@ void cmGlobalVisualStudioGenerator::SetVersion(VSVersion v) this->Version = v; } +void cmGlobalVisualStudioGenerator::EnableLanguage( + std::vector<std::string> const& lang, cmMakefile* mf, bool optional) +{ + mf->AddDefinition("CMAKE_VS_PLATFORM_NAME_DEFAULT", + this->DefaultPlatformName.c_str()); + this->cmGlobalGenerator::EnableLanguage(lang, mf, optional); +} + bool cmGlobalVisualStudioGenerator::SetGeneratorPlatform(std::string const& p, cmMakefile* mf) { diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h index 039191c..cbab329 100644 --- a/Source/cmGlobalVisualStudioGenerator.h +++ b/Source/cmGlobalVisualStudioGenerator.h @@ -50,6 +50,9 @@ public: /** Is the installed VS an Express edition? */ bool IsExpressEdition() const { return this->ExpressEdition; } + void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*, + bool optional) override; + bool SetGeneratorPlatform(std::string const& p, cmMakefile* mf) override; /** diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index 67763d4..8b51834 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -6,6 +6,7 @@ #include "cmComputeLinkInformation.h" #include "cmCustomCommandGenerator.h" #include "cmGeneratedFileStream.h" +#include "cmGeneratorExpression.h" #include "cmGeneratorExpressionEvaluationFile.h" #include "cmGeneratorTarget.h" #include "cmGlobalGenerator.h" @@ -1519,8 +1520,40 @@ void cmLocalGenerator::AddLanguageFlags(std::string& flags, flagsVar += "_FLAGS"; this->AddConfigVariableFlags(flags, flagsVar, config); - // Placeholder for possible future per-target flags. - static_cast<void>(target); + // Add MSVC runtime library flags. This is activated by the presence + // of a default selection whether or not it is overridden by a property. + const char* msvcRuntimeLibraryDefault = + this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT"); + if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) { + const char* msvcRuntimeLibraryValue = + target->GetProperty("MSVC_RUNTIME_LIBRARY"); + if (!msvcRuntimeLibraryValue) { + msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault; + } + cmGeneratorExpression ge; + std::unique_ptr<cmCompiledGeneratorExpression> cge = + ge.Parse(msvcRuntimeLibraryValue); + std::string const msvcRuntimeLibrary = + cge->Evaluate(this, config, false, target); + if (!msvcRuntimeLibrary.empty()) { + if (const char* msvcRuntimeLibraryOptions = + this->Makefile->GetDefinition( + "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" + + msvcRuntimeLibrary)) { + this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions); + } else if ((this->Makefile->GetSafeDefinition( + "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" || + this->Makefile->GetSafeDefinition( + "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") && + !cmSystemTools::GetErrorOccuredFlag()) { + // The compiler uses the MSVC ABI so it needs a known runtime library. + this->IssueMessage(MessageType::FATAL_ERROR, + "MSVC_RUNTIME_LIBRARY value '" + + msvcRuntimeLibrary + "' not known for this " + + lang + " compiler."); + } + } + } } void cmLocalGenerator::AddLanguageFlagsForLinking( diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx index 984cd85..ebf5fc2 100644 --- a/Source/cmMakefileExecutableTargetGenerator.cxx +++ b/Source/cmMakefileExecutableTargetGenerator.cxx @@ -9,6 +9,7 @@ #include <utility> #include <vector> +#include "cmAlgorithms.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" #include "cmGlobalUnixMakefileGenerator3.h" @@ -35,14 +36,12 @@ cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator( this->GeneratorTarget->GetExecutableNames(this->ConfigName); this->OSXBundleGenerator = - new cmOSXBundleGenerator(target, this->ConfigName); + cm::make_unique<cmOSXBundleGenerator>(target, this->ConfigName); this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders); } -cmMakefileExecutableTargetGenerator::~cmMakefileExecutableTargetGenerator() -{ - delete this->OSXBundleGenerator; -} +cmMakefileExecutableTargetGenerator::~cmMakefileExecutableTargetGenerator() = + default; void cmMakefileExecutableTargetGenerator::WriteRuleFiles() { diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx index 44e6547..0393e22 100644 --- a/Source/cmMakefileLibraryTargetGenerator.cxx +++ b/Source/cmMakefileLibraryTargetGenerator.cxx @@ -9,6 +9,7 @@ #include <utility> #include <vector> +#include "cmAlgorithms.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" #include "cmGlobalUnixMakefileGenerator3.h" @@ -37,14 +38,12 @@ cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator( } this->OSXBundleGenerator = - new cmOSXBundleGenerator(target, this->ConfigName); + cm::make_unique<cmOSXBundleGenerator>(target, this->ConfigName); this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders); } -cmMakefileLibraryTargetGenerator::~cmMakefileLibraryTargetGenerator() -{ - delete this->OSXBundleGenerator; -} +cmMakefileLibraryTargetGenerator::~cmMakefileLibraryTargetGenerator() = + default; void cmMakefileLibraryTargetGenerator::WriteRuleFiles() { diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h index c053d5b..ec58d17 100644 --- a/Source/cmMakefileTargetGenerator.h +++ b/Source/cmMakefileTargetGenerator.h @@ -235,7 +235,7 @@ protected: // macOS content info. std::set<std::string> MacContentFolders; - cmOSXBundleGenerator* OSXBundleGenerator; + std::unique_ptr<cmOSXBundleGenerator> OSXBundleGenerator; MacOSXContentGeneratorType* MacOSXContentGenerator; }; diff --git a/Source/cmMakefileUtilityTargetGenerator.cxx b/Source/cmMakefileUtilityTargetGenerator.cxx index 8fbd5d2..4236995 100644 --- a/Source/cmMakefileUtilityTargetGenerator.cxx +++ b/Source/cmMakefileUtilityTargetGenerator.cxx @@ -7,6 +7,7 @@ #include <utility> #include <vector> +#include "cmAlgorithms.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" #include "cmGlobalUnixMakefileGenerator3.h" @@ -21,14 +22,12 @@ cmMakefileUtilityTargetGenerator::cmMakefileUtilityTargetGenerator( { this->CustomCommandDriver = OnUtility; this->OSXBundleGenerator = - new cmOSXBundleGenerator(target, this->ConfigName); + cm::make_unique<cmOSXBundleGenerator>(target, this->ConfigName); this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders); } -cmMakefileUtilityTargetGenerator::~cmMakefileUtilityTargetGenerator() -{ - delete this->OSXBundleGenerator; -} +cmMakefileUtilityTargetGenerator::~cmMakefileUtilityTargetGenerator() = + default; void cmMakefileUtilityTargetGenerator::WriteRuleFiles() { diff --git a/Source/cmMessageCommand.cxx b/Source/cmMessageCommand.cxx index 2724030..5320ec5 100644 --- a/Source/cmMessageCommand.cxx +++ b/Source/cmMessageCommand.cxx @@ -8,6 +8,9 @@ #include "cmMessenger.h" #include "cmRange.h" #include "cmSystemTools.h" +#include "cmake.h" + +#include <cassert> class cmExecutionStatus; @@ -19,49 +22,88 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, this->SetError("called with incorrect number of arguments"); return false; } - std::vector<std::string>::const_iterator i = args.begin(); + auto i = args.cbegin(); - MessageType type = MessageType::MESSAGE; - bool status = false; - bool fatal = false; + auto type = MessageType::MESSAGE; + auto status = false; + auto fatal = false; + auto level = cmake::LogLevel::LOG_UNDEFINED; if (*i == "SEND_ERROR") { type = MessageType::FATAL_ERROR; + level = cmake::LogLevel::LOG_ERROR; ++i; } else if (*i == "FATAL_ERROR") { fatal = true; type = MessageType::FATAL_ERROR; + level = cmake::LogLevel::LOG_ERROR; ++i; } else if (*i == "WARNING") { type = MessageType::WARNING; + level = cmake::LogLevel::LOG_WARNING; ++i; } else if (*i == "AUTHOR_WARNING") { if (this->Makefile->IsSet("CMAKE_SUPPRESS_DEVELOPER_ERRORS") && !this->Makefile->IsOn("CMAKE_SUPPRESS_DEVELOPER_ERRORS")) { fatal = true; type = MessageType::AUTHOR_ERROR; + level = cmake::LogLevel::LOG_ERROR; } else if (!this->Makefile->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) { type = MessageType::AUTHOR_WARNING; + level = cmake::LogLevel::LOG_WARNING; } else { return true; } ++i; } else if (*i == "STATUS") { status = true; + level = cmake::LogLevel::LOG_STATUS; + ++i; + } else if (*i == "VERBOSE") { + status = true; + level = cmake::LogLevel::LOG_VERBOSE; + ++i; + } else if (*i == "DEBUG") { + status = true; + level = cmake::LogLevel::LOG_DEBUG; + ++i; + } else if (*i == "TRACE") { + status = true; + level = cmake::LogLevel::LOG_TRACE; ++i; } else if (*i == "DEPRECATION") { if (this->Makefile->IsOn("CMAKE_ERROR_DEPRECATED")) { fatal = true; type = MessageType::DEPRECATION_ERROR; + level = cmake::LogLevel::LOG_ERROR; } else if ((!this->Makefile->IsSet("CMAKE_WARN_DEPRECATED") || this->Makefile->IsOn("CMAKE_WARN_DEPRECATED"))) { type = MessageType::DEPRECATION_WARNING; + level = cmake::LogLevel::LOG_WARNING; } else { return true; } ++i; + } else if (*i == "NOTICE") { + // `NOTICE` message type is going to be output to stderr + level = cmake::LogLevel::LOG_NOTICE; + ++i; + } else { + // Messages w/o any type are `NOTICE`s + level = cmake::LogLevel::LOG_NOTICE; + } + assert("Message log level expected to be set" && + level != cmake::LogLevel::LOG_UNDEFINED); + + auto desiredLevel = this->Makefile->GetCMakeInstance()->GetLogLevel(); + assert("Expected a valid log level here" && + desiredLevel != cmake::LogLevel::LOG_UNDEFINED); + + if (desiredLevel < level) { + // Suppress the message + return true; } - std::string message = cmJoin(cmMakeRange(i, args.end()), std::string()); + auto message = cmJoin(cmMakeRange(i, args.cend()), ""); if (type != MessageType::MESSAGE) { // we've overridden the message type, above, so display it directly diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx index 3300fef..af47fa7 100644 --- a/Source/cmNinjaNormalTargetGenerator.cxx +++ b/Source/cmNinjaNormalTargetGenerator.cxx @@ -54,14 +54,11 @@ cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator( } this->OSXBundleGenerator = - new cmOSXBundleGenerator(target, this->GetConfigName()); + cm::make_unique<cmOSXBundleGenerator>(target, this->GetConfigName()); this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders); } -cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() -{ - delete this->OSXBundleGenerator; -} +cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() = default; void cmNinjaNormalTargetGenerator::Generate() { diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx index 1ad26dd..2324839 100644 --- a/Source/cmNinjaTargetGenerator.cxx +++ b/Source/cmNinjaTargetGenerator.cxx @@ -59,13 +59,10 @@ cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target) , LocalGenerator( static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator())) { - MacOSXContentGenerator = new MacOSXContentGeneratorType(this); + MacOSXContentGenerator = cm::make_unique<MacOSXContentGeneratorType>(this); } -cmNinjaTargetGenerator::~cmNinjaTargetGenerator() -{ - delete this->MacOSXContentGenerator; -} +cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default; cmGeneratedFileStream& cmNinjaTargetGenerator::GetBuildFileStream() const { @@ -813,11 +810,11 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() std::vector<cmSourceFile const*> headerSources; this->GeneratorTarget->GetHeaderSources(headerSources, config); this->OSXBundleGenerator->GenerateMacOSXContentStatements( - headerSources, this->MacOSXContentGenerator); + headerSources, this->MacOSXContentGenerator.get()); std::vector<cmSourceFile const*> extraSources; this->GeneratorTarget->GetExtraSources(extraSources, config); this->OSXBundleGenerator->GenerateMacOSXContentStatements( - extraSources, this->MacOSXContentGenerator); + extraSources, this->MacOSXContentGenerator.get()); std::vector<cmSourceFile const*> externalObjects; this->GeneratorTarget->GetExternalObjects(externalObjects, config); for (cmSourceFile const* sf : externalObjects) { diff --git a/Source/cmNinjaTargetGenerator.h b/Source/cmNinjaTargetGenerator.h index 6a42da0..51c9ac7 100644 --- a/Source/cmNinjaTargetGenerator.h +++ b/Source/cmNinjaTargetGenerator.h @@ -153,9 +153,9 @@ protected: }; friend struct MacOSXContentGeneratorType; - MacOSXContentGeneratorType* MacOSXContentGenerator; + std::unique_ptr<MacOSXContentGeneratorType> MacOSXContentGenerator; // Properly initialized by sub-classes. - cmOSXBundleGenerator* OSXBundleGenerator; + std::unique_ptr<cmOSXBundleGenerator> OSXBundleGenerator; std::set<std::string> MacContentFolders; void addPoolNinjaVariable(const std::string& pool_property, diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h index 02a6295..0e42295 100644 --- a/Source/cmPolicies.h +++ b/Source/cmPolicies.h @@ -267,6 +267,12 @@ class cmMakefile; 15, 0, cmPolicies::WARN) \ SELECT(POLICY, CMP0090, \ "export(PACKAGE) does not populate package registry by default.", 3, \ + 15, 0, cmPolicies::WARN) \ + SELECT(POLICY, CMP0091, \ + "MSVC runtime library flags are selected by an abstraction.", 3, 15, \ + 0, cmPolicies::WARN) \ + SELECT(POLICY, CMP0092, \ + "MSVC warning flags are not in CMAKE_<LANG>_FLAGS by default.", 3, \ 15, 0, cmPolicies::WARN) #define CM_SELECT_ID(F, A1, A2, A3, A4, A5, A6) F(A1) diff --git a/Source/cmQtAutoGenerator.cxx b/Source/cmQtAutoGenerator.cxx index f115016..6fbea82 100644 --- a/Source/cmQtAutoGenerator.cxx +++ b/Source/cmQtAutoGenerator.cxx @@ -14,12 +14,6 @@ #include "cmSystemTools.h" #include "cmake.h" -#include <algorithm> -#include <sstream> -#include <utility> - -// -- Class methods - cmQtAutoGenerator::Logger::Logger() { // Initialize logger @@ -431,232 +425,6 @@ bool cmQtAutoGenerator::FileSystem::MakeParentDirectory( return cmQtAutoGenerator::MakeParentDirectory(filename); } -int cmQtAutoGenerator::ReadOnlyProcessT::PipeT::init(uv_loop_t* uv_loop, - ReadOnlyProcessT* process) -{ - Process_ = process; - Target_ = nullptr; - return UVPipe_.init(*uv_loop, 0, this); -} - -int cmQtAutoGenerator::ReadOnlyProcessT::PipeT::startRead(std::string* target) -{ - Target_ = target; - return uv_read_start(uv_stream(), &PipeT::UVAlloc, &PipeT::UVData); -} - -void cmQtAutoGenerator::ReadOnlyProcessT::PipeT::reset() -{ - Process_ = nullptr; - Target_ = nullptr; - UVPipe_.reset(); - Buffer_.clear(); - Buffer_.shrink_to_fit(); -} - -void cmQtAutoGenerator::ReadOnlyProcessT::PipeT::UVAlloc(uv_handle_t* handle, - size_t suggestedSize, - uv_buf_t* buf) -{ - auto& pipe = *reinterpret_cast<PipeT*>(handle->data); - pipe.Buffer_.resize(suggestedSize); - buf->base = pipe.Buffer_.data(); - buf->len = pipe.Buffer_.size(); -} - -void cmQtAutoGenerator::ReadOnlyProcessT::PipeT::UVData(uv_stream_t* stream, - ssize_t nread, - const uv_buf_t* buf) -{ - auto& pipe = *reinterpret_cast<PipeT*>(stream->data); - if (nread > 0) { - // Append data to merged output - if ((buf->base != nullptr) && (pipe.Target_ != nullptr)) { - pipe.Target_->append(buf->base, nread); - } - } else if (nread < 0) { - // EOF or error - auto* proc = pipe.Process_; - // Check it this an unusual error - if (nread != UV_EOF) { - if (!proc->Result()->error()) { - proc->Result()->ErrorMessage = - "libuv reading from pipe failed with error code "; - proc->Result()->ErrorMessage += std::to_string(nread); - } - } - // Clear libuv pipe handle and try to finish - pipe.reset(); - proc->UVTryFinish(); - } -} - -void cmQtAutoGenerator::ProcessResultT::reset() -{ - ExitStatus = 0; - TermSignal = 0; - if (!StdOut.empty()) { - StdOut.clear(); - StdOut.shrink_to_fit(); - } - if (!StdErr.empty()) { - StdErr.clear(); - StdErr.shrink_to_fit(); - } - if (!ErrorMessage.empty()) { - ErrorMessage.clear(); - ErrorMessage.shrink_to_fit(); - } -} - -void cmQtAutoGenerator::ReadOnlyProcessT::setup( - ProcessResultT* result, bool mergedOutput, - std::vector<std::string> const& command, std::string const& workingDirectory) -{ - Setup_.WorkingDirectory = workingDirectory; - Setup_.Command = command; - Setup_.Result = result; - Setup_.MergedOutput = mergedOutput; -} - -static std::string getUVError(const char* prefixString, int uvErrorCode) -{ - std::ostringstream ost; - ost << prefixString << ": " << uv_strerror(uvErrorCode); - return ost.str(); -} - -bool cmQtAutoGenerator::ReadOnlyProcessT::start( - uv_loop_t* uv_loop, std::function<void()>&& finishedCallback) -{ - if (IsStarted() || (Result() == nullptr)) { - return false; - } - - // Reset result before the start - Result()->reset(); - - // Fill command string pointers - if (!Setup().Command.empty()) { - CommandPtr_.reserve(Setup().Command.size() + 1); - for (std::string const& arg : Setup().Command) { - CommandPtr_.push_back(arg.c_str()); - } - CommandPtr_.push_back(nullptr); - } else { - Result()->ErrorMessage = "Empty command"; - } - - if (!Result()->error()) { - if (UVPipeOut_.init(uv_loop, this) != 0) { - Result()->ErrorMessage = "libuv stdout pipe initialization failed"; - } - } - if (!Result()->error()) { - if (UVPipeErr_.init(uv_loop, this) != 0) { - Result()->ErrorMessage = "libuv stderr pipe initialization failed"; - } - } - if (!Result()->error()) { - // -- Setup process stdio options - // stdin - UVOptionsStdIO_[0].flags = UV_IGNORE; - UVOptionsStdIO_[0].data.stream = nullptr; - // stdout - UVOptionsStdIO_[1].flags = - static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); - UVOptionsStdIO_[1].data.stream = UVPipeOut_.uv_stream(); - // stderr - UVOptionsStdIO_[2].flags = - static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); - UVOptionsStdIO_[2].data.stream = UVPipeErr_.uv_stream(); - - // -- Setup process options - std::fill_n(reinterpret_cast<char*>(&UVOptions_), sizeof(UVOptions_), 0); - UVOptions_.exit_cb = &ReadOnlyProcessT::UVExit; - UVOptions_.file = CommandPtr_[0]; - UVOptions_.args = const_cast<char**>(CommandPtr_.data()); - UVOptions_.cwd = Setup_.WorkingDirectory.c_str(); - UVOptions_.flags = UV_PROCESS_WINDOWS_HIDE; - UVOptions_.stdio_count = static_cast<int>(UVOptionsStdIO_.size()); - UVOptions_.stdio = UVOptionsStdIO_.data(); - - // -- Spawn process - int uvErrorCode = UVProcess_.spawn(*uv_loop, UVOptions_, this); - if (uvErrorCode != 0) { - Result()->ErrorMessage = - getUVError("libuv process spawn failed ", uvErrorCode); - } - } - // -- Start reading from stdio streams - if (!Result()->error()) { - if (UVPipeOut_.startRead(&Result()->StdOut) != 0) { - Result()->ErrorMessage = "libuv start reading from stdout pipe failed"; - } - } - if (!Result()->error()) { - if (UVPipeErr_.startRead(Setup_.MergedOutput ? &Result()->StdOut - : &Result()->StdErr) != 0) { - Result()->ErrorMessage = "libuv start reading from stderr pipe failed"; - } - } - - if (!Result()->error()) { - IsStarted_ = true; - FinishedCallback_ = std::move(finishedCallback); - } else { - // Clear libuv handles and finish - UVProcess_.reset(); - UVPipeOut_.reset(); - UVPipeErr_.reset(); - CommandPtr_.clear(); - } - - return IsStarted(); -} - -void cmQtAutoGenerator::ReadOnlyProcessT::UVExit(uv_process_t* handle, - int64_t exitStatus, - int termSignal) -{ - auto& proc = *reinterpret_cast<ReadOnlyProcessT*>(handle->data); - if (proc.IsStarted() && !proc.IsFinished()) { - // Set error message on demand - proc.Result()->ExitStatus = exitStatus; - proc.Result()->TermSignal = termSignal; - if (!proc.Result()->error()) { - if (termSignal != 0) { - proc.Result()->ErrorMessage = "Process was terminated by signal "; - proc.Result()->ErrorMessage += - std::to_string(proc.Result()->TermSignal); - } else if (exitStatus != 0) { - proc.Result()->ErrorMessage = "Process failed with return value "; - proc.Result()->ErrorMessage += - std::to_string(proc.Result()->ExitStatus); - } - } - - // Reset process handle and try to finish - proc.UVProcess_.reset(); - proc.UVTryFinish(); - } -} - -void cmQtAutoGenerator::ReadOnlyProcessT::UVTryFinish() -{ - // There still might be data in the pipes after the process has finished. - // Therefore check if the process is finished AND all pipes are closed - // before signaling the worker thread to continue. - if (UVProcess_.get() == nullptr) { - if (UVPipeOut_.uv_pipe() == nullptr) { - if (UVPipeErr_.uv_pipe() == nullptr) { - IsFinished_ = true; - FinishedCallback_(); - } - } - } -} - cmQtAutoGenerator::cmQtAutoGenerator() = default; cmQtAutoGenerator::~cmQtAutoGenerator() = default; diff --git a/Source/cmQtAutoGenerator.h b/Source/cmQtAutoGenerator.h index 479d357..437fa20 100644 --- a/Source/cmQtAutoGenerator.h +++ b/Source/cmQtAutoGenerator.h @@ -7,14 +7,8 @@ #include "cmFilePathChecksum.h" #include "cmQtAutoGen.h" -#include "cmUVHandlePtr.h" -#include "cm_uv.h" -#include <array> -#include <functional> #include <mutex> -#include <stddef.h> -#include <stdint.h> #include <string> #include <vector> @@ -137,102 +131,6 @@ public: cmFilePathChecksum FilePathChecksum_; }; - /// @brief Return value and output of an external process - struct ProcessResultT - { - void reset(); - bool error() const - { - return (ExitStatus != 0) || (TermSignal != 0) || !ErrorMessage.empty(); - } - - std::int64_t ExitStatus = 0; - int TermSignal = 0; - std::string StdOut; - std::string StdErr; - std::string ErrorMessage; - }; - - /// @brief External process management class - struct ReadOnlyProcessT - { - // -- Types - - /// @brief libuv pipe buffer class - class PipeT - { - public: - int init(uv_loop_t* uv_loop, ReadOnlyProcessT* process); - int startRead(std::string* target); - void reset(); - - // -- Libuv casts - uv_pipe_t* uv_pipe() { return UVPipe_.get(); } - uv_stream_t* uv_stream() - { - return reinterpret_cast<uv_stream_t*>(uv_pipe()); - } - uv_handle_t* uv_handle() - { - return reinterpret_cast<uv_handle_t*>(uv_pipe()); - } - - // -- Libuv callbacks - static void UVAlloc(uv_handle_t* handle, size_t suggestedSize, - uv_buf_t* buf); - static void UVData(uv_stream_t* stream, ssize_t nread, - const uv_buf_t* buf); - - private: - ReadOnlyProcessT* Process_ = nullptr; - std::string* Target_ = nullptr; - std::vector<char> Buffer_; - cm::uv_pipe_ptr UVPipe_; - }; - - /// @brief Process settings - struct SetupT - { - std::string WorkingDirectory; - std::vector<std::string> Command; - ProcessResultT* Result = nullptr; - bool MergedOutput = false; - }; - - // -- Const accessors - const SetupT& Setup() const { return Setup_; } - ProcessResultT* Result() const { return Setup_.Result; } - bool IsStarted() const { return IsStarted_; } - bool IsFinished() const { return IsFinished_; } - - // -- Runtime - void setup(ProcessResultT* result, bool mergedOutput, - std::vector<std::string> const& command, - std::string const& workingDirectory = std::string()); - bool start(uv_loop_t* uv_loop, std::function<void()>&& finishedCallback); - - private: - // -- Friends - friend class PipeT; - // -- Libuv callbacks - static void UVExit(uv_process_t* handle, int64_t exitStatus, - int termSignal); - void UVTryFinish(); - - // -- Setup - SetupT Setup_; - // -- Runtime - bool IsStarted_ = false; - bool IsFinished_ = false; - std::function<void()> FinishedCallback_; - std::vector<const char*> CommandPtr_; - std::array<uv_stdio_container_t, 3> UVOptionsStdIO_; - uv_process_options_t UVOptions_; - cm::uv_process_ptr UVProcess_; - PipeT UVPipeOut_; - PipeT UVPipeErr_; - }; - public: // -- Constructors cmQtAutoGenerator(); diff --git a/Source/cmQtAutoGeneratorMocUic.cxx b/Source/cmQtAutoMocUic.cxx index ec1a1aa..005c27d 100644 --- a/Source/cmQtAutoGeneratorMocUic.cxx +++ b/Source/cmQtAutoMocUic.cxx @@ -1,10 +1,10 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ -#include "cmQtAutoGeneratorMocUic.h" +#include "cmQtAutoMocUic.h" #include <algorithm> #include <array> -#include <cstddef> +#include <deque> #include <list> #include <memory> #include <set> @@ -24,7 +24,7 @@ // -- Class methods -std::string cmQtAutoGeneratorMocUic::BaseSettingsT::AbsoluteBuildPath( +std::string cmQtAutoMocUic::BaseSettingsT::AbsoluteBuildPath( std::string const& relativePath) const { return FileSys->CollapseFullPath(relativePath, AutogenBuildDir); @@ -35,7 +35,7 @@ std::string cmQtAutoGeneratorMocUic::BaseSettingsT::AbsoluteBuildPath( * appending different header extensions * @return True on success */ -bool cmQtAutoGeneratorMocUic::BaseSettingsT::FindHeader( +bool cmQtAutoMocUic::BaseSettingsT::FindHeader( std::string& header, std::string const& testBasePath) const { for (std::string const& ext : HeaderExtensions) { @@ -50,8 +50,7 @@ bool cmQtAutoGeneratorMocUic::BaseSettingsT::FindHeader( return false; } -bool cmQtAutoGeneratorMocUic::MocSettingsT::skipped( - std::string const& fileName) const +bool cmQtAutoMocUic::MocSettingsT::skipped(std::string const& fileName) const { return (!Enabled || (SkipList.find(fileName) != SkipList.end())); } @@ -60,7 +59,7 @@ bool cmQtAutoGeneratorMocUic::MocSettingsT::skipped( * @brief Returns the first relevant Qt macro name found in the given C++ code * @return The name of the Qt macro or an empty string */ -std::string cmQtAutoGeneratorMocUic::MocSettingsT::FindMacro( +std::string cmQtAutoMocUic::MocSettingsT::FindMacro( std::string const& content) const { for (KeyExpT const& filter : MacroFilters) { @@ -77,7 +76,7 @@ std::string cmQtAutoGeneratorMocUic::MocSettingsT::FindMacro( return std::string(); } -std::string cmQtAutoGeneratorMocUic::MocSettingsT::MacrosString() const +std::string cmQtAutoMocUic::MocSettingsT::MacrosString() const { std::string res; const auto itB = MacroFilters.cbegin(); @@ -99,7 +98,7 @@ std::string cmQtAutoGeneratorMocUic::MocSettingsT::MacrosString() const return res; } -std::string cmQtAutoGeneratorMocUic::MocSettingsT::FindIncludedFile( +std::string cmQtAutoMocUic::MocSettingsT::FindIncludedFile( std::string const& sourcePath, std::string const& includeString) const { // Search in vicinity of the source @@ -123,7 +122,7 @@ std::string cmQtAutoGeneratorMocUic::MocSettingsT::FindIncludedFile( return std::string(); } -void cmQtAutoGeneratorMocUic::MocSettingsT::FindDependencies( +void cmQtAutoMocUic::MocSettingsT::FindDependencies( std::string const& content, std::set<std::string>& depends) const { if (!DependFilters.empty() && !content.empty()) { @@ -147,17 +146,124 @@ void cmQtAutoGeneratorMocUic::MocSettingsT::FindDependencies( } } -bool cmQtAutoGeneratorMocUic::UicSettingsT::skipped( - std::string const& fileName) const +bool cmQtAutoMocUic::UicSettingsT::skipped(std::string const& fileName) const { return (!Enabled || (SkipList.find(fileName) != SkipList.end())); } -void cmQtAutoGeneratorMocUic::JobParseT::Process(WorkerT& wrk) +void cmQtAutoMocUic::JobT::LogError(GenT genType, + std::string const& message) const +{ + Gen()->AbortError(); + Gen()->Log().Error(genType, message); +} + +void cmQtAutoMocUic::JobT::LogFileError(GenT genType, + std::string const& filename, + std::string const& message) const +{ + Gen()->AbortError(); + Gen()->Log().ErrorFile(genType, filename, message); +} + +void cmQtAutoMocUic::JobT::LogCommandError( + GenT genType, std::string const& message, + std::vector<std::string> const& command, std::string const& output) const +{ + Gen()->AbortError(); + Gen()->Log().ErrorCommand(genType, message, command, output); +} + +bool cmQtAutoMocUic::JobT::RunProcess(GenT genType, + cmWorkerPool::ProcessResultT& result, + std::vector<std::string> const& command) +{ + // Log command + if (Log().Verbose()) { + std::string msg = "Running command:\n"; + msg += QuotedCommand(command); + msg += '\n'; + Log().Info(genType, msg); + } + return cmWorkerPool::JobT::RunProcess(result, command, + Gen()->Base().AutogenBuildDir); +} + +void cmQtAutoMocUic::JobMocPredefsT::Process() +{ + // (Re)generate moc_predefs.h on demand + bool generate(false); + bool fileExists(FileSys().FileExists(Gen()->Moc().PredefsFileAbs)); + if (!fileExists) { + if (Log().Verbose()) { + std::string reason = "Generating "; + reason += Quoted(Gen()->Moc().PredefsFileRel); + reason += " because it doesn't exist"; + Log().Info(GenT::MOC, reason); + } + generate = true; + } else if (Gen()->Moc().SettingsChanged) { + if (Log().Verbose()) { + std::string reason = "Generating "; + reason += Quoted(Gen()->Moc().PredefsFileRel); + reason += " because the settings changed."; + Log().Info(GenT::MOC, reason); + } + generate = true; + } + if (generate) { + cmWorkerPool::ProcessResultT result; + { + // Compose command + std::vector<std::string> cmd = Gen()->Moc().PredefsCmd; + // Add includes + cmd.insert(cmd.end(), Gen()->Moc().Includes.begin(), + Gen()->Moc().Includes.end()); + // Add definitions + for (std::string const& def : Gen()->Moc().Definitions) { + cmd.push_back("-D" + def); + } + // Execute command + if (!RunProcess(GenT::MOC, result, cmd)) { + std::string emsg = "The content generation command for "; + emsg += Quoted(Gen()->Moc().PredefsFileRel); + emsg += " failed.\n"; + emsg += result.ErrorMessage; + LogCommandError(GenT::MOC, emsg, cmd, result.StdOut); + } + } + + // (Re)write predefs file only on demand + if (!result.error()) { + if (!fileExists || + FileSys().FileDiffers(Gen()->Moc().PredefsFileAbs, result.StdOut)) { + if (FileSys().FileWrite(Gen()->Moc().PredefsFileAbs, result.StdOut)) { + // Success + } else { + std::string emsg = "Writing "; + emsg += Quoted(Gen()->Moc().PredefsFileRel); + emsg += " failed."; + LogFileError(GenT::MOC, Gen()->Moc().PredefsFileAbs, emsg); + } + } else { + // Touch to update the time stamp + if (Log().Verbose()) { + std::string msg = "Touching "; + msg += Quoted(Gen()->Moc().PredefsFileRel); + msg += "."; + Log().Info(GenT::MOC, msg); + } + FileSys().Touch(Gen()->Moc().PredefsFileAbs); + } + } + } +} + +void cmQtAutoMocUic::JobParseT::Process() { if (AutoMoc && Header) { // Don't parse header for moc if the file is included by a source already - if (wrk.Gen().ParallelMocIncluded(FileName)) { + if (Gen()->ParallelMocIncluded(FileName)) { AutoMoc = false; } } @@ -165,35 +271,32 @@ void cmQtAutoGeneratorMocUic::JobParseT::Process(WorkerT& wrk) if (AutoMoc || AutoUic) { std::string error; MetaT meta; - if (wrk.FileSys().FileRead(meta.Content, FileName, &error)) { + if (FileSys().FileRead(meta.Content, FileName, &error)) { if (!meta.Content.empty()) { - meta.FileDir = wrk.FileSys().SubDirPrefix(FileName); - meta.FileBase = - wrk.FileSys().GetFilenameWithoutLastExtension(FileName); + meta.FileDir = FileSys().SubDirPrefix(FileName); + meta.FileBase = FileSys().GetFilenameWithoutLastExtension(FileName); bool success = true; if (AutoMoc) { if (Header) { - success = ParseMocHeader(wrk, meta); + success = ParseMocHeader(meta); } else { - success = ParseMocSource(wrk, meta); + success = ParseMocSource(meta); } } if (AutoUic && success) { - ParseUic(wrk, meta); + ParseUic(meta); } } else { - wrk.LogFileWarning(GenT::GEN, FileName, "The source file is empty"); + Log().WarningFile(GenT::GEN, FileName, "The source file is empty"); } } else { - wrk.LogFileError(GenT::GEN, FileName, - "Could not read the file: " + error); + LogFileError(GenT::GEN, FileName, "Could not read the file: " + error); } } } -bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, - MetaT const& meta) +bool cmQtAutoMocUic::JobParseT::ParseMocSource(MetaT const& meta) { struct JobPre { @@ -211,7 +314,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, }; // Check if this source file contains a relevant macro - std::string const ownMacro = wrk.Moc().FindMacro(meta.Content); + std::string const ownMacro = Gen()->Moc().FindMacro(meta.Content); // Extract moc includes from file std::deque<MocInclude> mocIncsUsc; @@ -220,11 +323,11 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, if (meta.Content.find("moc") != std::string::npos) { const char* contentChars = meta.Content.c_str(); cmsys::RegularExpressionMatch match; - while (wrk.Moc().RegExpInclude.find(contentChars, match)) { + while (Gen()->Moc().RegExpInclude.find(contentChars, match)) { std::string incString = match.match(2); - std::string incDir(wrk.FileSys().SubDirPrefix(incString)); + std::string incDir(FileSys().SubDirPrefix(incString)); std::string incBase = - wrk.FileSys().GetFilenameWithoutLastExtension(incString); + FileSys().GetFilenameWithoutLastExtension(incString); if (cmHasLiteralPrefix(incBase, "moc_")) { // moc_<BASE>.cxx // Remove the moc_ part from the base name @@ -253,10 +356,10 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, // Process moc_<BASE>.cxx includes for (const MocInclude& mocInc : mocIncsUsc) { std::string const header = - MocFindIncludedHeader(wrk, meta.FileDir, mocInc.Dir + mocInc.Base); + MocFindIncludedHeader(meta.FileDir, mocInc.Dir + mocInc.Base); if (!header.empty()) { // Check if header is skipped - if (wrk.Moc().skipped(header)) { + if (Gen()->Moc().skipped(header)) { continue; } // Register moc job @@ -271,9 +374,9 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, std::string emsg = "The file includes the moc file "; emsg += Quoted(mocInc.Inc); emsg += ", but the header "; - emsg += Quoted(MocStringHeaders(wrk, mocInc.Base)); + emsg += Quoted(MocStringHeaders(mocInc.Base)); emsg += " could not be found."; - wrk.LogFileError(GenT::MOC, FileName, emsg); + LogFileError(GenT::MOC, FileName, emsg); } return false; } @@ -282,7 +385,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, // Process <BASE>.moc includes for (const MocInclude& mocInc : mocIncsDot) { const bool ownMoc = (mocInc.Base == meta.FileBase); - if (wrk.Moc().RelaxedMode) { + if (Gen()->Moc().RelaxedMode) { // Relaxed mode if (!ownMacro.empty() && ownMoc) { // Add self @@ -292,10 +395,10 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, // In relaxed mode try to find a header instead but issue a warning. // This is for KDE4 compatibility std::string const header = - MocFindIncludedHeader(wrk, meta.FileDir, mocInc.Dir + mocInc.Base); + MocFindIncludedHeader(meta.FileDir, mocInc.Dir + mocInc.Base); if (!header.empty()) { // Check if header is skipped - if (wrk.Moc().skipped(header)) { + if (Gen()->Moc().skipped(header)) { continue; } // Register moc job @@ -305,14 +408,14 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, std::string emsg = "The file includes the moc file "; emsg += Quoted(mocInc.Inc); emsg += ", but does not contain a "; - emsg += wrk.Moc().MacrosString(); + emsg += Gen()->Moc().MacrosString(); emsg += " macro.\nRunning moc on\n "; emsg += Quoted(header); emsg += "!\nBetter include "; emsg += Quoted("moc_" + mocInc.Base + ".cpp"); emsg += " for a compatibility with strict mode.\n" "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n"; - wrk.LogFileWarning(GenT::MOC, FileName, emsg); + Log().WarningFile(GenT::MOC, FileName, emsg); } else { std::string emsg = "The file includes the moc file "; emsg += Quoted(mocInc.Inc); @@ -324,7 +427,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, emsg += Quoted("moc_" + mocInc.Base + ".cpp"); emsg += " for compatibility with strict mode.\n" "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n"; - wrk.LogFileWarning(GenT::MOC, FileName, emsg); + Log().WarningFile(GenT::MOC, FileName, emsg); } } } else { @@ -334,9 +437,9 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, emsg += ", which seems to be the moc file from a different " "source file.\nCMAKE_AUTOMOC_RELAXED_MODE: Also a " "matching header "; - emsg += Quoted(MocStringHeaders(wrk, mocInc.Base)); + emsg += Quoted(MocStringHeaders(mocInc.Base)); emsg += " could not be found."; - wrk.LogFileError(GenT::MOC, FileName, emsg); + LogFileError(GenT::MOC, FileName, emsg); } return false; } @@ -352,9 +455,9 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, std::string emsg = "The file includes the moc file "; emsg += Quoted(mocInc.Inc); emsg += ", but does not contain a "; - emsg += wrk.Moc().MacrosString(); + emsg += Gen()->Moc().MacrosString(); emsg += " macro."; - wrk.LogFileWarning(GenT::MOC, FileName, emsg); + Log().WarningFile(GenT::MOC, FileName, emsg); } } else { // Don't allow <BASE>.moc include other than self in strict mode @@ -365,7 +468,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, "source file.\nThis is not supported. Include "; emsg += Quoted(meta.FileBase + ".moc"); emsg += " to run moc on this source file."; - wrk.LogFileError(GenT::MOC, FileName, emsg); + LogFileError(GenT::MOC, FileName, emsg); } return false; } @@ -379,7 +482,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, // 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. // This is for KDE4 compatibility. - if (wrk.Moc().RelaxedMode && ownMocUscIncluded) { + if (Gen()->Moc().RelaxedMode && ownMocUscIncluded) { JobPre uscJobPre; // Remove underscore job request { @@ -408,7 +511,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, emsg += Quoted(meta.FileBase + ".moc"); emsg += " for compatibility with strict mode.\n" "(CMAKE_AUTOMOC_RELAXED_MODE warning)"; - wrk.LogFileWarning(GenT::MOC, FileName, emsg); + Log().WarningFile(GenT::MOC, FileName, emsg); } // Add own source job jobs.emplace_back( @@ -423,7 +526,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, emsg += "!\nConsider to\n - add #include \""; emsg += meta.FileBase; emsg += ".moc\"\n - enable SKIP_AUTOMOC for this file"; - wrk.LogFileError(GenT::MOC, FileName, emsg); + LogFileError(GenT::MOC, FileName, emsg); } return false; } @@ -431,76 +534,80 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, // Convert pre jobs to actual jobs for (JobPre& jobPre : jobs) { - JobHandleT jobHandle = cm::make_unique<JobMocT>( + cmWorkerPool::JobHandleT jobHandle = cm::make_unique<JobMocT>( std::move(jobPre.SourceFile), FileName, std::move(jobPre.IncludeString)); if (jobPre.self) { // Read dependencies from this source - static_cast<JobMocT&>(*jobHandle).FindDependencies(wrk, meta.Content); + JobMocT& jobMoc = static_cast<JobMocT&>(*jobHandle); + Gen()->Moc().FindDependencies(meta.Content, jobMoc.Depends); + jobMoc.DependsValid = true; } - if (!wrk.Gen().ParallelJobPushMoc(jobHandle)) { + if (!Gen()->ParallelJobPushMoc(std::move(jobHandle))) { return false; } } return true; } -bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocHeader(WorkerT& wrk, - MetaT const& meta) +bool cmQtAutoMocUic::JobParseT::ParseMocHeader(MetaT const& meta) { bool success = true; - std::string const macroName = wrk.Moc().FindMacro(meta.Content); + std::string const macroName = Gen()->Moc().FindMacro(meta.Content); if (!macroName.empty()) { - JobHandleT jobHandle = cm::make_unique<JobMocT>( + cmWorkerPool::JobHandleT jobHandle = cm::make_unique<JobMocT>( std::string(FileName), std::string(), std::string()); // Read dependencies from this source - static_cast<JobMocT&>(*jobHandle).FindDependencies(wrk, meta.Content); - success = wrk.Gen().ParallelJobPushMoc(jobHandle); + { + JobMocT& jobMoc = static_cast<JobMocT&>(*jobHandle); + Gen()->Moc().FindDependencies(meta.Content, jobMoc.Depends); + jobMoc.DependsValid = true; + } + success = Gen()->ParallelJobPushMoc(std::move(jobHandle)); } return success; } -std::string cmQtAutoGeneratorMocUic::JobParseT::MocStringHeaders( - WorkerT& wrk, std::string const& fileBase) const +std::string cmQtAutoMocUic::JobParseT::MocStringHeaders( + std::string const& fileBase) const { std::string res = fileBase; res += ".{"; - res += cmJoin(wrk.Base().HeaderExtensions, ","); + res += cmJoin(Gen()->Base().HeaderExtensions, ","); res += "}"; return res; } -std::string cmQtAutoGeneratorMocUic::JobParseT::MocFindIncludedHeader( - WorkerT& wrk, std::string const& includerDir, std::string const& includeBase) +std::string cmQtAutoMocUic::JobParseT::MocFindIncludedHeader( + std::string const& includerDir, std::string const& includeBase) { std::string header; // Search in vicinity of the source - if (!wrk.Base().FindHeader(header, includerDir + includeBase)) { + if (!Gen()->Base().FindHeader(header, includerDir + includeBase)) { // Search in include directories - for (std::string const& path : wrk.Moc().IncludePaths) { + for (std::string const& path : Gen()->Moc().IncludePaths) { std::string fullPath = path; fullPath.push_back('/'); fullPath += includeBase; - if (wrk.Base().FindHeader(header, fullPath)) { + if (Gen()->Base().FindHeader(header, fullPath)) { break; } } } // Sanitize if (!header.empty()) { - header = wrk.FileSys().GetRealPath(header); + header = FileSys().GetRealPath(header); } return header; } -bool cmQtAutoGeneratorMocUic::JobParseT::ParseUic(WorkerT& wrk, - MetaT const& meta) +bool cmQtAutoMocUic::JobParseT::ParseUic(MetaT const& meta) { bool success = true; if (meta.Content.find("ui_") != std::string::npos) { const char* contentChars = meta.Content.c_str(); cmsys::RegularExpressionMatch match; - while (wrk.Uic().RegExpInclude.find(contentChars, match)) { - if (!ParseUicInclude(wrk, meta, match.match(2))) { + while (Gen()->Uic().RegExpInclude.find(contentChars, match)) { + if (!ParseUicInclude(meta, match.match(2))) { success = false; break; } @@ -510,16 +617,16 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseUic(WorkerT& wrk, return success; } -bool cmQtAutoGeneratorMocUic::JobParseT::ParseUicInclude( - WorkerT& wrk, MetaT const& meta, std::string&& includeString) +bool cmQtAutoMocUic::JobParseT::ParseUicInclude(MetaT const& meta, + std::string&& includeString) { bool success = false; - std::string uiInputFile = UicFindIncludedFile(wrk, meta, includeString); + std::string uiInputFile = UicFindIncludedFile(meta, includeString); if (!uiInputFile.empty()) { - if (!wrk.Uic().skipped(uiInputFile)) { - JobHandleT jobHandle = cm::make_unique<JobUicT>( + if (!Gen()->Uic().skipped(uiInputFile)) { + cmWorkerPool::JobHandleT jobHandle = cm::make_unique<JobUicT>( std::move(uiInputFile), FileName, std::move(includeString)); - success = wrk.Gen().ParallelJobPushUic(jobHandle); + success = Gen()->ParallelJobPushUic(std::move(jobHandle)); } else { // A skipped file is successful success = true; @@ -528,17 +635,17 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseUicInclude( return success; } -std::string cmQtAutoGeneratorMocUic::JobParseT::UicFindIncludedFile( - WorkerT& wrk, MetaT const& meta, std::string const& includeString) +std::string cmQtAutoMocUic::JobParseT::UicFindIncludedFile( + MetaT const& meta, std::string const& includeString) { std::string res; std::string searchFile = - wrk.FileSys().GetFilenameWithoutLastExtension(includeString).substr(3); + FileSys().GetFilenameWithoutLastExtension(includeString).substr(3); searchFile += ".ui"; // Collect search paths list std::deque<std::string> testFiles; { - std::string const searchPath = wrk.FileSys().SubDirPrefix(includeString); + std::string const searchPath = FileSys().SubDirPrefix(includeString); std::string searchFileFull; if (!searchPath.empty()) { @@ -554,12 +661,12 @@ std::string cmQtAutoGeneratorMocUic::JobParseT::UicFindIncludedFile( } } // AUTOUIC search paths - if (!wrk.Uic().SearchPaths.empty()) { - for (std::string const& sPath : wrk.Uic().SearchPaths) { + if (!Gen()->Uic().SearchPaths.empty()) { + for (std::string const& sPath : Gen()->Uic().SearchPaths) { testFiles.push_back((sPath + "/").append(searchFile)); } if (!searchPath.empty()) { - for (std::string const& sPath : wrk.Uic().SearchPaths) { + for (std::string const& sPath : Gen()->Uic().SearchPaths) { testFiles.push_back((sPath + "/").append(searchFileFull)); } } @@ -568,8 +675,8 @@ std::string cmQtAutoGeneratorMocUic::JobParseT::UicFindIncludedFile( // Search for the .ui file! for (std::string const& testFile : testFiles) { - if (wrk.FileSys().FileExists(testFile)) { - res = wrk.FileSys().GetRealPath(testFile); + if (FileSys().FileExists(testFile)) { + res = FileSys().GetRealPath(testFile); break; } } @@ -584,162 +691,140 @@ std::string cmQtAutoGeneratorMocUic::JobParseT::UicFindIncludedFile( emsg += Quoted(testFile); emsg += "\n"; } - wrk.LogFileError(GenT::UIC, FileName, emsg); + LogFileError(GenT::UIC, FileName, emsg); } return res; } -void cmQtAutoGeneratorMocUic::JobMocPredefsT::Process(WorkerT& wrk) +void cmQtAutoMocUic::JobPostParseT::Process() { - // (Re)generate moc_predefs.h on demand - bool generate(false); - bool fileExists(wrk.FileSys().FileExists(wrk.Moc().PredefsFileAbs)); - if (!fileExists) { - if (wrk.Log().Verbose()) { - std::string reason = "Generating "; - reason += Quoted(wrk.Moc().PredefsFileRel); - reason += " because it doesn't exist"; - wrk.LogInfo(GenT::MOC, reason); - } - generate = true; - } else if (wrk.Moc().SettingsChanged) { - if (wrk.Log().Verbose()) { - std::string reason = "Generating "; - reason += Quoted(wrk.Moc().PredefsFileRel); - reason += " because the settings changed."; - wrk.LogInfo(GenT::MOC, reason); - } - generate = true; + if (Gen()->Moc().Enabled) { + // Add mocs compilations fence job + Gen()->WorkerPool().EmplaceJob<JobMocsCompilationT>(); } - if (generate) { - ProcessResultT result; - { - // Compose command - std::vector<std::string> cmd = wrk.Moc().PredefsCmd; - // Add includes - cmd.insert(cmd.end(), wrk.Moc().Includes.begin(), - wrk.Moc().Includes.end()); - // Add definitions - for (std::string const& def : wrk.Moc().Definitions) { - cmd.push_back("-D" + def); - } - // Execute command - if (!wrk.RunProcess(GenT::MOC, result, cmd)) { - std::string emsg = "The content generation command for "; - emsg += Quoted(wrk.Moc().PredefsFileRel); - emsg += " failed.\n"; - emsg += result.ErrorMessage; - wrk.LogCommandError(GenT::MOC, emsg, cmd, result.StdOut); - } + // Add finish job + Gen()->WorkerPool().EmplaceJob<JobFinishT>(); +} + +void cmQtAutoMocUic::JobMocsCompilationT::Process() +{ + // Compose mocs compilation file content + std::string content = + "// This file is autogenerated. Changes will be overwritten.\n"; + if (Gen()->MocAutoFiles().empty()) { + // Placeholder content + content += "// No files found that require moc or the moc files are " + "included\n"; + content += "enum some_compilers { need_more_than_nothing };\n"; + } else { + // Valid content + char const sbeg = Gen()->Base().MultiConfig ? '<' : '"'; + char const send = Gen()->Base().MultiConfig ? '>' : '"'; + for (std::string const& mocfile : Gen()->MocAutoFiles()) { + content += "#include "; + content += sbeg; + content += mocfile; + content += send; + content += '\n'; } + } - // (Re)write predefs file only on demand - if (!result.error()) { - if (!fileExists || - wrk.FileSys().FileDiffers(wrk.Moc().PredefsFileAbs, result.StdOut)) { - std::string error; - if (wrk.FileSys().FileWrite(wrk.Moc().PredefsFileAbs, result.StdOut, - &error)) { - // Success - } else { - std::string emsg = "Writing "; - emsg += Quoted(wrk.Moc().PredefsFileRel); - emsg += " failed. "; - emsg += error; - wrk.LogFileError(GenT::MOC, wrk.Moc().PredefsFileAbs, emsg); - } - } else { - // Touch to update the time stamp - if (wrk.Log().Verbose()) { - std::string msg = "Touching "; - msg += Quoted(wrk.Moc().PredefsFileRel); - msg += "."; - wrk.LogInfo(GenT::MOC, msg); - } - wrk.FileSys().Touch(wrk.Moc().PredefsFileAbs); - } + std::string const& compAbs = Gen()->Moc().CompFileAbs; + if (FileSys().FileDiffers(compAbs, content)) { + // Actually write mocs compilation file + if (Log().Verbose()) { + Log().Info(GenT::MOC, "Generating MOC compilation " + compAbs); + } + if (!FileSys().FileWrite(compAbs, content)) { + LogFileError(GenT::MOC, compAbs, + "mocs compilation file writing failed."); + } + } else if (Gen()->MocAutoFileUpdated()) { + // Only touch mocs compilation file + if (Log().Verbose()) { + Log().Info(GenT::MOC, "Touching mocs compilation " + compAbs); } + FileSys().Touch(compAbs); } } -void cmQtAutoGeneratorMocUic::JobMocT::FindDependencies( - WorkerT& wrk, std::string const& content) +void cmQtAutoMocUic::JobMocT::FindDependencies(std::string const& content) { - wrk.Moc().FindDependencies(content, Depends); + Gen()->Moc().FindDependencies(content, Depends); DependsValid = true; } -void cmQtAutoGeneratorMocUic::JobMocT::Process(WorkerT& wrk) +void cmQtAutoMocUic::JobMocT::Process() { // Compute build file name if (!IncludeString.empty()) { - BuildFile = wrk.Base().AutogenIncludeDir; + BuildFile = Gen()->Base().AutogenIncludeDir; BuildFile += '/'; BuildFile += IncludeString; } else { // Relative build path - std::string relPath = wrk.FileSys().GetFilePathChecksum(SourceFile); + std::string relPath = FileSys().GetFilePathChecksum(SourceFile); relPath += "/moc_"; - relPath += wrk.FileSys().GetFilenameWithoutLastExtension(SourceFile); + relPath += FileSys().GetFilenameWithoutLastExtension(SourceFile); // Register relative file path with duplication check - relPath = wrk.Gen().ParallelMocAutoRegister(relPath); + relPath = Gen()->ParallelMocAutoRegister(relPath); // Absolute build path - if (wrk.Base().MultiConfig) { - BuildFile = wrk.Base().AutogenIncludeDir; + if (Gen()->Base().MultiConfig) { + BuildFile = Gen()->Base().AutogenIncludeDir; BuildFile += '/'; BuildFile += relPath; } else { - BuildFile = wrk.Base().AbsoluteBuildPath(relPath); + BuildFile = Gen()->Base().AbsoluteBuildPath(relPath); } } - if (UpdateRequired(wrk)) { - GenerateMoc(wrk); + if (UpdateRequired()) { + GenerateMoc(); } } -bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) +bool cmQtAutoMocUic::JobMocT::UpdateRequired() { - bool const verbose = wrk.Gen().Log().Verbose(); + bool const verbose = Log().Verbose(); // Test if the build file exists - if (!wrk.FileSys().FileExists(BuildFile)) { + if (!FileSys().FileExists(BuildFile)) { if (verbose) { std::string reason = "Generating "; reason += Quoted(BuildFile); reason += " from its source file "; reason += Quoted(SourceFile); reason += " because it doesn't exist"; - wrk.LogInfo(GenT::MOC, reason); + Log().Info(GenT::MOC, reason); } return true; } // Test if any setting changed - if (wrk.Moc().SettingsChanged) { + if (Gen()->Moc().SettingsChanged) { if (verbose) { std::string reason = "Generating "; reason += Quoted(BuildFile); reason += " from "; reason += Quoted(SourceFile); reason += " because the MOC settings changed"; - wrk.LogInfo(GenT::MOC, reason); + Log().Info(GenT::MOC, reason); } return true; } // Test if the moc_predefs file is newer - if (!wrk.Moc().PredefsFileAbs.empty()) { + if (!Gen()->Moc().PredefsFileAbs.empty()) { bool isOlder = false; { std::string error; - isOlder = wrk.FileSys().FileIsOlderThan( - BuildFile, wrk.Moc().PredefsFileAbs, &error); + isOlder = FileSys().FileIsOlderThan(BuildFile, + Gen()->Moc().PredefsFileAbs, &error); if (!isOlder && !error.empty()) { - wrk.LogError(GenT::MOC, error); + LogError(GenT::MOC, error); return false; } } @@ -748,8 +833,8 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) std::string reason = "Generating "; reason += Quoted(BuildFile); reason += " because it's older than: "; - reason += Quoted(wrk.Moc().PredefsFileAbs); - wrk.LogInfo(GenT::MOC, reason); + reason += Quoted(Gen()->Moc().PredefsFileAbs); + Log().Info(GenT::MOC, reason); } return true; } @@ -760,9 +845,9 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) bool isOlder = false; { std::string error; - isOlder = wrk.FileSys().FileIsOlderThan(BuildFile, SourceFile, &error); + isOlder = FileSys().FileIsOlderThan(BuildFile, SourceFile, &error); if (!isOlder && !error.empty()) { - wrk.LogError(GenT::MOC, error); + LogError(GenT::MOC, error); return false; } } @@ -772,7 +857,7 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) reason += Quoted(BuildFile); reason += " because it's older than its source file "; reason += Quoted(SourceFile); - wrk.LogInfo(GenT::MOC, reason); + Log().Info(GenT::MOC, reason); } return true; } @@ -785,7 +870,7 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) std::string content; { std::string error; - if (!wrk.FileSys().FileRead(content, SourceFile, &error)) { + if (!FileSys().FileRead(content, SourceFile, &error)) { std::string emsg = "Could not read file\n "; emsg += Quoted(SourceFile); emsg += "\nrequired by moc include "; @@ -794,20 +879,20 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) emsg += Quoted(IncluderFile); emsg += ".\n"; emsg += error; - wrk.LogError(GenT::MOC, emsg); + LogError(GenT::MOC, emsg); return false; } } - FindDependencies(wrk, content); + FindDependencies(content); } // Check dependency timestamps std::string error; - std::string sourceDir = wrk.FileSys().SubDirPrefix(SourceFile); + std::string sourceDir = FileSys().SubDirPrefix(SourceFile); for (std::string const& depFileRel : Depends) { std::string depFileAbs = - wrk.Moc().FindIncludedFile(sourceDir, depFileRel); + Gen()->Moc().FindIncludedFile(sourceDir, depFileRel); if (!depFileAbs.empty()) { - if (wrk.FileSys().FileIsOlderThan(BuildFile, depFileAbs, &error)) { + if (FileSys().FileIsOlderThan(BuildFile, depFileAbs, &error)) { if (verbose) { std::string reason = "Generating "; reason += Quoted(BuildFile); @@ -815,18 +900,18 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) reason += Quoted(SourceFile); reason += " because it is older than it's dependency file "; reason += Quoted(depFileAbs); - wrk.LogInfo(GenT::MOC, reason); + Log().Info(GenT::MOC, reason); } return true; } if (!error.empty()) { - wrk.LogError(GenT::MOC, error); + LogError(GenT::MOC, error); return false; } } else { std::string message = "Could not find dependency file "; message += Quoted(depFileRel); - wrk.LogFileWarning(GenT::MOC, SourceFile, message); + Log().WarningFile(GenT::MOC, SourceFile, message); } } } @@ -834,41 +919,40 @@ bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk) return false; } -void cmQtAutoGeneratorMocUic::JobMocT::GenerateMoc(WorkerT& wrk) +void cmQtAutoMocUic::JobMocT::GenerateMoc() { // Make sure the parent directory exists - if (!wrk.FileSys().MakeParentDirectory(BuildFile)) { - wrk.LogFileError(GenT::MOC, BuildFile, - "Could not create parent directory."); + if (!FileSys().MakeParentDirectory(BuildFile)) { + LogFileError(GenT::MOC, BuildFile, "Could not create parent directory."); return; } { // Compose moc command std::vector<std::string> cmd; - cmd.push_back(wrk.Moc().Executable); + cmd.push_back(Gen()->Moc().Executable); // Add options - cmd.insert(cmd.end(), wrk.Moc().AllOptions.begin(), - wrk.Moc().AllOptions.end()); + cmd.insert(cmd.end(), Gen()->Moc().AllOptions.begin(), + Gen()->Moc().AllOptions.end()); // Add predefs include - if (!wrk.Moc().PredefsFileAbs.empty()) { + if (!Gen()->Moc().PredefsFileAbs.empty()) { cmd.emplace_back("--include"); - cmd.push_back(wrk.Moc().PredefsFileAbs); + cmd.push_back(Gen()->Moc().PredefsFileAbs); } cmd.emplace_back("-o"); cmd.push_back(BuildFile); cmd.push_back(SourceFile); // Execute moc command - ProcessResultT result; - if (wrk.RunProcess(GenT::MOC, result, cmd)) { + cmWorkerPool::ProcessResultT result; + if (RunProcess(GenT::MOC, result, cmd)) { // Moc command success // Print moc output if (!result.StdOut.empty()) { - wrk.LogInfo(GenT::MOC, result.StdOut); + Log().Info(GenT::MOC, result.StdOut); } // Notify the generator that a not included file changed (on demand) if (IncludeString.empty()) { - wrk.Gen().ParallelMocAutoUpdated(); + Gen()->ParallelMocAutoUpdated(); } } else { // Moc command failed @@ -879,51 +963,51 @@ void cmQtAutoGeneratorMocUic::JobMocT::GenerateMoc(WorkerT& wrk) emsg += Quoted(BuildFile); emsg += ".\n"; emsg += result.ErrorMessage; - wrk.LogCommandError(GenT::MOC, emsg, cmd, result.StdOut); + LogCommandError(GenT::MOC, emsg, cmd, result.StdOut); } - wrk.FileSys().FileRemove(BuildFile); + FileSys().FileRemove(BuildFile); } } } -void cmQtAutoGeneratorMocUic::JobUicT::Process(WorkerT& wrk) +void cmQtAutoMocUic::JobUicT::Process() { // Compute build file name - BuildFile = wrk.Base().AutogenIncludeDir; + BuildFile = Gen()->Base().AutogenIncludeDir; BuildFile += '/'; BuildFile += IncludeString; - if (UpdateRequired(wrk)) { - GenerateUic(wrk); + if (UpdateRequired()) { + GenerateUic(); } } -bool cmQtAutoGeneratorMocUic::JobUicT::UpdateRequired(WorkerT& wrk) +bool cmQtAutoMocUic::JobUicT::UpdateRequired() { - bool const verbose = wrk.Gen().Log().Verbose(); + bool const verbose = Log().Verbose(); // Test if the build file exists - if (!wrk.FileSys().FileExists(BuildFile)) { + if (!FileSys().FileExists(BuildFile)) { if (verbose) { std::string reason = "Generating "; reason += Quoted(BuildFile); reason += " from its source file "; reason += Quoted(SourceFile); reason += " because it doesn't exist"; - wrk.LogInfo(GenT::UIC, reason); + Log().Info(GenT::UIC, reason); } return true; } // Test if the uic settings changed - if (wrk.Uic().SettingsChanged) { + if (Gen()->Uic().SettingsChanged) { if (verbose) { std::string reason = "Generating "; reason += Quoted(BuildFile); reason += " from "; reason += Quoted(SourceFile); reason += " because the UIC settings changed"; - wrk.LogInfo(GenT::UIC, reason); + Log().Info(GenT::UIC, reason); } return true; } @@ -933,9 +1017,9 @@ bool cmQtAutoGeneratorMocUic::JobUicT::UpdateRequired(WorkerT& wrk) bool isOlder = false; { std::string error; - isOlder = wrk.FileSys().FileIsOlderThan(BuildFile, SourceFile, &error); + isOlder = FileSys().FileIsOlderThan(BuildFile, SourceFile, &error); if (!isOlder && !error.empty()) { - wrk.LogError(GenT::UIC, error); + LogError(GenT::UIC, error); return false; } } @@ -945,7 +1029,7 @@ bool cmQtAutoGeneratorMocUic::JobUicT::UpdateRequired(WorkerT& wrk) reason += Quoted(BuildFile); reason += " because it's older than its source file "; reason += Quoted(SourceFile); - wrk.LogInfo(GenT::UIC, reason); + Log().Info(GenT::UIC, reason); } return true; } @@ -954,37 +1038,36 @@ bool cmQtAutoGeneratorMocUic::JobUicT::UpdateRequired(WorkerT& wrk) return false; } -void cmQtAutoGeneratorMocUic::JobUicT::GenerateUic(WorkerT& wrk) +void cmQtAutoMocUic::JobUicT::GenerateUic() { // Make sure the parent directory exists - if (!wrk.FileSys().MakeParentDirectory(BuildFile)) { - wrk.LogFileError(GenT::UIC, BuildFile, - "Could not create parent directory."); + if (!FileSys().MakeParentDirectory(BuildFile)) { + LogFileError(GenT::UIC, BuildFile, "Could not create parent directory."); return; } { // Compose uic command std::vector<std::string> cmd; - cmd.push_back(wrk.Uic().Executable); + cmd.push_back(Gen()->Uic().Executable); { - std::vector<std::string> allOpts = wrk.Uic().TargetOptions; - auto optionIt = wrk.Uic().Options.find(SourceFile); - if (optionIt != wrk.Uic().Options.end()) { + std::vector<std::string> allOpts = Gen()->Uic().TargetOptions; + auto optionIt = Gen()->Uic().Options.find(SourceFile); + if (optionIt != Gen()->Uic().Options.end()) { UicMergeOptions(allOpts, optionIt->second, - (wrk.Base().QtVersionMajor == 5)); + (Gen()->Base().QtVersionMajor == 5)); } cmd.insert(cmd.end(), allOpts.begin(), allOpts.end()); } cmd.emplace_back("-o"); - cmd.push_back(BuildFile); - cmd.push_back(SourceFile); + cmd.emplace_back(BuildFile); + cmd.emplace_back(SourceFile); - ProcessResultT result; - if (wrk.RunProcess(GenT::UIC, result, cmd)) { + cmWorkerPool::ProcessResultT result; + if (RunProcess(GenT::UIC, result, cmd)) { // Uic command success // Print uic output if (!result.StdOut.empty()) { - wrk.LogInfo(GenT::UIC, result.StdOut); + Log().Info(GenT::UIC, result.StdOut); } } else { // Uic command failed @@ -997,147 +1080,19 @@ void cmQtAutoGeneratorMocUic::JobUicT::GenerateUic(WorkerT& wrk) emsg += Quoted(IncluderFile); emsg += ".\n"; emsg += result.ErrorMessage; - wrk.LogCommandError(GenT::UIC, emsg, cmd, result.StdOut); + LogCommandError(GenT::UIC, emsg, cmd, result.StdOut); } - wrk.FileSys().FileRemove(BuildFile); - } - } -} - -cmQtAutoGeneratorMocUic::WorkerT::WorkerT(cmQtAutoGeneratorMocUic* gen, - uv_loop_t* uvLoop) - : Gen_(gen) -{ - // Initialize uv asynchronous callback for process starting - ProcessRequest_.init(*uvLoop, &WorkerT::UVProcessStart, this); - // Start thread - Thread_ = std::thread(&WorkerT::Loop, this); -} - -cmQtAutoGeneratorMocUic::WorkerT::~WorkerT() -{ - // Join thread - if (Thread_.joinable()) { - Thread_.join(); - } -} - -void cmQtAutoGeneratorMocUic::WorkerT::LogInfo( - GenT genType, std::string const& message) const -{ - Log().Info(genType, message); -} - -void cmQtAutoGeneratorMocUic::WorkerT::LogWarning( - GenT genType, std::string const& message) const -{ - Log().Warning(genType, message); -} - -void cmQtAutoGeneratorMocUic::WorkerT::LogFileWarning( - GenT genType, std::string const& filename, std::string const& message) const -{ - Log().WarningFile(genType, filename, message); -} - -void cmQtAutoGeneratorMocUic::WorkerT::LogError( - GenT genType, std::string const& message) const -{ - Gen().ParallelRegisterJobError(); - Log().Error(genType, message); -} - -void cmQtAutoGeneratorMocUic::WorkerT::LogFileError( - GenT genType, std::string const& filename, std::string const& message) const -{ - Gen().ParallelRegisterJobError(); - Log().ErrorFile(genType, filename, message); -} - -void cmQtAutoGeneratorMocUic::WorkerT::LogCommandError( - GenT genType, std::string const& message, - std::vector<std::string> const& command, std::string const& output) const -{ - Gen().ParallelRegisterJobError(); - Log().ErrorCommand(genType, message, command, output); -} - -bool cmQtAutoGeneratorMocUic::WorkerT::RunProcess( - GenT genType, ProcessResultT& result, - std::vector<std::string> const& command) -{ - if (command.empty()) { - return false; - } - - // Create process instance - { - std::lock_guard<std::mutex> lock(ProcessMutex_); - Process_ = cm::make_unique<ReadOnlyProcessT>(); - Process_->setup(&result, true, command, Gen().Base().AutogenBuildDir); - } - - // Send asynchronous process start request to libuv loop - ProcessRequest_.send(); - - // Log command - if (this->Log().Verbose()) { - std::string msg = "Running command:\n"; - msg += QuotedCommand(command); - msg += '\n'; - this->LogInfo(genType, msg); - } - - // Wait until the process has been finished and destroyed - { - std::unique_lock<std::mutex> ulock(ProcessMutex_); - while (Process_) { - ProcessCondition_.wait(ulock); - } - } - return !result.error(); -} - -void cmQtAutoGeneratorMocUic::WorkerT::Loop() -{ - while (true) { - Gen().WorkerSwapJob(JobHandle_); - if (JobHandle_) { - JobHandle_->Process(*this); - } else { - break; + FileSys().FileRemove(BuildFile); } } } -void cmQtAutoGeneratorMocUic::WorkerT::UVProcessStart(uv_async_t* handle) +void cmQtAutoMocUic::JobFinishT::Process() { - auto& wrk = *reinterpret_cast<WorkerT*>(handle->data); - { - std::lock_guard<std::mutex> lock(wrk.ProcessMutex_); - if (wrk.Process_ && !wrk.Process_->IsStarted()) { - wrk.Process_->start(handle->loop, [&wrk] { wrk.UVProcessFinished(); }); - } - } - - if (!wrk.Process_->IsStarted()) { - wrk.UVProcessFinished(); - } + Gen()->AbortSuccess(); } -void cmQtAutoGeneratorMocUic::WorkerT::UVProcessFinished() -{ - { - std::lock_guard<std::mutex> lock(ProcessMutex_); - if (Process_ && (Process_->IsFinished() || !Process_->IsStarted())) { - Process_.reset(); - } - } - // Notify idling thread - ProcessCondition_.notify_one(); -} - -cmQtAutoGeneratorMocUic::cmQtAutoGeneratorMocUic() +cmQtAutoMocUic::cmQtAutoMocUic() : Base_(&FileSys()) , Moc_(&FileSys()) { @@ -1147,26 +1102,11 @@ cmQtAutoGeneratorMocUic::cmQtAutoGeneratorMocUic() "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]"); Uic_.RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+" "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]"); - - // Initialize libuv loop - uv_disable_stdio_inheritance(); -#ifdef CMAKE_UV_SIGNAL_HACK - UVHackRAII_ = cm::make_unique<cmUVSignalHackRAII>(); -#endif - UVLoop_ = cm::make_unique<uv_loop_t>(); - uv_loop_init(UVLoop()); - - // Initialize libuv asynchronous iteration request - UVRequest().init(*UVLoop(), &cmQtAutoGeneratorMocUic::UVPollStage, this); } -cmQtAutoGeneratorMocUic::~cmQtAutoGeneratorMocUic() -{ - // Close libuv loop - uv_loop_close(UVLoop()); -} +cmQtAutoMocUic::~cmQtAutoMocUic() = default; -bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile) +bool cmQtAutoMocUic::Init(cmMakefile* makefile) { // -- Meta Base_.HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions(); @@ -1246,6 +1186,7 @@ bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile) num = std::min<unsigned long>(num, ParallelMax); Base_.NumThreads = static_cast<unsigned int>(num); } + WorkerPool_.SetThreadCount(Base_.NumThreads); } // - Files and directories @@ -1364,7 +1305,7 @@ bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile) Moc_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD"); // Install moc predefs job if (!Moc().PredefsCmd.empty()) { - JobQueues_.MocPredefs.emplace_back(cm::make_unique<JobMocPredefsT>()); + WorkerPool().EmplaceJob<JobMocPredefsT>(); } } @@ -1400,46 +1341,48 @@ bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile) } // - Headers and sources + // Add sources { - auto addHeader = [this](std::string&& hdr, bool moc, bool uic) { - this->JobQueues_.Headers.emplace_back( - cm::make_unique<JobParseT>(std::move(hdr), moc, uic, true)); - }; auto addSource = [this](std::string&& src, bool moc, bool uic) { - this->JobQueues_.Sources.emplace_back( - cm::make_unique<JobParseT>(std::move(src), moc, uic, false)); + WorkerPool().EmplaceJob<JobParseT>(std::move(src), moc, uic, false); }; - - // Add headers - for (std::string& hdr : InfoGetList("AM_HEADERS")) { - addHeader(std::move(hdr), true, true); + for (std::string& src : InfoGetList("AM_SOURCES")) { + addSource(std::move(src), true, true); } if (Moc().Enabled) { - for (std::string& hdr : InfoGetList("AM_MOC_HEADERS")) { - addHeader(std::move(hdr), true, false); + for (std::string& src : InfoGetList("AM_MOC_SOURCES")) { + addSource(std::move(src), true, false); } } if (Uic().Enabled) { - for (std::string& hdr : InfoGetList("AM_UIC_HEADERS")) { - addHeader(std::move(hdr), false, true); + for (std::string& src : InfoGetList("AM_UIC_SOURCES")) { + addSource(std::move(src), false, true); } } - - // Add sources - for (std::string& src : InfoGetList("AM_SOURCES")) { - addSource(std::move(src), true, true); + } + // Add Fence job + WorkerPool().EmplaceJob<JobFenceT>(); + // Add headers + { + auto addHeader = [this](std::string&& hdr, bool moc, bool uic) { + WorkerPool().EmplaceJob<JobParseT>(std::move(hdr), moc, uic, true); + }; + for (std::string& hdr : InfoGetList("AM_HEADERS")) { + addHeader(std::move(hdr), true, true); } if (Moc().Enabled) { - for (std::string& src : InfoGetList("AM_MOC_SOURCES")) { - addSource(std::move(src), true, false); + for (std::string& hdr : InfoGetList("AM_MOC_HEADERS")) { + addHeader(std::move(hdr), true, false); } } if (Uic().Enabled) { - for (std::string& src : InfoGetList("AM_UIC_SOURCES")) { - addSource(std::move(src), false, true); + for (std::string& hdr : InfoGetList("AM_UIC_HEADERS")) { + addHeader(std::move(hdr), false, true); } } } + // Addpost parse fence job + WorkerPool().EmplaceJob<JobPostParseT>(); // Init derived information // ------------------------ @@ -1534,98 +1477,22 @@ bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile) return true; } -bool cmQtAutoGeneratorMocUic::Process() +bool cmQtAutoMocUic::Process() { - // Run libuv event loop - UVRequest().send(); - if (uv_run(UVLoop(), UV_RUN_DEFAULT) == 0) { - if (JobError_) { - return false; - } - } else { + SettingsFileRead(); + if (!CreateDirectories()) { return false; } - return true; -} - -void cmQtAutoGeneratorMocUic::UVPollStage(uv_async_t* handle) -{ - reinterpret_cast<cmQtAutoGeneratorMocUic*>(handle->data)->PollStage(); -} - -void cmQtAutoGeneratorMocUic::PollStage() -{ - switch (Stage_) { - case StageT::SETTINGS_READ: - SettingsFileRead(); - SetStage(StageT::CREATE_DIRECTORIES); - break; - case StageT::CREATE_DIRECTORIES: - CreateDirectories(); - SetStage(StageT::PARSE_SOURCES); - break; - case StageT::PARSE_SOURCES: - if (ThreadsStartJobs(JobQueues_.Sources)) { - SetStage(StageT::PARSE_HEADERS); - } - break; - case StageT::PARSE_HEADERS: - if (ThreadsStartJobs(JobQueues_.Headers)) { - SetStage(StageT::MOC_PREDEFS); - } - break; - case StageT::MOC_PREDEFS: - if (ThreadsStartJobs(JobQueues_.MocPredefs)) { - SetStage(StageT::MOC_PROCESS); - } - break; - case StageT::MOC_PROCESS: - if (ThreadsStartJobs(JobQueues_.Moc)) { - SetStage(StageT::MOCS_COMPILATION); - } - break; - case StageT::MOCS_COMPILATION: - if (ThreadsJobsDone()) { - MocGenerateCompilation(); - SetStage(StageT::UIC_PROCESS); - } - break; - case StageT::UIC_PROCESS: - if (ThreadsStartJobs(JobQueues_.Uic)) { - SetStage(StageT::SETTINGS_WRITE); - } - break; - case StageT::SETTINGS_WRITE: - SettingsFileWrite(); - SetStage(StageT::FINISH); - break; - case StageT::FINISH: - if (ThreadsJobsDone()) { - // Clear all libuv handles - ThreadsStop(); - UVRequest().reset(); - // Set highest END stage manually - Stage_ = StageT::END; - } - break; - case StageT::END: - break; + if (!WorkerPool_.Process(this)) { + return false; } -} - -void cmQtAutoGeneratorMocUic::SetStage(StageT stage) -{ if (JobError_) { - stage = StageT::FINISH; - } - // Only allow to increase the stage - if (Stage_ < stage) { - Stage_ = stage; - UVRequest().send(); + return false; } + return SettingsFileWrite(); } -void cmQtAutoGeneratorMocUic::SettingsFileRead() +void cmQtAutoMocUic::SettingsFileRead() { // Compose current settings strings { @@ -1691,11 +1558,10 @@ void cmQtAutoGeneratorMocUic::SettingsFileRead() } } -void cmQtAutoGeneratorMocUic::SettingsFileWrite() +bool cmQtAutoMocUic::SettingsFileWrite() { - std::lock_guard<std::mutex> jobsLock(JobsMutex_); // Only write if any setting changed - if (!JobError_ && (Moc().SettingsChanged || Uic().SettingsChanged)) { + if (Moc().SettingsChanged || Uic().SettingsChanged) { if (Log().Verbose()) { Log().Info(GenT::GEN, "Writing settings file " + Quoted(SettingsFile_)); } @@ -1721,255 +1587,142 @@ void cmQtAutoGeneratorMocUic::SettingsFileWrite() "Settings file writing failed. " + error); // Remove old settings file to trigger a full rebuild on the next run FileSys().FileRemove(SettingsFile_); - RegisterJobError(); + return false; } } + return true; } -void cmQtAutoGeneratorMocUic::CreateDirectories() +bool cmQtAutoMocUic::CreateDirectories() { // Create AUTOGEN include directory if (!FileSys().MakeDirectory(Base().AutogenIncludeDir)) { Log().ErrorFile(GenT::GEN, Base().AutogenIncludeDir, "Could not create directory."); - RegisterJobError(); + return false; } + return true; } -bool cmQtAutoGeneratorMocUic::ThreadsStartJobs(JobQueueT& queue) +// Private method that requires cmQtAutoMocUic::JobsMutex_ to be +// locked +void cmQtAutoMocUic::Abort(bool error) { - bool done = false; - std::size_t queueSize = queue.size(); - - // Change the active queue - { - std::lock_guard<std::mutex> jobsLock(JobsMutex_); - // Check if there are still unfinished jobs from the previous queue - if (JobsRemain_ == 0) { - if (!JobThreadsAbort_) { - JobQueue_.swap(queue); - JobsRemain_ = queueSize; - } else { - // Abort requested - queue.clear(); - queueSize = 0; - } - done = true; - } + if (error) { + JobError_.store(true); } + WorkerPool_.Abort(); +} - if (done && (queueSize != 0)) { - // Start new threads on demand - if (Workers_.empty()) { - Workers_.resize(Base().NumThreads); - for (auto& item : Workers_) { - item = cm::make_unique<WorkerT>(this, UVLoop()); +bool cmQtAutoMocUic::ParallelJobPushMoc(cmWorkerPool::JobHandleT&& jobHandle) +{ + JobMocT const& mocJob(static_cast<JobMocT&>(*jobHandle)); + // Do additional tests if this is an included moc job + if (!mocJob.IncludeString.empty()) { + std::lock_guard<std::mutex> guard(MocMetaMutex_); + // Register included moc file + MocIncludedFiles_.emplace(mocJob.SourceFile); + + // Check if the same moc file would be generated from a different + // source file. + auto const range = MocIncludes_.equal_range(mocJob.IncludeString); + for (auto it = range.first; it != range.second; ++it) { + if (it->second[0] == mocJob.SourceFile) { + // The output file already gets generated + return true; } - } else { - // Notify threads - if (queueSize == 1) { - JobsConditionRead_.notify_one(); - } else { - JobsConditionRead_.notify_all(); + { + // The output file already gets generated - from a different source + // file! + std::string error = "The two source files\n "; + error += Quoted(mocJob.IncluderFile); + error += " and\n "; + error += Quoted(it->second[1]); + error += "\ncontain the same moc include string "; + error += Quoted(mocJob.IncludeString); + error += "\nbut the moc file would be generated from different " + "source files\n "; + error += Quoted(mocJob.SourceFile); + error += " and\n "; + error += Quoted(it->second[0]); + error += ".\nConsider to\n" + "- not include the \"moc_<NAME>.cpp\" file\n" + "- add a directory prefix to a \"<NAME>.moc\" include " + "(e.g \"sub/<NAME>.moc\")\n" + "- rename the source file(s)\n"; + Log().Error(GenT::MOC, error); + AbortError(); + return false; } } - } - return done; -} - -void cmQtAutoGeneratorMocUic::ThreadsStop() -{ - if (!Workers_.empty()) { - // Clear all jobs - { - std::lock_guard<std::mutex> jobsLock(JobsMutex_); - JobThreadsAbort_ = true; - JobsRemain_ -= JobQueue_.size(); - JobQueue_.clear(); - - JobQueues_.Sources.clear(); - JobQueues_.Headers.clear(); - JobQueues_.MocPredefs.clear(); - JobQueues_.Moc.clear(); - JobQueues_.Uic.clear(); - } - // Wake threads - JobsConditionRead_.notify_all(); - // Join and clear threads - Workers_.clear(); + // We're still here so register this job + MocIncludes_.emplace_hint(range.first, mocJob.IncludeString, + std::array<std::string, 2>{ + { mocJob.SourceFile, mocJob.IncluderFile } }); } + return WorkerPool_.PushJob(std::move(jobHandle)); } -bool cmQtAutoGeneratorMocUic::ThreadsJobsDone() -{ - std::lock_guard<std::mutex> jobsLock(JobsMutex_); - return (JobsRemain_ == 0); -} - -void cmQtAutoGeneratorMocUic::WorkerSwapJob(JobHandleT& jobHandle) +bool cmQtAutoMocUic::ParallelJobPushUic(cmWorkerPool::JobHandleT&& jobHandle) { - bool const jobProcessed(jobHandle); - if (jobProcessed) { - jobHandle.reset(); - } + const JobUicT& uicJob(static_cast<JobUicT&>(*jobHandle)); { - std::unique_lock<std::mutex> jobsLock(JobsMutex_); - // Reduce the remaining job count and notify the libuv loop - // when all jobs are done - if (jobProcessed) { - --JobsRemain_; - if (JobsRemain_ == 0) { - UVRequest().send(); + std::lock_guard<std::mutex> guard(UicMetaMutex_); + // Check if the same uic file would be generated from a different + // source file. + auto const range = UicIncludes_.equal_range(uicJob.IncludeString); + for (auto it = range.first; it != range.second; ++it) { + if (it->second[0] == uicJob.SourceFile) { + // The output file already gets generated + return true; } - } - // Wait for new jobs - while (!JobThreadsAbort_ && JobQueue_.empty()) { - JobsConditionRead_.wait(jobsLock); - } - // Try to pick up a new job handle - if (!JobThreadsAbort_ && !JobQueue_.empty()) { - jobHandle = std::move(JobQueue_.front()); - JobQueue_.pop_front(); - } - } -} - -void cmQtAutoGeneratorMocUic::ParallelRegisterJobError() -{ - std::lock_guard<std::mutex> jobsLock(JobsMutex_); - RegisterJobError(); -} - -// Private method that requires cmQtAutoGeneratorMocUic::JobsMutex_ to be -// locked -void cmQtAutoGeneratorMocUic::RegisterJobError() -{ - JobError_ = true; - if (!JobThreadsAbort_) { - JobThreadsAbort_ = true; - // Clear remaining jobs - if (JobsRemain_ != 0) { - JobsRemain_ -= JobQueue_.size(); - JobQueue_.clear(); - } - } -} - -bool cmQtAutoGeneratorMocUic::ParallelJobPushMoc(JobHandleT& jobHandle) -{ - std::lock_guard<std::mutex> jobsLock(JobsMutex_); - if (!JobThreadsAbort_) { - bool pushJobHandle = true; - // Do additional tests if this is an included moc job - const JobMocT& mocJob(static_cast<JobMocT&>(*jobHandle)); - if (!mocJob.IncludeString.empty()) { - // Register included moc file and look for collisions - MocIncludedFiles_.emplace(mocJob.SourceFile); - if (!MocIncludedStrings_.emplace(mocJob.IncludeString).second) { - // Another source file includes the same moc file! - for (const JobHandleT& otherHandle : JobQueues_.Moc) { - const JobMocT& otherJob(static_cast<JobMocT&>(*otherHandle)); - if (otherJob.IncludeString == mocJob.IncludeString) { - // Check if the same moc file would be generated from different - // source files which is an error. - if (otherJob.SourceFile != mocJob.SourceFile) { - // Include string collision - std::string error = "The two source files\n "; - error += Quoted(mocJob.IncluderFile); - error += " and\n "; - error += Quoted(otherJob.IncluderFile); - error += "\ncontain the same moc include string "; - error += Quoted(mocJob.IncludeString); - error += "\nbut the moc file would be generated from different " - "source files\n "; - error += Quoted(mocJob.SourceFile); - error += " and\n "; - error += Quoted(otherJob.SourceFile); - error += ".\nConsider to\n" - "- not include the \"moc_<NAME>.cpp\" file\n" - "- add a directory prefix to a \"<NAME>.moc\" include " - "(e.g \"sub/<NAME>.moc\")\n" - "- rename the source file(s)\n"; - Log().Error(GenT::MOC, error); - RegisterJobError(); - } - // Do not push this job in since the included moc file already - // gets generated by an other job. - pushJobHandle = false; - break; - } - } + { + // The output file already gets generated - from a different .ui + // file! + std::string error = "The two source files\n "; + error += Quoted(uicJob.IncluderFile); + error += " and\n "; + error += Quoted(it->second[1]); + error += "\ncontain the same uic include string "; + error += Quoted(uicJob.IncludeString); + error += "\nbut the uic file would be generated from different " + "source files\n "; + error += Quoted(uicJob.SourceFile); + error += " and\n "; + error += Quoted(it->second[0]); + error += + ".\nConsider to\n" + "- add a directory prefix to a \"ui_<NAME>.h\" include " + "(e.g \"sub/ui_<NAME>.h\")\n" + "- rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" " + "include(s)\n"; + Log().Error(GenT::UIC, error); + AbortError(); + return false; } } - // Push job on demand - if (pushJobHandle) { - JobQueues_.Moc.emplace_back(std::move(jobHandle)); - } - } - return !JobError_; -} -bool cmQtAutoGeneratorMocUic::ParallelJobPushUic(JobHandleT& jobHandle) -{ - std::lock_guard<std::mutex> jobsLock(JobsMutex_); - if (!JobThreadsAbort_) { - bool pushJobHandle = true; - // Look for include collisions. - const JobUicT& uicJob(static_cast<JobUicT&>(*jobHandle)); - for (const JobHandleT& otherHandle : JobQueues_.Uic) { - const JobUicT& otherJob(static_cast<JobUicT&>(*otherHandle)); - if (otherJob.IncludeString == uicJob.IncludeString) { - // Check if the same uic file would be generated from different - // source files which would be an error. - if (otherJob.SourceFile != uicJob.SourceFile) { - // Include string collision - std::string error = "The two source files\n "; - error += Quoted(uicJob.IncluderFile); - error += " and\n "; - error += Quoted(otherJob.IncluderFile); - error += "\ncontain the same uic include string "; - error += Quoted(uicJob.IncludeString); - error += "\nbut the uic file would be generated from different " - "source files\n "; - error += Quoted(uicJob.SourceFile); - error += " and\n "; - error += Quoted(otherJob.SourceFile); - error += - ".\nConsider to\n" - "- add a directory prefix to a \"ui_<NAME>.h\" include " - "(e.g \"sub/ui_<NAME>.h\")\n" - "- rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" " - "include(s)\n"; - Log().Error(GenT::UIC, error); - RegisterJobError(); - } - // Do not push this job in since the uic file already - // gets generated by an other job. - pushJobHandle = false; - break; - } - } - if (pushJobHandle) { - JobQueues_.Uic.emplace_back(std::move(jobHandle)); - } + // We're still here so register this job + UicIncludes_.emplace_hint(range.first, uicJob.IncludeString, + std::array<std::string, 2>{ + { uicJob.SourceFile, uicJob.IncluderFile } }); } - return !JobError_; + return WorkerPool_.PushJob(std::move(jobHandle)); } -bool cmQtAutoGeneratorMocUic::ParallelMocIncluded( - std::string const& sourceFile) +bool cmQtAutoMocUic::ParallelMocIncluded(std::string const& sourceFile) { - std::lock_guard<std::mutex> mocLock(JobsMutex_); + std::lock_guard<std::mutex> guard(MocMetaMutex_); return (MocIncludedFiles_.find(sourceFile) != MocIncludedFiles_.end()); } -std::string cmQtAutoGeneratorMocUic::ParallelMocAutoRegister( +std::string cmQtAutoMocUic::ParallelMocAutoRegister( std::string const& baseName) { std::string res; { - std::lock_guard<std::mutex> mocLock(JobsMutex_); + std::lock_guard<std::mutex> mocLock(MocMetaMutex_); res = baseName; res += ".cpp"; if (MocAutoFiles_.find(res) == MocAutoFiles_.end()) { @@ -1990,63 +1743,3 @@ std::string cmQtAutoGeneratorMocUic::ParallelMocAutoRegister( } return res; } - -void cmQtAutoGeneratorMocUic::ParallelMocAutoUpdated() -{ - std::lock_guard<std::mutex> mocLock(JobsMutex_); - MocAutoFileUpdated_ = true; -} - -void cmQtAutoGeneratorMocUic::MocGenerateCompilation() -{ - std::lock_guard<std::mutex> mocLock(JobsMutex_); - if (!JobError_ && Moc().Enabled) { - // Write mocs compilation build file - { - // Compose mocs compilation file content - std::string content = - "// This file is autogenerated. Changes will be overwritten.\n"; - if (MocAutoFiles_.empty()) { - // Placeholder content - content += "// No files found that require moc or the moc files are " - "included\n"; - content += "enum some_compilers { need_more_than_nothing };\n"; - } else { - // Valid content - char const sbeg = Base().MultiConfig ? '<' : '"'; - char const send = Base().MultiConfig ? '>' : '"'; - for (std::string const& mocfile : MocAutoFiles_) { - content += "#include "; - content += sbeg; - content += mocfile; - content += send; - content += '\n'; - } - } - - std::string const& compAbs = Moc().CompFileAbs; - if (FileSys().FileDiffers(compAbs, content)) { - // Actually write mocs compilation file - if (Log().Verbose()) { - Log().Info(GenT::MOC, "Generating MOC compilation " + compAbs); - } - std::string error; - if (!FileSys().FileWrite(compAbs, content, &error)) { - Log().ErrorFile(GenT::MOC, compAbs, - "mocs compilation file writing failed. " + error); - RegisterJobError(); - return; - } - } else if (MocAutoFileUpdated_) { - // Only touch mocs compilation file - if (Log().Verbose()) { - Log().Info(GenT::MOC, "Touching mocs compilation " + compAbs); - } - FileSys().Touch(compAbs); - } - } - // Write mocs compilation wrapper file - if (Base().MultiConfig) { - } - } -} diff --git a/Source/cmQtAutoGeneratorMocUic.h b/Source/cmQtAutoMocUic.h index 27d73a7..3902abb 100644 --- a/Source/cmQtAutoGeneratorMocUic.h +++ b/Source/cmQtAutoMocUic.h @@ -1,26 +1,22 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ -#ifndef cmQtAutoGeneratorMocUic_h -#define cmQtAutoGeneratorMocUic_h +#ifndef cmQtAutoMocUic_h +#define cmQtAutoMocUic_h #include "cmConfigure.h" // IWYU pragma: keep #include "cmQtAutoGen.h" #include "cmQtAutoGenerator.h" -#include "cmUVHandlePtr.h" -#include "cmUVSignalHackRAII.h" // IWYU pragma: keep -#include "cm_uv.h" +#include "cmWorkerPool.h" #include "cmsys/RegularExpression.hxx" -#include <condition_variable> -#include <cstddef> -#include <deque> +#include <array> +#include <atomic> #include <map> #include <memory> // IWYU pragma: keep #include <mutex> #include <set> #include <string> -#include <thread> #include <unordered_set> #include <utility> #include <vector> @@ -28,18 +24,18 @@ class cmMakefile; // @brief AUTOMOC and AUTOUIC generator -class cmQtAutoGeneratorMocUic : public cmQtAutoGenerator +class cmQtAutoMocUic : public cmQtAutoGenerator { public: - cmQtAutoGeneratorMocUic(); - ~cmQtAutoGeneratorMocUic() override; + cmQtAutoMocUic(); + ~cmQtAutoMocUic() override; - cmQtAutoGeneratorMocUic(cmQtAutoGeneratorMocUic const&) = delete; - cmQtAutoGeneratorMocUic& operator=(cmQtAutoGeneratorMocUic const&) = delete; + cmQtAutoMocUic(cmQtAutoMocUic const&) = delete; + cmQtAutoMocUic& operator=(cmQtAutoMocUic const&) = delete; public: // -- Types - class WorkerT; + typedef std::multimap<std::string, std::array<std::string, 2>> IncludesMap; /// @brief Search key plus regular expression pair /// @@ -173,31 +169,71 @@ public: cmsys::RegularExpression RegExpInclude; }; - /// @brief Abstract job class for threaded processing + /// @brief Abstract job class for concurrent job processing /// - class JobT + class JobT : public cmWorkerPool::JobT { - public: - JobT() = default; - virtual ~JobT() = default; + protected: + /** + * @brief Protected default constructor + */ + JobT(bool fence = false) + : cmWorkerPool::JobT(fence) + { + } + + //! Get the generator. Only valid during Process() call! + cmQtAutoMocUic* Gen() const + { + return static_cast<cmQtAutoMocUic*>(UserData()); + }; + + //! Get the file system interface. Only valid during Process() call! + FileSystem& FileSys() { return Gen()->FileSys(); } + //! Get the logger. Only valid during Process() call! + Logger& Log() { return Gen()->Log(); } + + // -- Error logging with automatic abort + void LogError(GenT genType, std::string const& message) const; + void LogFileError(GenT genType, std::string const& filename, + std::string const& message) const; + void LogCommandError(GenT genType, std::string const& message, + std::vector<std::string> const& command, + std::string const& output) const; - JobT(JobT const&) = delete; - JobT& operator=(JobT const&) = delete; + /** + * @brief Run an external process. Use only during Process() call! + */ + bool RunProcess(GenT genType, cmWorkerPool::ProcessResultT& result, + std::vector<std::string> const& command); + }; - // -- Abstract processing interface - virtual void Process(WorkerT& wrk) = 0; + /// @brief Fence job utility class + /// + class JobFenceT : public JobT + { + public: + JobFenceT() + : JobT(true) + { + } + void Process() override{}; }; - // Job management types - typedef std::unique_ptr<JobT> JobHandleT; - typedef std::deque<JobHandleT> JobQueueT; + /// @brief Generate moc_predefs.h + /// + class JobMocPredefsT : public JobT + { + private: + void Process() override; + }; - /// @brief Parse source job + /// @brief Parses a source file /// class JobParseT : public JobT { public: - JobParseT(std::string&& fileName, bool moc, bool uic, bool header = false) + JobParseT(std::string fileName, bool moc, bool uic, bool header = false) : FileName(std::move(fileName)) , AutoMoc(moc) , AutoUic(uic) @@ -213,18 +249,15 @@ public: std::string FileBase; }; - void Process(WorkerT& wrk) override; - bool ParseMocSource(WorkerT& wrk, MetaT const& meta); - bool ParseMocHeader(WorkerT& wrk, MetaT const& meta); - std::string MocStringHeaders(WorkerT& wrk, - std::string const& fileBase) const; - std::string MocFindIncludedHeader(WorkerT& wrk, - std::string const& includerDir, + void Process() override; + bool ParseMocSource(MetaT const& meta); + bool ParseMocHeader(MetaT const& meta); + std::string MocStringHeaders(std::string const& fileBase) const; + std::string MocFindIncludedHeader(std::string const& includerDir, std::string const& includeBase); - bool ParseUic(WorkerT& wrk, MetaT const& meta); - bool ParseUicInclude(WorkerT& wrk, MetaT const& meta, - std::string&& includeString); - std::string UicFindIncludedFile(WorkerT& wrk, MetaT const& meta, + bool ParseUic(MetaT const& meta); + bool ParseUicInclude(MetaT const& meta, std::string&& includeString); + std::string UicFindIncludedFile(MetaT const& meta, std::string const& includeString); private: @@ -234,12 +267,20 @@ public: bool Header = false; }; - /// @brief Generate moc_predefs + /// @brief Generates additional jobs after all files have been parsed /// - class JobMocPredefsT : public JobT + class JobPostParseT : public JobFenceT { private: - void Process(WorkerT& wrk) override; + void Process() override; + }; + + /// @brief Generate mocs_compilation.cpp + /// + class JobMocsCompilationT : public JobFenceT + { + private: + void Process() override; }; /// @brief Moc a file job @@ -247,20 +288,20 @@ public: class JobMocT : public JobT { public: - JobMocT(std::string&& sourceFile, std::string includerFile, - std::string&& includeString) + JobMocT(std::string sourceFile, std::string includerFile, + std::string includeString) : SourceFile(std::move(sourceFile)) , IncluderFile(std::move(includerFile)) , IncludeString(std::move(includeString)) { } - void FindDependencies(WorkerT& wrk, std::string const& content); + void FindDependencies(std::string const& content); private: - void Process(WorkerT& wrk) override; - bool UpdateRequired(WorkerT& wrk); - void GenerateMoc(WorkerT& wrk); + void Process() override; + bool UpdateRequired(); + void GenerateMoc(); public: std::string SourceFile; @@ -276,8 +317,8 @@ public: class JobUicT : public JobT { public: - JobUicT(std::string&& sourceFile, std::string includerFile, - std::string&& includeString) + JobUicT(std::string sourceFile, std::string includerFile, + std::string includeString) : SourceFile(std::move(sourceFile)) , IncluderFile(std::move(includerFile)) , IncludeString(std::move(includeString)) @@ -285,9 +326,9 @@ public: } private: - void Process(WorkerT& wrk) override; - bool UpdateRequired(WorkerT& wrk); - void GenerateUic(WorkerT& wrk); + void Process() override; + bool UpdateRequired(); + void GenerateUic(); public: std::string SourceFile; @@ -296,80 +337,12 @@ public: std::string BuildFile; }; - /// @brief Worker Thread + /// @brief The last job /// - class WorkerT + class JobFinishT : public JobFenceT { - public: - WorkerT(cmQtAutoGeneratorMocUic* gen, uv_loop_t* uvLoop); - ~WorkerT(); - - WorkerT(WorkerT const&) = delete; - WorkerT& operator=(WorkerT const&) = delete; - - // -- Const accessors - cmQtAutoGeneratorMocUic& Gen() const { return *Gen_; } - Logger& Log() const { return Gen_->Log(); } - FileSystem& FileSys() const { return Gen_->FileSys(); } - const BaseSettingsT& Base() const { return Gen_->Base(); } - const MocSettingsT& Moc() const { return Gen_->Moc(); } - const UicSettingsT& Uic() const { return Gen_->Uic(); } - - // -- Log info - void LogInfo(GenT genType, std::string const& message) const; - // -- Log warning - void LogWarning(GenT genType, std::string const& message) const; - void LogFileWarning(GenT genType, std::string const& filename, - std::string const& message) const; - // -- Log error - void LogError(GenT genType, std::string const& message) const; - void LogFileError(GenT genType, std::string const& filename, - std::string const& message) const; - void LogCommandError(GenT genType, std::string const& message, - std::vector<std::string> const& command, - std::string const& output) const; - - // -- External processes - /// @brief Verbose logging version - bool RunProcess(GenT genType, ProcessResultT& result, - std::vector<std::string> const& command); - private: - /// @brief Thread main loop - void Loop(); - - // -- Libuv callbacks - static void UVProcessStart(uv_async_t* handle); - void UVProcessFinished(); - - private: - // -- Generator - cmQtAutoGeneratorMocUic* Gen_; - // -- Job handle - JobHandleT JobHandle_; - // -- Process management - std::mutex ProcessMutex_; - cm::uv_async_ptr ProcessRequest_; - std::condition_variable ProcessCondition_; - std::unique_ptr<ReadOnlyProcessT> Process_; - // -- System thread - std::thread Thread_; - }; - - /// @brief Processing stage - enum class StageT - { - SETTINGS_READ, - CREATE_DIRECTORIES, - PARSE_SOURCES, - PARSE_HEADERS, - MOC_PREDEFS, - MOC_PROCESS, - MOCS_COMPILATION, - UIC_PROCESS, - SETTINGS_WRITE, - FINISH, - END + void Process() override; }; // -- Const settings interface @@ -377,41 +350,39 @@ public: const MocSettingsT& Moc() const { return this->Moc_; } const UicSettingsT& Uic() const { return this->Uic_; } - // -- Worker thread interface - void WorkerSwapJob(JobHandleT& jobHandle); // -- Parallel job processing interface - void ParallelRegisterJobError(); - bool ParallelJobPushMoc(JobHandleT& jobHandle); - bool ParallelJobPushUic(JobHandleT& jobHandle); - bool ParallelMocIncluded(std::string const& sourceFile); + cmWorkerPool& WorkerPool() { return WorkerPool_; } + void AbortError() { Abort(true); } + void AbortSuccess() { Abort(false); } + bool ParallelJobPushMoc(cmWorkerPool::JobHandleT&& jobHandle); + bool ParallelJobPushUic(cmWorkerPool::JobHandleT&& jobHandle); + + // -- Mocs compilation include file updated flag + void ParallelMocAutoUpdated() { MocAutoFileUpdated_.store(true); } + bool MocAutoFileUpdated() const { return MocAutoFileUpdated_.load(); } + + // -- Mocs compilation file register std::string ParallelMocAutoRegister(std::string const& baseName); - void ParallelMocAutoUpdated(); + bool ParallelMocIncluded(std::string const& sourceFile); + std::set<std::string> const& MocAutoFiles() const + { + return this->MocAutoFiles_; + } private: // -- Utility accessors Logger& Log() { return Logger_; } FileSystem& FileSys() { return FileSys_; } - // -- libuv loop accessors - uv_loop_t* UVLoop() { return UVLoop_.get(); } - cm::uv_async_ptr& UVRequest() { return UVRequest_; } // -- Abstract processing interface bool Init(cmMakefile* makefile) override; bool Process() override; - // -- Process stage - static void UVPollStage(uv_async_t* handle); - void PollStage(); - void SetStage(StageT stage); // -- Settings file void SettingsFileRead(); - void SettingsFileWrite(); + bool SettingsFileWrite(); // -- Thread processing - bool ThreadsStartJobs(JobQueueT& queue); - bool ThreadsJobsDone(); - void ThreadsStop(); - void RegisterJobError(); + void Abort(bool error); // -- Generation - void CreateDirectories(); - void MocGenerateCompilation(); + bool CreateDirectories(); private: // -- Utility @@ -421,39 +392,22 @@ private: BaseSettingsT Base_; MocSettingsT Moc_; UicSettingsT Uic_; - // -- libuv loop -#ifdef CMAKE_UV_SIGNAL_HACK - std::unique_ptr<cmUVSignalHackRAII> UVHackRAII_; -#endif - std::unique_ptr<uv_loop_t> UVLoop_; - cm::uv_async_ptr UVRequest_; - StageT Stage_ = StageT::SETTINGS_READ; - // -- Job queues - std::mutex JobsMutex_; - struct - { - JobQueueT Sources; - JobQueueT Headers; - JobQueueT MocPredefs; - JobQueueT Moc; - JobQueueT Uic; - } JobQueues_; - JobQueueT JobQueue_; - std::size_t volatile JobsRemain_ = 0; - bool volatile JobError_ = false; - bool volatile JobThreadsAbort_ = false; - std::condition_variable JobsConditionRead_; // -- Moc meta - std::set<std::string> MocIncludedStrings_; + std::mutex MocMetaMutex_; std::set<std::string> MocIncludedFiles_; + IncludesMap MocIncludes_; std::set<std::string> MocAutoFiles_; - bool volatile MocAutoFileUpdated_ = false; + std::atomic<bool> MocAutoFileUpdated_ = ATOMIC_VAR_INIT(false); + // -- Uic meta + std::mutex UicMetaMutex_; + IncludesMap UicIncludes_; // -- Settings file std::string SettingsFile_; std::string SettingsStringMoc_; std::string SettingsStringUic_; - // -- Threads and loops - std::vector<std::unique_ptr<WorkerT>> Workers_; + // -- Thread pool and job queue + std::atomic<bool> JobError_ = ATOMIC_VAR_INIT(false); + cmWorkerPool WorkerPool_; }; #endif diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx index 203ee93..dad8821 100644 --- a/Source/cmServerProtocol.cxx +++ b/Source/cmServerProtocol.cxx @@ -8,6 +8,7 @@ #include "cmGlobalGenerator.h" #include "cmJsonObjectDictionary.h" #include "cmJsonObjects.h" +#include "cmMessageType.h" #include "cmServer.h" #include "cmServerDictionary.h" #include "cmState.h" @@ -600,6 +601,10 @@ cmServerResponse cmServerProtocol1::ProcessConfigure( } int ret = cm->Configure(); + cm->IssueMessage( + MessageType::DEPRECATION_WARNING, + "The 'cmake-server(7)' is deprecated. " + "Please port clients to use the 'cmake-file-api(7)' instead."); if (ret < 0) { return request.ReportError("Configuration failed."); } diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx index 2bc4c39..5cdacaa 100644 --- a/Source/cmSourceGroupCommand.cxx +++ b/Source/cmSourceGroupCommand.cxx @@ -80,7 +80,10 @@ std::vector<std::string> prepareFilesPathsForTree( prepared.reserve(filesPaths.size()); for (auto const& filePath : filesPaths) { - prepared.push_back(prepareFilePathForTree(filePath, currentSourceDir)); + // If provided file path is actually not a file, silently ignore it. + if (cmSystemTools::FileExists(filePath, /*isFile=*/true)) { + prepared.push_back(prepareFilePathForTree(filePath, currentSourceDir)); + } } return prepared; diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index 252d985..998f904 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -1,9 +1,13 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ +#define _SCL_SECURE_NO_WARNINGS + #include "cmStringCommand.h" #include "cmsys/RegularExpression.hxx" +#include <algorithm> #include <ctype.h> +#include <iterator> #include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> @@ -13,6 +17,7 @@ #include "cmCryptoHash.h" #include "cmGeneratorExpression.h" #include "cmMakefile.h" +#include "cmMessageType.h" #include "cmRange.h" #include "cmStringReplaceHelper.h" #include "cmSystemTools.h" @@ -79,6 +84,9 @@ bool cmStringCommand::InitialPass(std::vector<std::string> const& args, if (subCommand == "STRIP") { return this->HandleStripCommand(args); } + if (subCommand == "REPEAT") { + return this->HandleRepeatCommand(args); + } if (subCommand == "RANDOM") { return this->HandleRandomCommand(args); } @@ -709,6 +717,59 @@ bool cmStringCommand::HandleStripCommand(std::vector<std::string> const& args) return true; } +bool cmStringCommand::HandleRepeatCommand(std::vector<std::string> const& args) +{ + // `string(REPEAT "<str>" <times> OUTPUT_VARIABLE)` + enum ArgPos : std::size_t + { + SUB_COMMAND, + VALUE, + TIMES, + OUTPUT_VARIABLE, + TOTAL_ARGS + }; + + if (args.size() != ArgPos::TOTAL_ARGS) { + this->Makefile->IssueMessage( + MessageType::FATAL_ERROR, + "sub-command REPEAT requires three arguments."); + return true; + } + + unsigned long times; + if (!cmSystemTools::StringToULong(args[ArgPos::TIMES].c_str(), ×)) { + this->Makefile->IssueMessage(MessageType::FATAL_ERROR, + "repeat count is not a positive number."); + return true; + } + + const auto& stringValue = args[ArgPos::VALUE]; + const auto& variableName = args[ArgPos::OUTPUT_VARIABLE]; + const auto inStringLength = stringValue.size(); + + std::string result; + switch (inStringLength) { + case 0u: + // Nothing to do for zero length input strings + break; + case 1u: + // NOTE If the string to repeat consists of the only character, + // use the appropriate constructor. + result = std::string(times, stringValue[0]); + break; + default: + result = std::string(inStringLength * times, char{}); + for (auto i = 0u; i < times; ++i) { + std::copy(cm::cbegin(stringValue), cm::cend(stringValue), + &result[i * inStringLength]); + } + break; + } + + this->Makefile->AddDefinition(variableName, result.c_str()); + return true; +} + bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args) { if (args.size() < 2 || args.size() == 3 || args.size() == 5) { diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h index cbff73e..acde605 100644 --- a/Source/cmStringCommand.h +++ b/Source/cmStringCommand.h @@ -51,6 +51,7 @@ protected: bool HandleConcatCommand(std::vector<std::string> const& args); bool HandleJoinCommand(std::vector<std::string> const& args); bool HandleStripCommand(std::vector<std::string> const& args); + bool HandleRepeatCommand(std::vector<std::string> const& args); bool HandleRandomCommand(std::vector<std::string> const& args); bool HandleFindCommand(std::vector<std::string> const& args); bool HandleTimestampCommand(std::vector<std::string> const& args); diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index 212608d..bc853b7 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -168,7 +168,6 @@ bool cmSystemTools::s_RunCommandHideConsole = false; bool cmSystemTools::s_DisableRunCommandOutput = false; bool cmSystemTools::s_ErrorOccured = false; bool cmSystemTools::s_FatalErrorOccured = false; -bool cmSystemTools::s_DisableMessages = false; bool cmSystemTools::s_ForceUnixPaths = false; // replace replace with with as many times as it shows up in source. @@ -326,14 +325,11 @@ void cmSystemTools::Stdout(const std::string& s) void cmSystemTools::Message(const std::string& m, const char* title) { - if (s_DisableMessages) { - return; - } if (s_MessageCallback) { s_MessageCallback(m, title); - return; + } else { + std::cerr << m << std::endl; } - std::cerr << m << std::endl << std::flush; } void cmSystemTools::ReportLastSystemError(const char* msg) diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h index a8b2d37..05bd351 100644 --- a/Source/cmSystemTools.h +++ b/Source/cmSystemTools.h @@ -266,8 +266,6 @@ public: static size_t CalculateCommandLineLengthLimit(); - static void EnableMessages() { s_DisableMessages = false; } - static void DisableMessages() { s_DisableMessages = true; } static void DisableRunCommandOutput() { s_DisableRunCommandOutput = true; } static void EnableRunCommandOutput() { s_DisableRunCommandOutput = false; } static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; } @@ -540,7 +538,6 @@ private: static bool s_RunCommandHideConsole; static bool s_ErrorOccured; static bool s_FatalErrorOccured; - static bool s_DisableMessages; static bool s_DisableRunCommandOutput; }; diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx index dc9b6d2..9598a3f 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -304,6 +304,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, InitProperty("AUTORCC_OPTIONS", nullptr); InitProperty("LINK_DEPENDS_NO_SHARED", nullptr); InitProperty("LINK_INTERFACE_LIBRARIES", nullptr); + InitProperty("MSVC_RUNTIME_LIBRARY", nullptr); InitProperty("WIN32_EXECUTABLE", nullptr); InitProperty("MACOSX_BUNDLE", nullptr); InitProperty("MACOSX_RPATH", nullptr); diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx index 5c7b95c..3883b52 100644 --- a/Source/cmTargetLinkLibrariesCommand.cxx +++ b/Source/cmTargetLinkLibrariesCommand.cxx @@ -456,8 +456,8 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, this->Target->GetType() == cmStateEnums::OBJECT_LIBRARY) { std::string configLib = this->Target->GetDebugGeneratorExpressions(libRef, llt); - if (cmGeneratorExpression::IsValidTargetName(libRef) || - cmGeneratorExpression::Find(libRef) != std::string::npos) { + if (cmGeneratorExpression::IsValidTargetName(lib) || + cmGeneratorExpression::Find(lib) != std::string::npos) { configLib = "$<LINK_ONLY:" + configLib + ">"; } this->Target->AppendProperty("INTERFACE_LINK_LIBRARIES", diff --git a/Source/cmUVHandlePtr.cxx b/Source/cmUVHandlePtr.cxx index fd07d2d..27069ee 100644 --- a/Source/cmUVHandlePtr.cxx +++ b/Source/cmUVHandlePtr.cxx @@ -11,19 +11,59 @@ namespace cm { -static void close_delete(uv_handle_t* h) +struct uv_loop_deleter { - free(h); + void operator()(uv_loop_t* loop) const; +}; + +void uv_loop_deleter::operator()(uv_loop_t* loop) const +{ + uv_run(loop, UV_RUN_DEFAULT); + int result = uv_loop_close(loop); + (void)result; + assert(result >= 0); + free(loop); +} + +int uv_loop_ptr::init(void* data) +{ + this->reset(); + + this->loop.reset(static_cast<uv_loop_t*>(calloc(1, sizeof(uv_loop_t))), + uv_loop_deleter()); + this->loop->data = data; + + return uv_loop_init(this->loop.get()); +} + +void uv_loop_ptr::reset() +{ + this->loop.reset(); +} + +uv_loop_ptr::operator uv_loop_t*() +{ + return this->loop.get(); +} + +uv_loop_t* uv_loop_ptr::operator->() const noexcept +{ + return this->loop.get(); +} + +uv_loop_t* uv_loop_ptr::get() const +{ + return this->loop.get(); } template <typename T> -static void default_delete(T* type_handle) +static void handle_default_delete(T* type_handle) { auto handle = reinterpret_cast<uv_handle_t*>(type_handle); if (handle) { assert(!uv_is_closing(handle)); if (!uv_is_closing(handle)) { - uv_close(handle, &close_delete); + uv_close(handle, [](uv_handle_t* h) { free(h); }); } } } @@ -34,7 +74,7 @@ static void default_delete(T* type_handle) template <typename T> struct uv_handle_deleter { - void operator()(T* type_handle) const { default_delete(type_handle); } + void operator()(T* type_handle) const { handle_default_delete(type_handle); } }; template <typename T> @@ -107,7 +147,7 @@ struct uv_handle_deleter<uv_async_t> void operator()(uv_async_t* handle) { std::lock_guard<std::mutex> lock(*handleMutex); - default_delete(handle); + handle_default_delete(handle); } }; @@ -136,7 +176,7 @@ struct uv_handle_deleter<uv_signal_t> { if (handle) { uv_signal_stop(handle); - default_delete(handle); + handle_default_delete(handle); } } }; diff --git a/Source/cmUVHandlePtr.h b/Source/cmUVHandlePtr.h index 992c429..c09e4bf 100644 --- a/Source/cmUVHandlePtr.h +++ b/Source/cmUVHandlePtr.h @@ -30,7 +30,45 @@ namespace cm { /*** - * RAII class to simplify and insure the safe usage of uv_*_t types. This + * RAII class to simplify and ensure the safe usage of uv_loop_t. This includes + * making sure resources are properly freed. + */ +class uv_loop_ptr +{ +protected: + std::shared_ptr<uv_loop_t> loop; + +public: + uv_loop_ptr(uv_loop_ptr const&) = delete; + uv_loop_ptr& operator=(uv_loop_ptr const&) = delete; + uv_loop_ptr(uv_loop_ptr&&) noexcept; + uv_loop_ptr& operator=(uv_loop_ptr&&) noexcept; + + // Dtor and ctor need to be inline defined like this for default ctors and + // dtors to work. Some compilers do not like '= default' here. + uv_loop_ptr() {} // NOLINT(modernize-use-equals-default) + uv_loop_ptr(std::nullptr_t) {} + ~uv_loop_ptr() { this->reset(); } + + int init(void* data = nullptr); + + /** + * Properly close the handle if needed and sets the inner handle to nullptr + */ + void reset(); + + /** + * Allow less verbose calling of uv_loop_* functions + * @return reinterpreted handle + */ + operator uv_loop_t*(); + + uv_loop_t* get() const; + uv_loop_t* operator->() const noexcept; +}; + +/*** + * RAII class to simplify and ensure the safe usage of uv_*_t types. This * includes making sure resources are properly freed and contains casting * operators which allow for passing into relevant uv_* functions. * diff --git a/Source/cmUVStreambuf.h b/Source/cmUVStreambuf.h new file mode 100644 index 0000000..29e4fde --- /dev/null +++ b/Source/cmUVStreambuf.h @@ -0,0 +1,219 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmUVStreambuf_h +#define cmUVStreambuf_h + +#include "cmUVHandlePtr.h" + +#include "cm_uv.h" + +#include <algorithm> +#include <cstring> +#include <streambuf> +#include <vector> + +/* + * This file is based on example code from: + * + * http://www.voidcn.com/article/p-vjnlygmc-gy.html + * + * The example code was distributed under the following license: + * + * Copyright 2007 Edd Dawson. + * Distributed under the Boost Software License, Version 1.0. + * + * Boost Software License - Version 1.0 - August 17th, 2003 + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +template <typename CharT, typename Traits = std::char_traits<CharT>> +class cmBasicUVStreambuf : public std::basic_streambuf<CharT, Traits> +{ +public: + cmBasicUVStreambuf(std::size_t bufSize = 256, std::size_t putBack = 8); + ~cmBasicUVStreambuf() override; + + bool is_open() const; + + cmBasicUVStreambuf* open(uv_stream_t* stream); + + cmBasicUVStreambuf* close(); + +protected: + typename cmBasicUVStreambuf::int_type underflow() override; + std::streamsize showmanyc() override; + + // FIXME: Add write support + +private: + uv_stream_t* Stream = nullptr; + void* OldStreamData; + const std::size_t PutBack; + std::vector<CharT> InputBuffer; + bool EndOfFile; + + void StreamReadStartStop(); + + void StreamRead(ssize_t nread); + void HandleAlloc(uv_buf_t* buf); +}; + +template <typename CharT, typename Traits> +cmBasicUVStreambuf<CharT, Traits>::cmBasicUVStreambuf(std::size_t bufSize, + std::size_t putBack) + : PutBack(std::max<std::size_t>(putBack, 1)) + , InputBuffer(std::max<std::size_t>(this->PutBack, bufSize) + this->PutBack) +{ + this->close(); +} + +template <typename CharT, typename Traits> +cmBasicUVStreambuf<CharT, Traits>::~cmBasicUVStreambuf() +{ + this->close(); +} + +template <typename CharT, typename Traits> +bool cmBasicUVStreambuf<CharT, Traits>::is_open() const +{ + return this->Stream != nullptr; +} + +template <typename CharT, typename Traits> +cmBasicUVStreambuf<CharT, Traits>* cmBasicUVStreambuf<CharT, Traits>::open( + uv_stream_t* stream) +{ + this->close(); + this->Stream = stream; + this->EndOfFile = false; + if (this->Stream) { + this->OldStreamData = this->Stream->data; + this->Stream->data = this; + } + this->StreamReadStartStop(); + return this; +} + +template <typename CharT, typename Traits> +cmBasicUVStreambuf<CharT, Traits>* cmBasicUVStreambuf<CharT, Traits>::close() +{ + if (this->Stream) { + uv_read_stop(this->Stream); + this->Stream->data = this->OldStreamData; + } + this->Stream = nullptr; + CharT* readEnd = this->InputBuffer.data() + this->InputBuffer.size(); + this->setg(readEnd, readEnd, readEnd); + return this; +} + +template <typename CharT, typename Traits> +typename cmBasicUVStreambuf<CharT, Traits>::int_type +cmBasicUVStreambuf<CharT, Traits>::underflow() +{ + if (!this->is_open()) { + return Traits::eof(); + } + + if (this->gptr() < this->egptr()) { + return Traits::to_int_type(*this->gptr()); + } + + this->StreamReadStartStop(); + while (this->in_avail() == 0) { + uv_run(this->Stream->loop, UV_RUN_ONCE); + } + if (this->in_avail() == -1) { + return Traits::eof(); + } + return Traits::to_int_type(*this->gptr()); +} + +template <typename CharT, typename Traits> +std::streamsize cmBasicUVStreambuf<CharT, Traits>::showmanyc() +{ + if (!this->is_open() || this->EndOfFile) { + return -1; + } + return 0; +} + +template <typename CharT, typename Traits> +void cmBasicUVStreambuf<CharT, Traits>::StreamReadStartStop() +{ + if (this->Stream) { + uv_read_stop(this->Stream); + if (this->gptr() >= this->egptr()) { + uv_read_start( + this->Stream, + [](uv_handle_t* handle, size_t /* unused */, uv_buf_t* buf) { + auto streambuf = + static_cast<cmBasicUVStreambuf<CharT, Traits>*>(handle->data); + streambuf->HandleAlloc(buf); + }, + [](uv_stream_t* stream2, ssize_t nread, const uv_buf_t* /* unused */) { + auto streambuf = + static_cast<cmBasicUVStreambuf<CharT, Traits>*>(stream2->data); + streambuf->StreamRead(nread); + }); + } + } +} + +template <typename CharT, typename Traits> +void cmBasicUVStreambuf<CharT, Traits>::HandleAlloc(uv_buf_t* buf) +{ + auto size = this->egptr() - this->gptr(); + std::memmove(this->InputBuffer.data(), this->gptr(), + this->egptr() - this->gptr()); + this->setg(this->InputBuffer.data(), this->InputBuffer.data(), + this->InputBuffer.data() + size); + buf->base = this->egptr(); +#ifdef _WIN32 +# define BUF_LEN_TYPE ULONG +#else +# define BUF_LEN_TYPE size_t +#endif + buf->len = BUF_LEN_TYPE( + (this->InputBuffer.data() + this->InputBuffer.size() - this->egptr()) * + sizeof(CharT)); +#undef BUF_LEN_TYPE +} + +template <typename CharT, typename Traits> +void cmBasicUVStreambuf<CharT, Traits>::StreamRead(ssize_t nread) +{ + if (nread > 0) { + this->setg(this->eback(), this->gptr(), + this->egptr() + nread / sizeof(CharT)); + uv_read_stop(this->Stream); + } else if (nread < 0 || nread == UV_EOF) { + this->EndOfFile = true; + uv_read_stop(this->Stream); + } +} + +using cmUVStreambuf = cmBasicUVStreambuf<char>; + +#endif diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index 5195957..c60706d 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -663,6 +663,7 @@ void cmVisualStudio10TargetGenerator::Generate() this->WriteCustomCommands(e0); this->WriteAllSources(e0); this->WriteDotNetReferences(e0); + this->WriteImports(e0); this->WriteEmbeddedResourceGroup(e0); this->WriteXamlFilesGroup(e0); this->WriteWinRTReferences(e0); @@ -811,6 +812,24 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReference( this->WriteDotNetReferenceCustomTags(e2, ref); } +void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0) +{ + const char* imports = + this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT"); + if (imports) { + std::vector<std::string> argsSplit; + cmSystemTools::ExpandListArgument(std::string(imports), argsSplit, false); + for (auto& path : argsSplit) { + if (!cmsys::SystemTools::FileIsFullPath(path)) { + path = this->Makefile->GetCurrentSourceDirectory() + "/" + path; + } + ConvertToWindowsSlash(path); + Elem e1(e0, "Import"); + e1.Attribute("Project", path); + } + } +} + void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags( Elem& e2, std::string const& ref) { @@ -1430,10 +1449,10 @@ std::string cmVisualStudio10TargetGenerator::ConvertPath( static void ConvertToWindowsSlash(std::string& s) { // first convert all of the slashes - std::string::size_type pos = 0; - while ((pos = s.find('/', pos)) != std::string::npos) { - s[pos] = '\\'; - pos++; + for (auto& ch : s) { + if (ch == '/') { + ch = '\\'; + } } } @@ -1449,7 +1468,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups() std::vector<cmGeneratorTarget::AllConfigSource> const& sources = this->GeneratorTarget->GetAllConfigSources(); - std::set<cmSourceGroup*> groupsUsed; + std::set<cmSourceGroup const*> groupsUsed; for (cmGeneratorTarget::AllConfigSource const& si : sources) { std::string const& source = si.Source->GetFullPath(); cmSourceGroup* sourceGroup = @@ -1534,13 +1553,13 @@ void cmVisualStudio10TargetGenerator::WriteGroups() { Elem e1(e0, "ItemGroup"); e1.SetHasElements(); - std::vector<cmSourceGroup*> groupsVec(groupsUsed.begin(), - groupsUsed.end()); + std::vector<cmSourceGroup const*> groupsVec(groupsUsed.begin(), + groupsUsed.end()); std::sort(groupsVec.begin(), groupsVec.end(), - [](cmSourceGroup* l, cmSourceGroup* r) { + [](cmSourceGroup const* l, cmSourceGroup const* r) { return l->GetFullName() < r->GetFullName(); }); - for (cmSourceGroup* sg : groupsVec) { + for (cmSourceGroup const* sg : groupsVec) { std::string const& name = sg->GetFullName(); if (!name.empty()) { std::string guidName = "SG_Filter_" + name; @@ -1572,7 +1591,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups() // Add to groupsUsed empty source groups that have non-empty children. void cmVisualStudio10TargetGenerator::AddMissingSourceGroups( - std::set<cmSourceGroup*>& groupsUsed, + std::set<cmSourceGroup const*>& groupsUsed, const std::vector<cmSourceGroup>& allGroups) { for (cmSourceGroup const& current : allGroups) { @@ -1583,17 +1602,15 @@ void cmVisualStudio10TargetGenerator::AddMissingSourceGroups( this->AddMissingSourceGroups(groupsUsed, children); - cmSourceGroup* current_ptr = const_cast<cmSourceGroup*>(¤t); - if (groupsUsed.find(current_ptr) != groupsUsed.end()) { + if (groupsUsed.count(¤t) > 0) { continue; // group has already been added to set } // check if it least one of the group's descendants is not empty // (at least one child must already have been added) - std::vector<cmSourceGroup>::const_iterator child_it = children.begin(); + auto child_it = children.begin(); while (child_it != children.end()) { - cmSourceGroup* child_ptr = const_cast<cmSourceGroup*>(&(*child_it)); - if (groupsUsed.find(child_ptr) != groupsUsed.end()) { + if (groupsUsed.count(&(*child_it)) > 0) { break; // found a child that was already added => add current group too } child_it++; @@ -1603,7 +1620,7 @@ void cmVisualStudio10TargetGenerator::AddMissingSourceGroups( continue; // no descendants have source files => ignore this group } - groupsUsed.insert(current_ptr); + groupsUsed.insert(¤t); } } @@ -2530,10 +2547,9 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( } else { std::set<std::string> languages; this->GeneratorTarget->GetLanguages(languages, configName); - for (const char* const* l = cm::cbegin(clLangs); l != cm::cend(clLangs); - ++l) { - if (languages.find(*l) != languages.end()) { - langForClCompile = *l; + for (const char* l : clLangs) { + if (languages.count(l)) { + langForClCompile = l; break; } } @@ -4058,10 +4074,7 @@ bool cmVisualStudio10TargetGenerator::IsResxHeader( { std::set<std::string> expectedResxHeaders; this->GeneratorTarget->GetExpectedResxHeaders(expectedResxHeaders, ""); - - std::set<std::string>::const_iterator it = - expectedResxHeaders.find(headerFile); - return it != expectedResxHeaders.end(); + return expectedResxHeaders.count(headerFile) > 0; } bool cmVisualStudio10TargetGenerator::IsXamlHeader( @@ -4069,10 +4082,7 @@ bool cmVisualStudio10TargetGenerator::IsXamlHeader( { std::set<std::string> expectedXamlHeaders; this->GeneratorTarget->GetExpectedXamlHeaders(expectedXamlHeaders, ""); - - std::set<std::string>::const_iterator it = - expectedXamlHeaders.find(headerFile); - return it != expectedXamlHeaders.end(); + return expectedXamlHeaders.count(headerFile) > 0; } bool cmVisualStudio10TargetGenerator::IsXamlSource( @@ -4080,10 +4090,7 @@ bool cmVisualStudio10TargetGenerator::IsXamlSource( { std::set<std::string> expectedXamlSources; this->GeneratorTarget->GetExpectedXamlSources(expectedXamlSources, ""); - - std::set<std::string>::const_iterator it = - expectedXamlSources.find(sourceFile); - return it != expectedXamlSources.end(); + return expectedXamlSources.count(sourceFile) > 0; } void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings(Elem& e1) @@ -4654,10 +4661,8 @@ void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties( void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties( Elem& e2, const std::map<std::string, std::string>& tags) { - if (!tags.empty()) { - for (const auto& i : tags) { - e2.Element(i.first.c_str(), i.second); - } + for (const auto& i : tags) { + e2.Element(i.first.c_str(), i.second); } } diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h index 5901004..1dea8e9 100644 --- a/Source/cmVisualStudio10TargetGenerator.h +++ b/Source/cmVisualStudio10TargetGenerator.h @@ -76,6 +76,7 @@ private: void WriteDotNetReference(Elem& e1, std::string const& ref, std::string const& hint, std::string const& config); + void WriteImports(Elem& e0); void WriteDotNetReferenceCustomTags(Elem& e2, std::string const& ref); void WriteEmbeddedResourceGroup(Elem& e0); void WriteWinRTReferences(Elem& e0); @@ -165,7 +166,7 @@ private: void WriteGroupSources(Elem& e0, std::string const& name, ToolSources const& sources, std::vector<cmSourceGroup>&); - void AddMissingSourceGroups(std::set<cmSourceGroup*>& groupsUsed, + void AddMissingSourceGroups(std::set<cmSourceGroup const*>& groupsUsed, const std::vector<cmSourceGroup>& allGroups); bool IsResxHeader(const std::string& headerFile); bool IsXamlHeader(const std::string& headerFile); diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx index e8b2668..e1b0c70 100644 --- a/Source/cmVisualStudioGeneratorOptions.cxx +++ b/Source/cmVisualStudioGeneratorOptions.cxx @@ -374,19 +374,19 @@ void cmVisualStudioGeneratorOptions::StoreUnknownFlag(std::string const& flag) { // Look for Intel Fortran flags that do not map well in the flag table. if (this->CurrentTool == FortranCompiler) { - if (flag == "/dbglibs") { + if (flag == "/dbglibs" || flag == "-dbglibs") { this->FortranRuntimeDebug = true; return; } - if (flag == "/threads") { + if (flag == "/threads" || flag == "-threads") { this->FortranRuntimeMT = true; return; } - if (flag == "/libs:dll") { + if (flag == "/libs:dll" || flag == "-libs:dll") { this->FortranRuntimeDLL = true; return; } - if (flag == "/libs:static") { + if (flag == "/libs:static" || flag == "-libs:static") { this->FortranRuntimeDLL = false; return; } diff --git a/Source/cmWorkerPool.cxx b/Source/cmWorkerPool.cxx new file mode 100644 index 0000000..cbf070e --- /dev/null +++ b/Source/cmWorkerPool.cxx @@ -0,0 +1,763 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmWorkerPool.h" + +#include "cmRange.h" +#include "cmUVHandlePtr.h" +#include "cmUVSignalHackRAII.h" // IWYU pragma: keep +#include "cm_uv.h" + +#include <algorithm> +#include <array> +#include <condition_variable> +#include <deque> +#include <functional> +#include <mutex> +#include <stddef.h> +#include <thread> + +/** + * @brief libuv pipe buffer class + */ +class cmUVPipeBuffer +{ +public: + typedef cmRange<char const*> DataRange; + typedef std::function<void(DataRange)> DataFunction; + /// On error the ssize_t argument is a non zero libuv error code + typedef std::function<void(ssize_t)> EndFunction; + +public: + /** + * Reset to construction state + */ + void reset(); + + /** + * Initializes uv_pipe(), uv_stream() and uv_handle() + * @return true on success + */ + bool init(uv_loop_t* uv_loop); + + /** + * Start reading + * @return true on success + */ + bool startRead(DataFunction dataFunction, EndFunction endFunction); + + //! libuv pipe + uv_pipe_t* uv_pipe() const { return UVPipe_.get(); } + //! uv_pipe() casted to libuv stream + uv_stream_t* uv_stream() const { return static_cast<uv_stream_t*>(UVPipe_); } + //! uv_pipe() casted to libuv handle + uv_handle_t* uv_handle() { return static_cast<uv_handle_t*>(UVPipe_); } + +private: + // -- Libuv callbacks + static void UVAlloc(uv_handle_t* handle, size_t suggestedSize, + uv_buf_t* buf); + static void UVData(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf); + +private: + cm::uv_pipe_ptr UVPipe_; + std::vector<char> Buffer_; + DataFunction DataFunction_; + EndFunction EndFunction_; +}; + +void cmUVPipeBuffer::reset() +{ + if (UVPipe_.get() != nullptr) { + EndFunction_ = nullptr; + DataFunction_ = nullptr; + Buffer_.clear(); + Buffer_.shrink_to_fit(); + UVPipe_.reset(); + } +} + +bool cmUVPipeBuffer::init(uv_loop_t* uv_loop) +{ + reset(); + if (uv_loop == nullptr) { + return false; + } + int ret = UVPipe_.init(*uv_loop, 0, this); + return (ret == 0); +} + +bool cmUVPipeBuffer::startRead(DataFunction dataFunction, + EndFunction endFunction) +{ + if (UVPipe_.get() == nullptr) { + return false; + } + if (!dataFunction || !endFunction) { + return false; + } + DataFunction_ = std::move(dataFunction); + EndFunction_ = std::move(endFunction); + int ret = uv_read_start(uv_stream(), &cmUVPipeBuffer::UVAlloc, + &cmUVPipeBuffer::UVData); + return (ret == 0); +} + +void cmUVPipeBuffer::UVAlloc(uv_handle_t* handle, size_t suggestedSize, + uv_buf_t* buf) +{ + auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(handle->data); + pipe.Buffer_.resize(suggestedSize); + buf->base = pipe.Buffer_.data(); + buf->len = static_cast<unsigned long>(pipe.Buffer_.size()); +} + +void cmUVPipeBuffer::UVData(uv_stream_t* stream, ssize_t nread, + const uv_buf_t* buf) +{ + auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(stream->data); + if (nread > 0) { + if (buf->base != nullptr) { + // Call data function + pipe.DataFunction_(DataRange(buf->base, buf->base + nread)); + } + } else if (nread < 0) { + // Save the end function on the stack before resetting the pipe + EndFunction efunc; + efunc.swap(pipe.EndFunction_); + // Reset pipe before calling the end function + pipe.reset(); + // Call end function + efunc((nread == UV_EOF) ? 0 : nread); + } +} + +/** + * @brief External process management class + */ +class cmUVReadOnlyProcess +{ +public: + // -- Types + //! @brief Process settings + struct SetupT + { + std::string WorkingDirectory; + std::vector<std::string> Command; + cmWorkerPool::ProcessResultT* Result = nullptr; + bool MergedOutput = false; + }; + +public: + // -- Const accessors + SetupT const& Setup() const { return Setup_; } + cmWorkerPool::ProcessResultT* Result() const { return Setup_.Result; } + bool IsStarted() const { return IsStarted_; } + bool IsFinished() const { return IsFinished_; } + + // -- Runtime + void setup(cmWorkerPool::ProcessResultT* result, bool mergedOutput, + std::vector<std::string> const& command, + std::string const& workingDirectory = std::string()); + bool start(uv_loop_t* uv_loop, std::function<void()> finishedCallback); + +private: + // -- Libuv callbacks + static void UVExit(uv_process_t* handle, int64_t exitStatus, int termSignal); + void UVPipeOutData(cmUVPipeBuffer::DataRange data); + void UVPipeOutEnd(ssize_t error); + void UVPipeErrData(cmUVPipeBuffer::DataRange data); + void UVPipeErrEnd(ssize_t error); + void UVTryFinish(); + +private: + // -- Setup + SetupT Setup_; + // -- Runtime + bool IsStarted_ = false; + bool IsFinished_ = false; + std::function<void()> FinishedCallback_; + std::vector<const char*> CommandPtr_; + std::array<uv_stdio_container_t, 3> UVOptionsStdIO_; + uv_process_options_t UVOptions_; + cm::uv_process_ptr UVProcess_; + cmUVPipeBuffer UVPipeOut_; + cmUVPipeBuffer UVPipeErr_; +}; + +void cmUVReadOnlyProcess::setup(cmWorkerPool::ProcessResultT* result, + bool mergedOutput, + std::vector<std::string> const& command, + std::string const& workingDirectory) +{ + Setup_.WorkingDirectory = workingDirectory; + Setup_.Command = command; + Setup_.Result = result; + Setup_.MergedOutput = mergedOutput; +} + +bool cmUVReadOnlyProcess::start(uv_loop_t* uv_loop, + std::function<void()> finishedCallback) +{ + if (IsStarted() || (Result() == nullptr)) { + return false; + } + + // Reset result before the start + Result()->reset(); + + // Fill command string pointers + if (!Setup().Command.empty()) { + CommandPtr_.reserve(Setup().Command.size() + 1); + for (std::string const& arg : Setup().Command) { + CommandPtr_.push_back(arg.c_str()); + } + CommandPtr_.push_back(nullptr); + } else { + Result()->ErrorMessage = "Empty command"; + } + + if (!Result()->error()) { + if (!UVPipeOut_.init(uv_loop)) { + Result()->ErrorMessage = "libuv stdout pipe initialization failed"; + } + } + if (!Result()->error()) { + if (!UVPipeErr_.init(uv_loop)) { + Result()->ErrorMessage = "libuv stderr pipe initialization failed"; + } + } + if (!Result()->error()) { + // -- Setup process stdio options + // stdin + UVOptionsStdIO_[0].flags = UV_IGNORE; + UVOptionsStdIO_[0].data.stream = nullptr; + // stdout + UVOptionsStdIO_[1].flags = + static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); + UVOptionsStdIO_[1].data.stream = UVPipeOut_.uv_stream(); + // stderr + UVOptionsStdIO_[2].flags = + static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); + UVOptionsStdIO_[2].data.stream = UVPipeErr_.uv_stream(); + + // -- Setup process options + std::fill_n(reinterpret_cast<char*>(&UVOptions_), sizeof(UVOptions_), 0); + UVOptions_.exit_cb = &cmUVReadOnlyProcess::UVExit; + UVOptions_.file = CommandPtr_[0]; + UVOptions_.args = const_cast<char**>(CommandPtr_.data()); + UVOptions_.cwd = Setup_.WorkingDirectory.c_str(); + UVOptions_.flags = UV_PROCESS_WINDOWS_HIDE; + UVOptions_.stdio_count = static_cast<int>(UVOptionsStdIO_.size()); + UVOptions_.stdio = UVOptionsStdIO_.data(); + + // -- Spawn process + int uvErrorCode = UVProcess_.spawn(*uv_loop, UVOptions_, this); + if (uvErrorCode != 0) { + Result()->ErrorMessage = "libuv process spawn failed"; + if (const char* uvErr = uv_strerror(uvErrorCode)) { + Result()->ErrorMessage += ": "; + Result()->ErrorMessage += uvErr; + } + } + } + // -- Start reading from stdio streams + if (!Result()->error()) { + if (!UVPipeOut_.startRead( + [this](cmUVPipeBuffer::DataRange range) { + this->UVPipeOutData(range); + }, + [this](ssize_t error) { this->UVPipeOutEnd(error); })) { + Result()->ErrorMessage = "libuv start reading from stdout pipe failed"; + } + } + if (!Result()->error()) { + if (!UVPipeErr_.startRead( + [this](cmUVPipeBuffer::DataRange range) { + this->UVPipeErrData(range); + }, + [this](ssize_t error) { this->UVPipeErrEnd(error); })) { + Result()->ErrorMessage = "libuv start reading from stderr pipe failed"; + } + } + + if (!Result()->error()) { + IsStarted_ = true; + FinishedCallback_ = std::move(finishedCallback); + } else { + // Clear libuv handles and finish + UVProcess_.reset(); + UVPipeOut_.reset(); + UVPipeErr_.reset(); + CommandPtr_.clear(); + } + + return IsStarted(); +} + +void cmUVReadOnlyProcess::UVExit(uv_process_t* handle, int64_t exitStatus, + int termSignal) +{ + auto& proc = *reinterpret_cast<cmUVReadOnlyProcess*>(handle->data); + if (proc.IsStarted() && !proc.IsFinished()) { + // Set error message on demand + proc.Result()->ExitStatus = exitStatus; + proc.Result()->TermSignal = termSignal; + if (!proc.Result()->error()) { + if (termSignal != 0) { + proc.Result()->ErrorMessage = "Process was terminated by signal "; + proc.Result()->ErrorMessage += + std::to_string(proc.Result()->TermSignal); + } else if (exitStatus != 0) { + proc.Result()->ErrorMessage = "Process failed with return value "; + proc.Result()->ErrorMessage += + std::to_string(proc.Result()->ExitStatus); + } + } + + // Reset process handle + proc.UVProcess_.reset(); + // Try finish + proc.UVTryFinish(); + } +} + +void cmUVReadOnlyProcess::UVPipeOutData(cmUVPipeBuffer::DataRange data) +{ + Result()->StdOut.append(data.begin(), data.end()); +} + +void cmUVReadOnlyProcess::UVPipeOutEnd(ssize_t error) +{ + // Process pipe error + if ((error != 0) && !Result()->error()) { + Result()->ErrorMessage = + "Reading from stdout pipe failed with libuv error code "; + Result()->ErrorMessage += std::to_string(error); + } + // Try finish + UVTryFinish(); +} + +void cmUVReadOnlyProcess::UVPipeErrData(cmUVPipeBuffer::DataRange data) +{ + std::string* str = + Setup_.MergedOutput ? &Result()->StdOut : &Result()->StdErr; + str->append(data.begin(), data.end()); +} + +void cmUVReadOnlyProcess::UVPipeErrEnd(ssize_t error) +{ + // Process pipe error + if ((error != 0) && !Result()->error()) { + Result()->ErrorMessage = + "Reading from stderr pipe failed with libuv error code "; + Result()->ErrorMessage += std::to_string(error); + } + // Try finish + UVTryFinish(); +} + +void cmUVReadOnlyProcess::UVTryFinish() +{ + // There still might be data in the pipes after the process has finished. + // Therefore check if the process is finished AND all pipes are closed + // before signaling the worker thread to continue. + if ((UVProcess_.get() != nullptr) || (UVPipeOut_.uv_pipe() != nullptr) || + (UVPipeErr_.uv_pipe() != nullptr)) { + return; + } + IsFinished_ = true; + FinishedCallback_(); +} + +/** + * @brief Worker pool worker thread + */ +class cmWorkerPoolWorker +{ +public: + cmWorkerPoolWorker(uv_loop_t& uvLoop); + ~cmWorkerPoolWorker(); + + cmWorkerPoolWorker(cmWorkerPoolWorker const&) = delete; + cmWorkerPoolWorker& operator=(cmWorkerPoolWorker const&) = delete; + + /** + * Set the internal thread + */ + void SetThread(std::thread&& aThread) { Thread_ = std::move(aThread); } + + /** + * Run an external process + */ + bool RunProcess(cmWorkerPool::ProcessResultT& result, + std::vector<std::string> const& command, + std::string const& workingDirectory); + +private: + // -- Libuv callbacks + static void UVProcessStart(uv_async_t* handle); + void UVProcessFinished(); + +private: + // -- Process management + struct + { + std::mutex Mutex; + cm::uv_async_ptr Request; + std::condition_variable Condition; + std::unique_ptr<cmUVReadOnlyProcess> ROP; + } Proc_; + // -- System thread + std::thread Thread_; +}; + +cmWorkerPoolWorker::cmWorkerPoolWorker(uv_loop_t& uvLoop) +{ + Proc_.Request.init(uvLoop, &cmWorkerPoolWorker::UVProcessStart, this); +} + +cmWorkerPoolWorker::~cmWorkerPoolWorker() +{ + if (Thread_.joinable()) { + Thread_.join(); + } +} + +bool cmWorkerPoolWorker::RunProcess(cmWorkerPool::ProcessResultT& result, + std::vector<std::string> const& command, + std::string const& workingDirectory) +{ + if (command.empty()) { + return false; + } + // Create process instance + { + std::lock_guard<std::mutex> lock(Proc_.Mutex); + Proc_.ROP = cm::make_unique<cmUVReadOnlyProcess>(); + Proc_.ROP->setup(&result, true, command, workingDirectory); + } + // Send asynchronous process start request to libuv loop + Proc_.Request.send(); + // Wait until the process has been finished and destroyed + { + std::unique_lock<std::mutex> ulock(Proc_.Mutex); + while (Proc_.ROP) { + Proc_.Condition.wait(ulock); + } + } + return !result.error(); +} + +void cmWorkerPoolWorker::UVProcessStart(uv_async_t* handle) +{ + auto* wrk = reinterpret_cast<cmWorkerPoolWorker*>(handle->data); + bool startFailed = false; + { + auto& Proc = wrk->Proc_; + std::lock_guard<std::mutex> lock(Proc.Mutex); + if (Proc.ROP && !Proc.ROP->IsStarted()) { + startFailed = + !Proc.ROP->start(handle->loop, [wrk] { wrk->UVProcessFinished(); }); + } + } + // Clean up if starting of the process failed + if (startFailed) { + wrk->UVProcessFinished(); + } +} + +void cmWorkerPoolWorker::UVProcessFinished() +{ + { + std::lock_guard<std::mutex> lock(Proc_.Mutex); + if (Proc_.ROP && (Proc_.ROP->IsFinished() || !Proc_.ROP->IsStarted())) { + Proc_.ROP.reset(); + } + } + // Notify idling thread + Proc_.Condition.notify_one(); +} + +/** + * @brief Private worker pool internals + */ +class cmWorkerPoolInternal +{ +public: + // -- Constructors + cmWorkerPoolInternal(cmWorkerPool* pool); + ~cmWorkerPoolInternal(); + + /** + * Runs the libuv loop. + */ + bool Process(); + + /** + * Clear queue and abort threads. + */ + void Abort(); + + /** + * Push a job to the queue and notify a worker. + */ + bool PushJob(cmWorkerPool::JobHandleT&& jobHandle); + + /** + * Worker thread main loop method. + */ + void Work(unsigned int workerIndex); + + // -- Request slots + static void UVSlotBegin(uv_async_t* handle); + static void UVSlotEnd(uv_async_t* handle); + +public: + // -- UV loop +#ifdef CMAKE_UV_SIGNAL_HACK + std::unique_ptr<cmUVSignalHackRAII> UVHackRAII; +#endif + std::unique_ptr<uv_loop_t> UVLoop; + cm::uv_async_ptr UVRequestBegin; + cm::uv_async_ptr UVRequestEnd; + + // -- Thread pool and job queue + std::mutex Mutex; + bool Processing = false; + bool Aborting = false; + bool FenceProcessing = false; + unsigned int WorkersRunning = 0; + unsigned int WorkersIdle = 0; + unsigned int JobsProcessing = 0; + std::deque<cmWorkerPool::JobHandleT> Queue; + std::condition_variable Condition; + std::vector<std::unique_ptr<cmWorkerPoolWorker>> Workers; + + // -- References + cmWorkerPool* Pool = nullptr; +}; + +void cmWorkerPool::ProcessResultT::reset() +{ + ExitStatus = 0; + TermSignal = 0; + if (!StdOut.empty()) { + StdOut.clear(); + StdOut.shrink_to_fit(); + } + if (!StdErr.empty()) { + StdErr.clear(); + StdErr.shrink_to_fit(); + } + if (!ErrorMessage.empty()) { + ErrorMessage.clear(); + ErrorMessage.shrink_to_fit(); + } +} + +cmWorkerPoolInternal::cmWorkerPoolInternal(cmWorkerPool* pool) + : Pool(pool) +{ + // Initialize libuv loop + uv_disable_stdio_inheritance(); +#ifdef CMAKE_UV_SIGNAL_HACK + UVHackRAII = cm::make_unique<cmUVSignalHackRAII>(); +#endif + UVLoop = cm::make_unique<uv_loop_t>(); + uv_loop_init(UVLoop.get()); +} + +cmWorkerPoolInternal::~cmWorkerPoolInternal() +{ + uv_loop_close(UVLoop.get()); +} + +bool cmWorkerPoolInternal::Process() +{ + // Reset state flags + Processing = true; + Aborting = false; + // Initialize libuv asynchronous request + UVRequestBegin.init(*UVLoop, &cmWorkerPoolInternal::UVSlotBegin, this); + UVRequestEnd.init(*UVLoop, &cmWorkerPoolInternal::UVSlotEnd, this); + // Send begin request + UVRequestBegin.send(); + // Run libuv loop + bool success = (uv_run(UVLoop.get(), UV_RUN_DEFAULT) == 0); + // Update state flags + Processing = false; + Aborting = false; + return success; +} + +void cmWorkerPoolInternal::Abort() +{ + bool notifyThreads = false; + // Clear all jobs and set abort flag + { + std::lock_guard<std::mutex> guard(Mutex); + if (Processing && !Aborting) { + // Register abort and clear queue + Aborting = true; + Queue.clear(); + notifyThreads = true; + } + } + if (notifyThreads) { + // Wake threads + Condition.notify_all(); + } +} + +inline bool cmWorkerPoolInternal::PushJob(cmWorkerPool::JobHandleT&& jobHandle) +{ + std::lock_guard<std::mutex> guard(Mutex); + if (Aborting) { + return false; + } + // Append the job to the queue + Queue.emplace_back(std::move(jobHandle)); + // Notify an idle worker if there's one + if (WorkersIdle != 0) { + Condition.notify_one(); + } + // Return success + return true; +} + +void cmWorkerPoolInternal::UVSlotBegin(uv_async_t* handle) +{ + auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data); + // Create worker threads + { + unsigned int const num = gint.Pool->ThreadCount(); + // Create workers + gint.Workers.reserve(num); + for (unsigned int ii = 0; ii != num; ++ii) { + gint.Workers.emplace_back( + cm::make_unique<cmWorkerPoolWorker>(*gint.UVLoop)); + } + // Start worker threads + for (unsigned int ii = 0; ii != num; ++ii) { + gint.Workers[ii]->SetThread( + std::thread(&cmWorkerPoolInternal::Work, &gint, ii)); + } + } + // Destroy begin request + gint.UVRequestBegin.reset(); +} + +void cmWorkerPoolInternal::UVSlotEnd(uv_async_t* handle) +{ + auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data); + // Join and destroy worker threads + gint.Workers.clear(); + // Destroy end request + gint.UVRequestEnd.reset(); +} + +void cmWorkerPoolInternal::Work(unsigned int workerIndex) +{ + cmWorkerPool::JobHandleT jobHandle; + std::unique_lock<std::mutex> uLock(Mutex); + // Increment running workers count + ++WorkersRunning; + // Enter worker main loop + while (true) { + // Abort on request + if (Aborting) { + break; + } + // Wait for new jobs + if (Queue.empty()) { + ++WorkersIdle; + Condition.wait(uLock); + --WorkersIdle; + continue; + } + + // Check for fence jobs + if (FenceProcessing || Queue.front()->IsFence()) { + if (JobsProcessing != 0) { + Condition.wait(uLock); + continue; + } + // No jobs get processed. Set the fence job processing flag. + FenceProcessing = true; + } + + // Pop next job from queue + jobHandle = std::move(Queue.front()); + Queue.pop_front(); + + // Unlocked scope for job processing + ++JobsProcessing; + { + uLock.unlock(); + jobHandle->Work(Pool, workerIndex); // Process job + jobHandle.reset(); // Destroy job + uLock.lock(); + } + --JobsProcessing; + + // Was this a fence job? + if (FenceProcessing) { + FenceProcessing = false; + Condition.notify_all(); + } + } + + // Decrement running workers count + if (--WorkersRunning == 0) { + // Last worker thread about to finish. Send libuv event. + UVRequestEnd.send(); + } +} + +cmWorkerPool::JobT::~JobT() = default; + +bool cmWorkerPool::JobT::RunProcess(ProcessResultT& result, + std::vector<std::string> const& command, + std::string const& workingDirectory) +{ + // Get worker by index + auto* wrk = Pool_->Int_->Workers.at(WorkerIndex_).get(); + return wrk->RunProcess(result, command, workingDirectory); +} + +cmWorkerPool::cmWorkerPool() + : Int_(cm::make_unique<cmWorkerPoolInternal>(this)) +{ +} + +cmWorkerPool::~cmWorkerPool() = default; + +void cmWorkerPool::SetThreadCount(unsigned int threadCount) +{ + if (!Int_->Processing) { + ThreadCount_ = (threadCount > 0) ? threadCount : 1u; + } +} + +bool cmWorkerPool::Process(void* userData) +{ + // Setup user data + UserData_ = userData; + // Run libuv loop + bool success = Int_->Process(); + // Clear user data + UserData_ = nullptr; + // Return + return success; +} + +bool cmWorkerPool::PushJob(JobHandleT&& jobHandle) +{ + return Int_->PushJob(std::move(jobHandle)); +} + +void cmWorkerPool::Abort() +{ + Int_->Abort(); +} diff --git a/Source/cmWorkerPool.h b/Source/cmWorkerPool.h new file mode 100644 index 0000000..f08bb4f --- /dev/null +++ b/Source/cmWorkerPool.h @@ -0,0 +1,226 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmWorkerPool_h +#define cmWorkerPool_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include "cmAlgorithms.h" // IWYU pragma: keep + +#include <memory> // IWYU pragma: keep +#include <stdint.h> +#include <string> +#include <utility> +#include <vector> + +// -- Types +class cmWorkerPoolInternal; + +/** @class cmWorkerPool + * @brief Thread pool with job queue + */ +class cmWorkerPool +{ +public: + /** + * Return value and output of an external process. + */ + struct ProcessResultT + { + void reset(); + bool error() const + { + return (ExitStatus != 0) || (TermSignal != 0) || !ErrorMessage.empty(); + } + + std::int64_t ExitStatus = 0; + int TermSignal = 0; + std::string StdOut; + std::string StdErr; + std::string ErrorMessage; + }; + + /** + * Abstract job class for concurrent job processing. + */ + class JobT + { + public: + JobT(JobT const&) = delete; + JobT& operator=(JobT const&) = delete; + + /** + * Virtual destructor. + */ + virtual ~JobT(); + + /** + * Fence job flag + * + * Fence jobs require that: + * - all jobs before in the queue have been processed + * - no jobs later in the queue will be processed before this job was + * processed + */ + bool IsFence() const { return Fence_; } + + protected: + /** + * Protected default constructor + */ + JobT(bool fence = false) + : Fence_(fence) + { + } + + /** + * Abstract processing interface that must be implement in derived classes. + */ + virtual void Process() = 0; + + /** + * Get the worker pool. + * Only valid during the JobT::Process() call! + */ + cmWorkerPool* Pool() const { return Pool_; } + + /** + * Get the user data. + * Only valid during the JobT::Process() call! + */ + void* UserData() const { return Pool_->UserData(); }; + + /** + * Get the worker index. + * This is the index of the thread processing this job and is in the range + * [0..ThreadCount). + * Concurrently processing jobs will never have the same WorkerIndex(). + * Only valid during the JobT::Process() call! + */ + unsigned int WorkerIndex() const { return WorkerIndex_; } + + /** + * Run an external read only process. + * Use only during JobT::Process() call! + */ + bool RunProcess(ProcessResultT& result, + std::vector<std::string> const& command, + std::string const& workingDirectory); + + private: + //! Needs access to Work() + friend class cmWorkerPoolInternal; + //! Worker thread entry method. + void Work(cmWorkerPool* pool, unsigned int workerIndex) + { + Pool_ = pool; + WorkerIndex_ = workerIndex; + this->Process(); + } + + private: + cmWorkerPool* Pool_ = nullptr; + unsigned int WorkerIndex_ = 0; + bool Fence_ = false; + }; + + /** + * Job handle type + */ + typedef std::unique_ptr<JobT> JobHandleT; + + /** + * Fence job base class + */ + class JobFenceT : public JobT + { + public: + JobFenceT() + : JobT(true) + { + } + //! Does nothing + void Process() override{}; + }; + + /** + * Fence job that aborts the worker pool. + * + * Useful as the last job in the job queue. + */ + class JobEndT : JobFenceT + { + public: + //! Does nothing + void Process() override { Pool()->Abort(); } + }; + +public: + // -- Methods + cmWorkerPool(); + ~cmWorkerPool(); + + /** + * Number of worker threads. + */ + unsigned int ThreadCount() const { return ThreadCount_; } + + /** + * Set the number of worker threads. + * + * Calling this method during Process() has no effect. + */ + void SetThreadCount(unsigned int threadCount); + + /** + * Blocking function that starts threads to process all Jobs in the queue. + * + * This method blocks until a job calls the Abort() method. + * @arg threadCount Number of threads to process jobs. + * @arg userData Common user data pointer available in all Jobs. + */ + bool Process(void* userData = nullptr); + + /** + * User data reference passed to Process(). + * + * Only valid during Process(). + */ + void* UserData() const { return UserData_; } + + // -- Job processing interface + + /** + * Clears the job queue and aborts all worker threads. + * + * This method is thread safe and can be called from inside a job. + */ + void Abort(); + + /** + * Push job to the queue. + * + * This method is thread safe and can be called from inside a job or before + * Process(). + */ + bool PushJob(JobHandleT&& jobHandle); + + /** + * Push job to the queue + * + * This method is thread safe and can be called from inside a job or before + * Process(). + */ + template <class T, typename... Args> + bool EmplaceJob(Args&&... args) + { + return PushJob(cm::make_unique<T>(std::forward<Args>(args)...)); + } + +private: + void* UserData_ = nullptr; + unsigned int ThreadCount_ = 1; + std::unique_ptr<cmWorkerPoolInternal> Int_; +}; + +#endif diff --git a/Source/cmake.cxx b/Source/cmake.cxx index fc24ac0..121d12d 100644 --- a/Source/cmake.cxx +++ b/Source/cmake.cxx @@ -718,6 +718,14 @@ void cmake::SetArgs(const std::vector<std::string>& args) } else if (arg.find("--debug-output", 0) == 0) { std::cout << "Running with debug output on.\n"; this->SetDebugOutputOn(true); + } else if (arg.find("--loglevel=", 0) == 0) { + const auto logLevel = + StringToLogLevel(arg.substr(sizeof("--loglevel=") - 1)); + if (logLevel == LogLevel::LOG_UNDEFINED) { + cmSystemTools::Error("Invalid level specified for --loglevel"); + return; + } + this->SetLogLevel(logLevel); } else if (arg.find("--trace-expand", 0) == 0) { std::cout << "Running with expanded trace output on.\n"; this->SetTrace(true); @@ -828,6 +836,25 @@ void cmake::SetArgs(const std::vector<std::string>& args) } } +cmake::LogLevel cmake::StringToLogLevel(const std::string& levelStr) +{ + using LevelsPair = std::pair<std::string, LogLevel>; + static const std::vector<LevelsPair> levels = { + { "error", LogLevel::LOG_ERROR }, { "warning", LogLevel::LOG_WARNING }, + { "notice", LogLevel::LOG_NOTICE }, { "status", LogLevel::LOG_STATUS }, + { "verbose", LogLevel::LOG_VERBOSE }, { "debug", LogLevel::LOG_DEBUG }, + { "trace", LogLevel::LOG_TRACE } + }; + + const auto levelStrLowCase = cmSystemTools::LowerCase(levelStr); + + const auto it = std::find_if(levels.cbegin(), levels.cend(), + [&levelStrLowCase](const LevelsPair& p) { + return p.first == levelStrLowCase; + }); + return (it != levels.cend()) ? it->second : LogLevel::LOG_UNDEFINED; +} + void cmake::SetDirectoriesFromFile(const char* arg) { // Check if the argument refers to a CMakeCache.txt or diff --git a/Source/cmake.h b/Source/cmake.h index 8b4b396..4a345cf 100644 --- a/Source/cmake.h +++ b/Source/cmake.h @@ -96,6 +96,19 @@ public: FIND_PACKAGE_MODE }; + /** \brief Define log level constants. */ + enum LogLevel + { + LOG_UNDEFINED, + LOG_ERROR, + LOG_WARNING, + LOG_NOTICE, + LOG_STATUS, + LOG_VERBOSE, + LOG_DEBUG, + LOG_TRACE + }; + struct GeneratorInfo { std::string name; @@ -331,6 +344,11 @@ public: */ cmFileTimeCache* GetFileTimeCache() { return this->FileTimeCache; } + // Get the selected log level for `message()` commands during the cmake run. + LogLevel GetLogLevel() const { return this->MessageLogLevel; } + void SetLogLevel(LogLevel level) { this->MessageLogLevel = level; } + static LogLevel StringToLogLevel(const std::string& levelStr); + // Do we want debug output during the cmake run. bool GetDebugOutput() { return this->DebugOutput; } void SetDebugOutputOn(bool b) { this->DebugOutput = b; } @@ -524,6 +542,8 @@ private: std::vector<std::string> TraceOnlyThisSources; + LogLevel MessageLogLevel = LogLevel::LOG_STATUS; + void UpdateConversionPathTable(); // Print a list of valid generators to stderr. diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx index d70c9d9..5631d10 100644 --- a/Source/cmakemain.cxx +++ b/Source/cmakemain.cxx @@ -95,6 +95,8 @@ static const char* cmDocumentationOptions[][2] = { "Generate graphviz of dependencies, see " "CMakeGraphVizOptions.cmake for more." }, { "--system-information [file]", "Dump information about this system." }, + { "--loglevel=<error|warn|notice|status|verbose|debug|trace>", + "Set the verbosity of messages from CMake files." }, { "--debug-trycompile", "Do not delete the try_compile build tree. Only " "useful on one try_compile at a time." }, diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx index c18c256..3c75957 100644 --- a/Source/cmcmd.cxx +++ b/Source/cmcmd.cxx @@ -7,7 +7,7 @@ #include "cmGlobalGenerator.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" -#include "cmQtAutoGeneratorMocUic.h" +#include "cmQtAutoMocUic.h" #include "cmQtAutoRcc.h" #include "cmRange.h" #include "cmState.h" @@ -1018,7 +1018,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) #ifdef CMAKE_BUILD_WITH_CMAKE if ((args[1] == "cmake_autogen") && (args.size() >= 4)) { - cmQtAutoGeneratorMocUic autoGen; + cmQtAutoMocUic autoGen; std::string const& infoDir = args[2]; std::string const& config = args[3]; return autoGen.Run(infoDir, config) ? 0 : 1; diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt index db4ef90..1302c64 100644 --- a/Source/kwsys/CMakeLists.txt +++ b/Source/kwsys/CMakeLists.txt @@ -465,6 +465,14 @@ IF(KWSYS_USE_DynamicLoader) ENDIF() IF(KWSYS_USE_SystemTools) + if (NOT DEFINED KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP) + set(KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP 1) + endif () + if (KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP) + set(KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP 1) + else () + set(KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP 0) + endif () KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_SETENV "Checking whether CXX compiler has setenv" DIRECT) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_UNSETENV diff --git a/Source/kwsys/Configure.hxx.in b/Source/kwsys/Configure.hxx.in index d1e7464..92ffea3 100644 --- a/Source/kwsys/Configure.hxx.in +++ b/Source/kwsys/Configure.hxx.in @@ -11,6 +11,9 @@ /* Whether <ext/stdio_filebuf.h> is available. */ #define @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H \ @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@ +/* Whether the translation map is available or not. */ +#define @KWSYS_NAMESPACE@_SYSTEMTOOLS_USE_TRANSLATION_MAP \ + @KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP@ #if defined(__SUNPRO_CC) && __SUNPRO_CC > 0x5130 && defined(__has_attribute) # define @KWSYS_NAMESPACE@__has_cpp_attribute(x) __has_attribute(x) @@ -56,6 +59,8 @@ @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H # define KWSYS_FALLTHROUGH @KWSYS_NAMESPACE@_FALLTHROUGH # define KWSYS_NULLPTR @KWSYS_NAMESPACE@_NULLPTR +# define KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP \ + @KWSYS_NAMESPACE@_SYSTEMTOOLS_USE_TRANSLATION_MAP #endif #endif diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx index 87da80e..e756cdc 100644 --- a/Source/kwsys/SystemTools.cxx +++ b/Source/kwsys/SystemTools.cxx @@ -453,11 +453,13 @@ class SystemToolsStatic { public: typedef std::map<std::string, std::string> StringMap; +#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP /** * Path translation table from dir to refdir * Each time 'dir' will be found it will be replace by 'refdir' */ StringMap TranslationMap; +#endif #ifdef _WIN32 static std::string GetCasePathName(std::string const& pathIn); static std::string GetActualCaseForPathCached(std::string const& path); @@ -623,7 +625,9 @@ const char* SystemToolsStatic::GetEnvBuffered(const char* key) std::string env; if (SystemTools::GetEnv(key, env)) { std::string& menv = SystemTools::Statics->EnvMap[key]; - menv = std::move(env); + if (menv != env) { + menv = std::move(env); + } return menv.c_str(); } return KWSYS_NULLPTR; @@ -2810,27 +2814,15 @@ std::string SystemToolsStatic::FindName( SystemTools::GetPath(path); } // now add the additional paths - { - for (std::vector<std::string>::const_iterator i = userPaths.begin(); - i != userPaths.end(); ++i) { - path.push_back(*i); - } - } - // Add a trailing slash to all paths to aid the search process. - { - for (std::vector<std::string>::iterator i = path.begin(); i != path.end(); - ++i) { - std::string& p = *i; - if (p.empty() || p.back() != '/') { - p += "/"; - } - } - } + path.reserve(path.size() + userPaths.size()); + path.insert(path.end(), userPaths.begin(), userPaths.end()); // now look for the file std::string tryPath; - for (std::vector<std::string>::const_iterator p = path.begin(); - p != path.end(); ++p) { - tryPath = *p; + for (std::string const& p : path) { + tryPath = p; + if (tryPath.empty() || tryPath.back() != '/') { + tryPath += '/'; + } tryPath += name; if (SystemTools::FileExists(tryPath)) { return tryPath; @@ -2904,14 +2896,13 @@ std::string SystemTools::FindProgram(const std::string& name, // the end of it // on windows try .com then .exe if (name.size() <= 3 || name[name.size() - 4] != '.') { - extensions.push_back(".com"); - extensions.push_back(".exe"); + extensions.emplace_back(".com"); + extensions.emplace_back(".exe"); // first try with extensions if the os supports them - for (std::vector<std::string>::iterator i = extensions.begin(); - i != extensions.end(); ++i) { + for (std::string const& ext : extensions) { tryPath = name; - tryPath += *i; + tryPath += ext; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } @@ -2930,43 +2921,33 @@ std::string SystemTools::FindProgram(const std::string& name, SystemTools::GetPath(path); } // now add the additional paths - { - for (std::vector<std::string>::const_iterator i = userPaths.begin(); - i != userPaths.end(); ++i) { - path.push_back(*i); - } - } + path.reserve(path.size() + userPaths.size()); + path.insert(path.end(), userPaths.begin(), userPaths.end()); // Add a trailing slash to all paths to aid the search process. - { - for (std::vector<std::string>::iterator i = path.begin(); i != path.end(); - ++i) { - std::string& p = *i; - if (p.empty() || p.back() != '/') { - p += "/"; - } + for (std::string& p : path) { + if (p.empty() || p.back() != '/') { + p += '/'; } } // Try each path - for (std::vector<std::string>::iterator p = path.begin(); p != path.end(); - ++p) { + for (std::string& p : path) { #ifdef _WIN32 // Remove double quotes from the path on windows - SystemTools::ReplaceString(*p, "\"", ""); + SystemTools::ReplaceString(p, "\"", ""); #endif #if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) // first try with extensions - for (std::vector<std::string>::iterator ext = extensions.begin(); - ext != extensions.end(); ++ext) { - tryPath = *p; + for (std::string const& ext : extensions) { + tryPath = p; tryPath += name; - tryPath += *ext; + tryPath += ext; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } } #endif // now try it without them - tryPath = *p; + tryPath = p; tryPath += name; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); @@ -2980,10 +2961,9 @@ std::string SystemTools::FindProgram(const std::vector<std::string>& names, const std::vector<std::string>& path, bool noSystemPath) { - for (std::vector<std::string>::const_iterator it = names.begin(); - it != names.end(); ++it) { + for (std::string const& name : names) { // Try to find the program. - std::string result = SystemTools::FindProgram(*it, path, noSystemPath); + std::string result = SystemTools::FindProgram(name, path, noSystemPath); if (!result.empty()) { return result; } @@ -3008,27 +2988,18 @@ std::string SystemTools::FindLibrary(const std::string& name, std::vector<std::string> path; SystemTools::GetPath(path); // now add the additional paths - { - for (std::vector<std::string>::const_iterator i = userPaths.begin(); - i != userPaths.end(); ++i) { - path.push_back(*i); - } - } + path.reserve(path.size() + userPaths.size()); + path.insert(path.end(), userPaths.begin(), userPaths.end()); // Add a trailing slash to all paths to aid the search process. - { - for (std::vector<std::string>::iterator i = path.begin(); i != path.end(); - ++i) { - std::string& p = *i; - if (p.empty() || p.back() != '/') { - p += "/"; - } + for (std::string& p : path) { + if (p.empty() || p.back() != '/') { + p += '/'; } } std::string tryPath; - for (std::vector<std::string>::const_iterator p = path.begin(); - p != path.end(); ++p) { + for (std::string const& p : path) { #if defined(__APPLE__) - tryPath = *p; + tryPath = p; tryPath += name; tryPath += ".framework"; if (SystemTools::FileIsDirectory(tryPath)) { @@ -3036,42 +3007,42 @@ std::string SystemTools::FindLibrary(const std::string& name, } #endif #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__) - tryPath = *p; + tryPath = p; tryPath += name; tryPath += ".lib"; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } #else - tryPath = *p; + tryPath = p; tryPath += "lib"; tryPath += name; tryPath += ".so"; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } - tryPath = *p; + tryPath = p; tryPath += "lib"; tryPath += name; tryPath += ".a"; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } - tryPath = *p; + tryPath = p; tryPath += "lib"; tryPath += name; tryPath += ".sl"; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } - tryPath = *p; + tryPath = p; tryPath += "lib"; tryPath += name; tryPath += ".dylib"; if (SystemTools::FileExists(tryPath, true)) { return SystemTools::CollapseFullPath(tryPath); } - tryPath = *p; + tryPath = p; tryPath += "lib"; tryPath += name; tryPath += ".dll"; @@ -3333,9 +3304,8 @@ bool SystemTools::FindProgramPath(const char* argv0, std::string& pathOut, msg << " argv[0] = \"" << argv0 << "\"\n"; } msg << " Attempted paths:\n"; - std::vector<std::string>::iterator i; - for (i = failures.begin(); i != failures.end(); ++i) { - msg << " \"" << *i << "\"\n"; + for (std::string const& ff : failures) { + msg << " \"" << ff << "\"\n"; } errorMsg = msg.str(); return false; @@ -3349,6 +3319,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_relative) return SystemTools::CollapseFullPath(in_relative, KWSYS_NULLPTR); } +#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP void SystemTools::AddTranslationPath(const std::string& a, const std::string& b) { @@ -3412,6 +3383,7 @@ void SystemTools::CheckTranslationPath(std::string& path) // Remove the trailing slash we added before. path.pop_back(); } +#endif static void SystemToolsAppendComponents( std::vector<std::string>& out_components, @@ -3482,6 +3454,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path, // Transform the path back to a string. std::string newPath = SystemTools::JoinPath(out_components); +#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP // Update the translation table with this potentially new path. I am not // sure why this line is here, it seems really questionable, but yet I // would put good money that if I remove it something will break, basically @@ -3497,6 +3470,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path, // SystemTools::AddTranslationPath(newPath, in_path); SystemTools::CheckTranslationPath(newPath); +#endif #ifdef _WIN32 newPath = SystemTools::Statics->GetActualCaseForPathCached(newPath); SystemTools::ConvertToUnixSlashes(newPath); @@ -3558,28 +3532,26 @@ std::string SystemTools::RelativePath(const std::string& local, // for each entry that is not common in the local path // add a ../ to the finalpath array, this gets us out of the local // path into the remote dir - for (unsigned int i = 0; i < localSplit.size(); ++i) { - if (!localSplit[i].empty()) { - finalPath.push_back("../"); + for (std::string const& lp : localSplit) { + if (!lp.empty()) { + finalPath.emplace_back("../"); } } // for each entry that is not common in the remote path add it // to the final path. - for (std::vector<std::string>::iterator vit = remoteSplit.begin(); - vit != remoteSplit.end(); ++vit) { - if (!vit->empty()) { - finalPath.push_back(*vit); + for (std::string const& rp : remoteSplit) { + if (!rp.empty()) { + finalPath.push_back(rp); } } std::string relativePath; // result string // now turn the array of directories into a unix path by puttint / // between each entry that does not already have one - for (std::vector<std::string>::iterator vit1 = finalPath.begin(); - vit1 != finalPath.end(); ++vit1) { + for (std::string const& fp : finalPath) { if (!relativePath.empty() && relativePath.back() != '/') { - relativePath += "/"; + relativePath += '/'; } - relativePath += *vit1; + relativePath += fp; } return relativePath; } @@ -3727,8 +3699,7 @@ std::string SystemTools::JoinPath( // Construct result in a single string. std::string result; size_t len = 0; - std::vector<std::string>::const_iterator i; - for (i = first; i != last; ++i) { + for (std::vector<std::string>::const_iterator i = first; i != last; ++i) { len += 1 + i->size(); } result.reserve(len); @@ -4737,10 +4708,11 @@ void SystemTools::ClassInitialize() // Create statics singleton instance SystemTools::Statics = new SystemToolsStatic; +#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP // Add some special translation paths for unix. These are not added // for windows because drive letters need to be maintained. Also, // there are not sym-links and mount points on windows anyway. -#if !defined(_WIN32) || defined(__CYGWIN__) +# if !defined(_WIN32) || defined(__CYGWIN__) // The tmp path is frequently a logical path so always keep it: SystemTools::AddKeepPath("/tmp/"); @@ -4778,6 +4750,7 @@ void SystemTools::ClassInitialize() } } } +# endif #endif } diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in index cdc9483..dd1266b 100644 --- a/Source/kwsys/SystemTools.hxx.in +++ b/Source/kwsys/SystemTools.hxx.in @@ -891,6 +891,7 @@ public: */ static int GetTerminalWidth(); +#if @KWSYS_NAMESPACE@_SYSTEMTOOLS_USE_TRANSLATION_MAP /** * Add an entry in the path translation table. */ @@ -907,6 +908,7 @@ public: * Update path by going through the Path Translation table; */ static void CheckTranslationPath(std::string& path); +#endif /** * Delay the execution for a specified amount of time specified diff --git a/Tests/CMakeCommands/target_link_libraries/CMakeLists.txt b/Tests/CMakeCommands/target_link_libraries/CMakeLists.txt index 85ce1f7..5c704ac 100644 --- a/Tests/CMakeCommands/target_link_libraries/CMakeLists.txt +++ b/Tests/CMakeCommands/target_link_libraries/CMakeLists.txt @@ -134,11 +134,15 @@ assert_property(newsignature1 LINK_LIBRARIES "depC;depB;subdirlib") #---------------------------------------------------------------------------- # Test cross-directory linking. cmake_policy(PUSH) +cmake_policy(SET CMP0022 NEW) cmake_policy(SET CMP0079 NEW) add_executable(TopDir TopDir.c) add_subdirectory(SubDirA) add_subdirectory(SubDirB) target_link_libraries(SubDirB TopDirImported) +add_subdirectory(SubDirC) +target_link_libraries(SubDirC PRIVATE SubDirC2) +target_link_libraries(TopDir SubDirC) add_library(TopDirImported IMPORTED INTERFACE) target_compile_definitions(TopDirImported INTERFACE DEF_TopDirImported) cmake_policy(POP) diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt b/Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt new file mode 100644 index 0000000..54bcc51 --- /dev/null +++ b/Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt @@ -0,0 +1,9 @@ +add_library(SubDirC STATIC SubDirC.c) + +add_library(SubDirC1 INTERFACE) +target_compile_definitions(SubDirC1 INTERFACE DEF_SubDirC1) + +add_library(SubDirC2 INTERFACE) +target_compile_definitions(SubDirC2 INTERFACE DEF_SubDirC2) + +target_link_libraries(SubDirC PRIVATE SubDirC1) diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c b/Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c new file mode 100644 index 0000000..c5536dc --- /dev/null +++ b/Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c @@ -0,0 +1,11 @@ +#ifndef DEF_SubDirC1 +# error "DEF_SubDirC1 not defined" +#endif +#ifndef DEF_SubDirC2 +# error "DEF_SubDirC2 not defined" +#endif + +int SubDirC(void) +{ + return 0; +} diff --git a/Tests/CMakeCommands/target_link_libraries/TopDir.c b/Tests/CMakeCommands/target_link_libraries/TopDir.c index 4706bb9..d8066e5 100644 --- a/Tests/CMakeCommands/target_link_libraries/TopDir.c +++ b/Tests/CMakeCommands/target_link_libraries/TopDir.c @@ -7,6 +7,12 @@ #ifdef DEF_TopDirImported # error "DEF_TopDirImported is defined but should not be!" #endif +#ifdef DEF_SubDirC1 +# error "DEF_SubDirC1 defined but should not be" +#endif +#ifdef DEF_SubDirC2 +# error "DEF_SubDirC2 defined but should not be" +#endif int main(void) { diff --git a/Tests/CMakeLib/CMakeLists.txt b/Tests/CMakeLib/CMakeLists.txt index 031ab01..e04bba2 100644 --- a/Tests/CMakeLib/CMakeLists.txt +++ b/Tests/CMakeLib/CMakeLists.txt @@ -16,9 +16,11 @@ set(CMakeLib_TESTS testXMLSafe.cxx testFindPackageCommand.cxx testUVRAII.cxx + testUVStreambuf.cxx ) set(testRST_ARGS ${CMAKE_CURRENT_SOURCE_DIR}) +set(testUVStreambuf_ARGS $<TARGET_FILE:cmake>) if(WIN32) list(APPEND CMakeLib_TESTS @@ -43,7 +45,7 @@ target_link_libraries(testEncoding cmsys) foreach(testfile ${CMakeLib_TESTS}) get_filename_component(test "${testfile}" NAME_WE) - add_test(CMakeLib.${test} CMakeLibTests ${test} ${${test}_ARGS}) + add_test(NAME CMakeLib.${test} COMMAND CMakeLibTests ${test} ${${test}_ARGS}) endforeach() if(TEST_CompileCommandOutput) diff --git a/Tests/CMakeLib/testUVRAII.cxx b/Tests/CMakeLib/testUVRAII.cxx index 1c1da76..2aeaf2c 100644 --- a/Tests/CMakeLib/testUVRAII.cxx +++ b/Tests/CMakeLib/testUVRAII.cxx @@ -171,11 +171,59 @@ static bool testAllMoves() return true; }; +static bool testLoopReset() +{ + bool closed = false; + cm::uv_loop_ptr loop; + loop.init(); + + uv_timer_t timer; + uv_timer_init(loop, &timer); + timer.data = &closed; + uv_close(reinterpret_cast<uv_handle_t*>(&timer), [](uv_handle_t* handle) { + auto closedPtr = static_cast<bool*>(handle->data); + *closedPtr = true; + }); + + loop.reset(); + if (!closed) { + std::cerr << "uv_loop_ptr did not finish" << std::endl; + return false; + } + + return true; +}; + +static bool testLoopDestructor() +{ + bool closed = false; + + uv_timer_t timer; + { + cm::uv_loop_ptr loop; + loop.init(); + + uv_timer_init(loop, &timer); + timer.data = &closed; + uv_close(reinterpret_cast<uv_handle_t*>(&timer), [](uv_handle_t* handle) { + auto closedPtr = static_cast<bool*>(handle->data); + *closedPtr = true; + }); + } + + if (!closed) { + std::cerr << "uv_loop_ptr did not finish" << std::endl; + return false; + } + + return true; +}; + int testUVRAII(int, char** const) { if ((testAsyncShutdown() && testAsyncDtor() & testAsyncMove() & testCrossAssignment() & - testAllMoves()) == 0) { + testAllMoves() & testLoopReset() & testLoopDestructor()) == 0) { return -1; } return 0; diff --git a/Tests/CMakeLib/testUVStreambuf.cxx b/Tests/CMakeLib/testUVStreambuf.cxx new file mode 100644 index 0000000..39655f3 --- /dev/null +++ b/Tests/CMakeLib/testUVStreambuf.cxx @@ -0,0 +1,457 @@ +#include "cmUVStreambuf.h" + +#include "cmGetPipes.h" +#include "cmUVHandlePtr.h" + +#include "cm_uv.h" + +#include <iostream> +#include <string> +#include <vector> + +#include <cstring> + +#include <stdint.h> + +#define TEST_STR_LINE_1 "This string must be exactly 128 characters long so" +#define TEST_STR_LINE_2 "that we can test CMake's std::streambuf integration" +#define TEST_STR_LINE_3 "with libuv's uv_stream_t." +#define TEST_STR TEST_STR_LINE_1 "\n" TEST_STR_LINE_2 "\n" TEST_STR_LINE_3 + +bool writeDataToStreamPipe(uv_loop_t& loop, cm::uv_pipe_ptr& inputPipe, + char* outputData, unsigned int outputDataLength, + const char* /* unused */) +{ + int err; + + // Create the pipe + int pipeHandles[2]; + if (cmGetPipes(pipeHandles) < 0) { + std::cout << "Could not open pipe" << std::endl; + return false; + } + + cm::uv_pipe_ptr outputPipe; + inputPipe.init(loop, 0); + outputPipe.init(loop, 0); + uv_pipe_open(inputPipe, pipeHandles[0]); + uv_pipe_open(outputPipe, pipeHandles[1]); + + // Write data for reading + uv_write_t writeReq; + struct WriteCallbackData + { + bool Finished = false; + int Status; + } writeData; + writeReq.data = &writeData; + uv_buf_t outputBuf; + outputBuf.base = outputData; + outputBuf.len = outputDataLength; + if ((err = uv_write(&writeReq, outputPipe, &outputBuf, 1, + [](uv_write_t* req, int status) { + auto data = static_cast<WriteCallbackData*>(req->data); + data->Finished = true; + data->Status = status; + })) < 0) { + std::cout << "Could not write to pipe: " << uv_strerror(err) << std::endl; + return false; + } + while (!writeData.Finished) { + uv_run(&loop, UV_RUN_ONCE); + } + if (writeData.Status < 0) { + std::cout << "Status is " << uv_strerror(writeData.Status) + << ", should be 0" << std::endl; + return false; + } + + return true; +} + +bool writeDataToStreamProcess(uv_loop_t& loop, cm::uv_pipe_ptr& inputPipe, + char* outputData, unsigned int /* unused */, + const char* cmakeCommand) +{ + int err; + + inputPipe.init(loop, 0); + std::vector<std::string> arguments = { cmakeCommand, "-E", "echo_append", + outputData }; + std::vector<const char*> processArgs; + for (auto const& arg : arguments) { + processArgs.push_back(arg.c_str()); + } + processArgs.push_back(nullptr); + std::vector<uv_stdio_container_t> stdio(3); + stdio[0].flags = UV_IGNORE; + stdio[0].data.stream = nullptr; + stdio[1].flags = + static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); + stdio[1].data.stream = inputPipe; + stdio[2].flags = UV_IGNORE; + stdio[2].data.stream = nullptr; + + struct ProcessExitData + { + bool Finished = false; + int64_t ExitStatus; + int TermSignal; + } exitData; + cm::uv_process_ptr process; + auto options = uv_process_options_t(); + options.file = cmakeCommand; + options.args = const_cast<char**>(processArgs.data()); + options.flags = UV_PROCESS_WINDOWS_HIDE; + options.stdio = stdio.data(); + options.stdio_count = static_cast<int>(stdio.size()); + options.exit_cb = [](uv_process_t* handle, int64_t exitStatus, + int termSignal) { + auto data = static_cast<ProcessExitData*>(handle->data); + data->Finished = true; + data->ExitStatus = exitStatus; + data->TermSignal = termSignal; + }; + if ((err = process.spawn(loop, options, &exitData)) < 0) { + std::cout << "Could not spawn process: " << uv_strerror(err) << std::endl; + return false; + } + while (!exitData.Finished) { + uv_run(&loop, UV_RUN_ONCE); + } + if (exitData.ExitStatus != 0) { + std::cout << "Process exit status is " << exitData.ExitStatus + << ", should be 0" << std::endl; + return false; + } + if (exitData.TermSignal != 0) { + std::cout << "Process term signal is " << exitData.TermSignal + << ", should be 0" << std::endl; + return false; + } + + return true; +} + +bool testUVStreambufRead( + bool (*cb)(uv_loop_t& loop, cm::uv_pipe_ptr& inputPipe, char* outputData, + unsigned int outputDataLength, const char* cmakeCommand), + const char* cmakeCommand) +{ + char outputData[] = TEST_STR; + bool success = false; + cm::uv_loop_ptr loop; + loop.init(); + cm::uv_pipe_ptr inputPipe; + std::vector<char> inputData(128); + std::streamsize readLen; + std::string line; + cm::uv_timer_ptr timer; + + // Create the streambuf + cmUVStreambuf inputBuf(64); + std::istream inputStream(&inputBuf); + if (inputBuf.is_open()) { + std::cout << "is_open() is true, should be false" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + + // Perform first read test - read all the data + if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) { + goto end; + } + inputBuf.open(inputPipe); + if (!inputBuf.is_open()) { + std::cout << "is_open() is false, should be true" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 128) { + std::cout << "sgetn() returned " << readLen << ", should be 128" + << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if (std::memcmp(inputData.data(), outputData, 128)) { + std::cout << "Read data does not match write data" << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + inputData.assign(128, char{}); + inputBuf.close(); + if (inputBuf.is_open()) { + std::cout << "is_open() is true, should be false" << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + + // Perform second read test - read some data and then close + if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) { + goto end; + } + inputBuf.open(inputPipe); + if (!inputBuf.is_open()) { + std::cout << "is_open() is false, should be true" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 64)) != 64) { + std::cout << "sgetn() returned " << readLen << ", should be 64" + << std::endl; + goto end; + } + if (std::memcmp(inputData.data(), outputData, 64)) { + std::cout << "Read data does not match write data" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 8) { + std::cout << "in_avail() returned " << readLen << ", should be 8" + << std::endl; + goto end; + } + inputData.assign(128, char{}); + inputBuf.close(); + if (inputBuf.is_open()) { + std::cout << "is_open() is true, should be false" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + + // Perform third read test - read line by line + if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) { + goto end; + } + inputBuf.open(inputPipe); + if (!inputBuf.is_open()) { + std::cout << "is_open() is false, should be true" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + + if (!std::getline(inputStream, line)) { + std::cout << "getline returned false, should be true" << std::endl; + goto end; + } + if (line != TEST_STR_LINE_1) { + std::cout << "Line 1 is \"" << line + << "\", should be \"" TEST_STR_LINE_1 "\"" << std::endl; + goto end; + } + + if (!std::getline(inputStream, line)) { + std::cout << "getline returned false, should be true" << std::endl; + goto end; + } + if (line != TEST_STR_LINE_2) { + std::cout << "Line 2 is \"" << line + << "\", should be \"" TEST_STR_LINE_2 "\"" << std::endl; + goto end; + } + + if (!std::getline(inputStream, line)) { + std::cout << "getline returned false, should be true" << std::endl; + goto end; + } + if (line != TEST_STR_LINE_3) { + std::cout << "Line 3 is \"" << line + << "\", should be \"" TEST_STR_LINE_3 "\"" << std::endl; + goto end; + } + + if (std::getline(inputStream, line)) { + std::cout << "getline returned true, should be false" << std::endl; + goto end; + } + + inputBuf.close(); + if (inputBuf.is_open()) { + std::cout << "is_open() is true, should be false" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + + // Perform fourth read test - run the event loop outside of underflow() + if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) { + goto end; + } + inputBuf.open(inputPipe); + if (!inputBuf.is_open()) { + std::cout << "is_open() is false, should be true" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + uv_run(loop, UV_RUN_DEFAULT); + if ((readLen = inputBuf.in_avail()) != 72) { + std::cout << "in_avail() returned " << readLen << ", should be 72" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 128) { + std::cout << "sgetn() returned " << readLen << ", should be 128" + << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 128" + << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + + inputBuf.close(); + if (inputBuf.is_open()) { + std::cout << "is_open() is true, should be false" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + + // Perform fifth read test - close the streambuf in the middle of a read + timer.init(*loop, &inputBuf); + if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) { + goto end; + } + inputBuf.open(inputPipe); + if (!inputBuf.is_open()) { + std::cout << "is_open() is false, should be true" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != 0) { + std::cout << "in_avail() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + uv_timer_start(timer, + [](uv_timer_t* handle) { + auto buf = static_cast<cmUVStreambuf*>(handle->data); + buf->close(); + }, + 0, 0); + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + if (inputBuf.is_open()) { + std::cout << "is_open() is true, should be false" << std::endl; + goto end; + } + if ((readLen = inputBuf.in_avail()) != -1) { + std::cout << "in_avail() returned " << readLen << ", should be -1" + << std::endl; + goto end; + } + if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) { + std::cout << "sgetn() returned " << readLen << ", should be 0" + << std::endl; + goto end; + } + + success = true; + +end: + return success; +} + +int testUVStreambuf(int argc, char** const argv) +{ + if (argc < 2) { + std::cout << "Invalid arguments.\n"; + return -1; + } + + if (!testUVStreambufRead(writeDataToStreamPipe, argv[1])) { + std::cout << "While executing testUVStreambufRead() with pipe.\n"; + return -1; + } + + if (!testUVStreambufRead(writeDataToStreamProcess, argv[1])) { + std::cout << "While executing testUVStreambufRead() with process.\n"; + return -1; + } + + return 0; +} diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 3746965..bc4812b 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -1995,6 +1995,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release if(NOT CMAKE_C_COMPILER_ID STREQUAL "Clang") ADD_TEST_MACRO(PrecompiledHeader foo) endif() + ADD_TEST_MACRO(MSVCRuntimeLibrary) + if(CMAKE_Fortran_COMPILER) + ADD_TEST_MACRO(MSVCRuntimeLibrary.Fortran) + endif() endif() if(MSVC OR "${CMAKE_GENERATOR}" MATCHES "(MSYS|MinGW) Makefiles") @@ -2336,7 +2340,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release endmacro() macro(add_test_GhsMulti_rename_install test_name) add_test_GhsMulti( ${test_name} GhsMultiRenameInstall ${test_name} - "-DCMAKE_INSTALL_PREFIX=. -DRUN_TEST=${test_name}" ${CMAKE_CMAKE_COMMAND} -P ./cmake_install.cmake) + "-DCMAKE_INSTALL_PREFIX=. -DRUN_TEST=${test_name}" ${CMAKE_CMAKE_COMMAND} --build . --target install) endmacro() #unset ghs config variables unset(ghs_config_name) @@ -2391,6 +2395,9 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_test_GhsMulti(compiler_options_kernel GhsMultiCompilerOptions Kernel "-DRUN_TEST=KERNEL_FLAGS -DRUN_TEST_BUILD_TYPE=DEBUG") add_test_GhsMulti(try_compile_copy GhsMultiCopyFile "" "") add_test_GhsMulti(ghs_platform GhsMultiPlatform "" "") + add_test_GhsMulti(custom_target GhsMultiCustomTarget "" "") + add_test_GhsMulti(dep_order GhsMultiDepOrder "" "") + add_test_GhsMulti(external_project GhsMultiExternalProject "" "") list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/GhsMulti/${ghs_config_name}") #unset ghs config variables unset(ghs_config_name) diff --git a/Tests/CompileFeatures/CMakeLists.txt b/Tests/CompileFeatures/CMakeLists.txt index 2dd8917..060fb49 100644 --- a/Tests/CompileFeatures/CMakeLists.txt +++ b/Tests/CompileFeatures/CMakeLists.txt @@ -52,6 +52,16 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang" endif() if (CMAKE_CXX_COMPILER_ID STREQUAL SunPro) + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.15) + # SunPro 5.14 accepts -std=c++14 and compiles two features but does + # not define __cplusplus to a value different than with -std=c++11. + list(REMOVE_ITEM CXX_non_features + cxx_aggregate_default_initializers + cxx_digit_separators + ) + endif() + + # FIXME: Do any of these work correctly on SunPro 5.13 or above? list(REMOVE_ITEM CXX_non_features cxx_attribute_deprecated cxx_contextual_conversions diff --git a/Tests/FindBoost/CMakeLists.txt b/Tests/FindBoost/CMakeLists.txt index 17a8ec7..58d795b 100644 --- a/Tests/FindBoost/CMakeLists.txt +++ b/Tests/FindBoost/CMakeLists.txt @@ -33,3 +33,16 @@ add_test(NAME FindBoost.TestHeaders COMMAND --build-options ${build_options} --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> ) + +if (CMake_TEST_FindBoost_Python) + add_test(NAME FindBoost.TestPython COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindBoost/TestPython" + "${CMake_BINARY_DIR}/Tests/FindBoost/TestPython" + ${build_generator_args} + --build-project TestFindBoostPython + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) +endif () diff --git a/Tests/FindBoost/TestPython/CMakeLists.txt b/Tests/FindBoost/TestPython/CMakeLists.txt new file mode 100644 index 0000000..4d137ca --- /dev/null +++ b/Tests/FindBoost/TestPython/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.14) +project(TestFindBoostPython CXX) +include(CTest) + +find_package(Boost OPTIONAL_COMPONENTS python27 python34 python35 python36 python37) + +set(FAILTEST TRUE) +foreach (v IN ITEMS 27 34 35 36 37) + if (Boost_PYTHON${v}_FOUND) + set(FAILTEST FALSE) + break() + endif () +endforeach () + +if (FAILTEST) + message(FATAL_ERROR "No Boost Python module found") +endif () diff --git a/Tests/FindPackageTest/.gitignore b/Tests/FindPackageTest/.gitignore new file mode 100644 index 0000000..3aaef13 --- /dev/null +++ b/Tests/FindPackageTest/.gitignore @@ -0,0 +1 @@ +/symlink diff --git a/Tests/FindPackageTest/CMakeLists.txt b/Tests/FindPackageTest/CMakeLists.txt index 972580c..6c876a7 100644 --- a/Tests/FindPackageTest/CMakeLists.txt +++ b/Tests/FindPackageTest/CMakeLists.txt @@ -205,15 +205,20 @@ if(UNIX) message(SEND_ERROR "SetFoundResolved_DIR set by find_package() is set to \"${SetFoundResolved_DIR}\" (expected \"${SetFoundResolved_EXPECTED}\")") endif() - # Resolve symlinks when finding the package. - set(CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS TRUE) - set(SetFoundResolved_DIR "") - find_package(SetFoundResolved) - # ./symlink points back here so it should be gone when resolved. - set(SetFoundResolved_EXPECTED "${CMAKE_CURRENT_SOURCE_DIR}/cmake") - if(NOT "${SetFoundResolved_DIR}" STREQUAL "${SetFoundResolved_EXPECTED}") - message(SEND_ERROR "SetFoundResolved_DIR set by find_package() is set to \"${SetFoundResolved_DIR}\" (expected \"${SetFoundResolved_EXPECTED}\")") + # This part of the test only works if there are no symlinks in our path. + get_filename_component(real_src_dir "${CMAKE_CURRENT_SOURCE_DIR}" REALPATH) + if(real_src_dir STREQUAL CMAKE_CURRENT_SOURCE_DIR) + # Resolve symlinks when finding the package. + set(CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS TRUE) + set(SetFoundResolved_DIR "") + find_package(SetFoundResolved) + # ./symlink points back here so it should be gone when resolved. + set(SetFoundResolved_EXPECTED "${CMAKE_CURRENT_SOURCE_DIR}/cmake") + if(NOT "${SetFoundResolved_DIR}" STREQUAL "${SetFoundResolved_EXPECTED}") + message(SEND_ERROR "SetFoundResolved_DIR set by find_package() is set to \"${SetFoundResolved_DIR}\" (expected \"${SetFoundResolved_EXPECTED}\")") + endif() endif() + # Cleanup. unset(CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS) file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/symlink") diff --git a/Tests/GeneratorExpression/CMakeLists.txt b/Tests/GeneratorExpression/CMakeLists.txt index df0c78d..5ba0dc0 100644 --- a/Tests/GeneratorExpression/CMakeLists.txt +++ b/Tests/GeneratorExpression/CMakeLists.txt @@ -374,4 +374,49 @@ if(NOT CMAKE_GENERATOR STREQUAL Xcode OR NOT CMAKE_OSX_ARCHITECTURES MATCHES "[; -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" DEPENDS objlib ) + + + add_library(sharedlib SHARED objlib1.c objlib2.c) + file(GENERATE + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/sharedlib_files_$<CONFIGURATION>" + CONTENT "$<JOIN:$<TARGET_OBJECTS:sharedlib>,\n>\n" + ) + + add_custom_target(check_sharedlib_objs ALL + COMMAND ${CMAKE_COMMAND} + "-DOBJLIB_LISTFILE=${CMAKE_CURRENT_BINARY_DIR}/sharedlib_files_$<CONFIGURATION>" + -DEXPECTED_NUM_OBJECTFILES=2 + -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" + DEPENDS sharedlib + ) + + + add_library(staticlib STATIC objlib1.c objlib2.c) + file(GENERATE + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/staticlib_files_$<CONFIGURATION>" + CONTENT "$<JOIN:$<TARGET_OBJECTS:staticlib>,\n>\n" + ) + + add_custom_target(check_staticlib_objs ALL + COMMAND ${CMAKE_COMMAND} + "-DOBJLIB_LISTFILE=${CMAKE_CURRENT_BINARY_DIR}/staticlib_files_$<CONFIGURATION>" + -DEXPECTED_NUM_OBJECTFILES=2 + -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" + DEPENDS staticlib + ) + + + add_executable(execobjs objlib1.c objlib2.c echo.c) + file(GENERATE + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/execobjs_files_$<CONFIGURATION>" + CONTENT "$<JOIN:$<TARGET_OBJECTS:execobjs>,\n>\n" + ) + + add_custom_target(check_exec_objs ALL + COMMAND ${CMAKE_COMMAND} + "-DOBJLIB_LISTFILE=${CMAKE_CURRENT_BINARY_DIR}/execobjs_files_$<CONFIGURATION>" + -DEXPECTED_NUM_OBJECTFILES=3 + -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" + DEPENDS execobjs + ) endif() diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt new file mode 100644 index 0000000..93d668b --- /dev/null +++ b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt @@ -0,0 +1,110 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +project(test C) + +# Tests assume no previous builds in the build directory +file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/build) + +macro (test_output) + if (BUILD_OUTPUT STREQUAL EXPECTED_LINES ) + message("Build OK") + else() + message("BUILD_OUTPUT") + foreach(Line IN LISTS BUILD_OUTPUT) + message("${Line}") + endforeach() + message("EXPECTED_LINES") + foreach(Line IN LISTS EXPECTED_LINES) + message("${Line}") + endforeach() + message(SEND_ERROR "Build KO") + endif() +endmacro() + +message("Copy project") +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt.in + ${CMAKE_CURRENT_BINARY_DIR}/src/CMakeLists.txt COPYONLY) + +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/exe1.c + ${CMAKE_CURRENT_SOURCE_DIR}/lib1.c + DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/src +) + +message("Building ALL target") +try_compile(RESULT + ${CMAKE_CURRENT_BINARY_DIR}/build + ${CMAKE_CURRENT_BINARY_DIR}/src + test + CMAKE_FLAGS + -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS} + OUTPUT_VARIABLE BUILD_OUTPUT) + +message("Output from build:\n${BUILD_OUTPUT}") + +#filter outputs +string(REPLACE "\r" "" BUILD_OUTPUT "${BUILD_OUTPUT}") +string(REPLACE "\n" ";" BUILD_OUTPUT "${BUILD_OUTPUT}") +list(FILTER BUILD_OUTPUT INCLUDE REGEX "^.*CT:") + +unset(EXPECTED_LINES) +list(APPEND EXPECTED_LINES "CT: Processing target_empty_prebuild") +list(APPEND EXPECTED_LINES "CT: Processing target_empty_postbuild") +list(APPEND EXPECTED_LINES "CT: Processing target_cmd") +list(APPEND EXPECTED_LINES "CT: Processing target_cmd_prebuild") +list(APPEND EXPECTED_LINES "CT: Processing target_cmd_postbuild") + +test_output() + +message("Building target_update_files target") +try_compile(RESULT + ${CMAKE_CURRENT_BINARY_DIR}/build + ${CMAKE_CURRENT_BINARY_DIR}/src + test target_update_files + CMAKE_FLAGS + -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS} + OUTPUT_VARIABLE BUILD_OUTPUT) + +message("Output from build:\n${BUILD_OUTPUT}") + +#filter outputs +string(REPLACE "\r" "" BUILD_OUTPUT "${BUILD_OUTPUT}") +string(REPLACE "\n" ";" BUILD_OUTPUT "${BUILD_OUTPUT}") +list(FILTER BUILD_OUTPUT INCLUDE REGEX "^.*CT:") + +unset(EXPECTED_LINES) +list(APPEND EXPECTED_LINES "CT: Processing target_empty_prebuild") +list(APPEND EXPECTED_LINES "CT: Processing target_empty_postbuild") +list(APPEND EXPECTED_LINES "CT: generate C file another_file") +list(APPEND EXPECTED_LINES "CT: generate text file dependsA") +list(APPEND EXPECTED_LINES "CT: generate text file out_of_order_dep") +list(APPEND EXPECTED_LINES "CT: generate text files A, B, and C") +list(APPEND EXPECTED_LINES "CT: Processing target_update_files") + +test_output() + +message("Rerun target_update_files target") +try_compile(RESULT + ${CMAKE_CURRENT_BINARY_DIR}/build + ${CMAKE_CURRENT_BINARY_DIR}/src + test target_update_files + CMAKE_FLAGS + -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS} + OUTPUT_VARIABLE BUILD_OUTPUT) + +message("Output from build:\n${BUILD_OUTPUT}") + +#filter outputs +string(REPLACE "\r" "" BUILD_OUTPUT "${BUILD_OUTPUT}") +string(REPLACE "\n" ";" BUILD_OUTPUT "${BUILD_OUTPUT}") +list(FILTER BUILD_OUTPUT INCLUDE REGEX "^.*CT:") + +unset(EXPECTED_LINES) +list(APPEND EXPECTED_LINES "CT: Processing target_empty_prebuild") +list(APPEND EXPECTED_LINES "CT: Processing target_empty_postbuild") +list(APPEND EXPECTED_LINES "CT: generate text files A, B, and C") +list(APPEND EXPECTED_LINES "CT: Processing target_update_files") + +test_output() diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in new file mode 100644 index 0000000..fed946c --- /dev/null +++ b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in @@ -0,0 +1,108 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +project(test C) + +if(CMAKE_C_COMPILER_ID STREQUAL "GHS") + add_link_options("-non_shared") +endif() + +add_library(lib1 lib1.c) + +set(TEST_MISSING_TARGET_SRC 0) +set(TEST_MISSING_TARGET_DEP 0) +set(TEST_MISSING_DEP 0) +set(TEST_DEP_CYCLE 0) + +add_executable(exe1 exe1.c) +target_link_libraries(exe1 lib1) + +add_custom_target(target_cmd ALL + COMMAND ${CMAKE_COMMAND} -E echo "target_cmd" > target_cmd + COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_extra" > target_cmd_extra.txt + BYPRODUCTS target_cmd target_cmd_extra.txt + COMMENT "CT: Processing target_cmd") + +add_custom_command(TARGET target_cmd PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_prebuild" > target_cmd_prebuild.txt + BYPRODUCTS target_cmd_prebuild.txt + COMMENT "CT: Processing target_cmd_prebuild") +#event does not run for custom targets +add_custom_command(TARGET target_cmd PRE_LINK + COMMAND ${CMAKE_COMMAND} -E echo "executing target_cmd_prelink commands" + COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_prelink" > target_cmd_prelink.txt + BYPRODUCTS target_cmd_prelink.txt + COMMENT "CT: Processing target_cmd_prelink") +add_custom_command(TARGET target_cmd POST_BUILD + COMMAND ${CMAKE_COMMAND} -E echo "executing target_cmd_postbuild commands" + COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_postbuild" > target_cmd_postbuild.txt + BYPRODUCTS target_cmd_postbuild.txt + COMMENT "CT: Processing target_cmd_postbuild") + +add_custom_target(target_empty ALL + COMMENT "CT: Processing target_empty") + +add_custom_command(TARGET target_empty PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E echo "target_empty_prebuild" > target_empty_prebuild.txt + BYPRODUCTS target_empty_prebuild.txt + COMMENT "CT: Processing target_empty_prebuild") +add_custom_command(TARGET target_empty POST_BUILD + COMMAND ${CMAKE_COMMAND} -E echo "target_empty_postbuild" > target_empty_postbuild.txt + BYPRODUCTS target_empty_postbuild.txt + COMMENT "CT: Processing target_empty_postbuild") + +add_dependencies(target_cmd target_empty) + +add_custom_command( + OUTPUT out_of_order_dep.txt + COMMAND ${CMAKE_COMMAND} -E echo "out_of_order_dep" > out_of_order_dep.txt + COMMENT "CT: generate text file out_of_order_dep" + DEPENDS dependsA.txt +) + +if(TEST_MISSING_TARGET_SRC) + set(SRC_FILE does_not_exist) +endif() +if(TEST_MISSING_TARGET_DEP) + set(DEP_FILE does_not_exist) +endif() + +add_custom_target(target_update_files + DEPENDS genc_do_not_list.txt ${DEP_FILE} + SOURCES gena.txt genb.txt another_file.c ${SRC_FILE} + BYPRODUCTS junkit.txt + COMMAND ${CMAKE_COMMAND} -E copy another_file.c junkit.txt + COMMENT "CT: Processing target_update_files") + +add_custom_command( + OUTPUT force_rebuild gena.txt genb.txt genc_do_not_list.txt + COMMAND ${CMAKE_COMMAND} -E copy dependsA.txt gena.txt + COMMAND ${CMAKE_COMMAND} -E echo "genb" > genb.txt + COMMAND ${CMAKE_COMMAND} -E echo "genc" > genc_do_not_list.txt + DEPENDS out_of_order_dep.txt dependsA.txt + COMMENT "CT: generate text files A, B, and C" +) + +if(TEST_MISSING_DEP) + set(MISSING_DEP MISSING_DEP) +endif() +if(TEST_DEP_CYCLE) + set(DEP_CYCLE out_of_order_dep.txt) +endif() + +add_custom_command( + OUTPUT dependsA.txt + COMMAND ${CMAKE_COMMAND} -E echo "dependsA" > dependsA.txt + DEPENDS ${MISSING_DEP} ${DEP_CYCLE} another_file.c + COMMENT "CT: generate text file dependsA" +) + +add_custom_command( + OUTPUT another_file.c + COMMAND ${CMAKE_COMMAND} -E echo "//auto-gen file" > another_file.c + COMMENT "CT: generate C file another_file" +) + +add_dependencies(target_update_files target_empty) diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/exe1.c b/Tests/GhsMulti/GhsMultiCustomTarget/exe1.c new file mode 100644 index 0000000..29ad70a --- /dev/null +++ b/Tests/GhsMulti/GhsMultiCustomTarget/exe1.c @@ -0,0 +1,5 @@ +extern int func(void); +int main(void) +{ + return func(); +} diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/lib1.c b/Tests/GhsMulti/GhsMultiCustomTarget/lib1.c new file mode 100644 index 0000000..b35e9cc --- /dev/null +++ b/Tests/GhsMulti/GhsMultiCustomTarget/lib1.c @@ -0,0 +1,4 @@ +int func(void) +{ + return 2; +} diff --git a/Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt new file mode 100644 index 0000000..2e2871b --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt @@ -0,0 +1,12 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +project(test C) + +#set_property( GLOBAL PROPERTY GLOBAL_DEPENDS_DEBUG_MODE 1) +add_subdirectory(exec) +add_subdirectory(lib) +add_subdirectory(protolib) +add_dependencies(lib1 proto) diff --git a/Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt new file mode 100644 index 0000000..85ee805 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt @@ -0,0 +1,11 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +add_executable(exe1 exe1.c) +target_link_libraries(exe1 lib1) +target_include_directories(exe1 PRIVATE "${test_BINARY_DIR}") +if(CMAKE_C_COMPILER_ID STREQUAL "GHS") + target_link_options(exe1 PRIVATE "-non_shared") +endif() diff --git a/Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c b/Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c new file mode 100644 index 0000000..fbf4ed4 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c @@ -0,0 +1,8 @@ +#include "lib1.h" +#include "p.h" + +int main(void) +{ + return func1() + func2() + func3() + func1p() + func2p() + func3p() + + PROTO1 + PROTO2 + PROTO3; +} diff --git a/Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt new file mode 100644 index 0000000..ae30fa2 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt @@ -0,0 +1,17 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +add_library(lib1 STATIC + func1.c lib1.h + "${test_BINARY_DIR}/protolib/proto1.c" + "${test_BINARY_DIR}/protolib/proto1.h") +set_source_files_properties( + "${test_BINARY_DIR}/protolib/proto1.c" + "${test_BINARY_DIR}/protolib/proto1.h" + PROPERTIES GENERATED 1) +target_include_directories(lib1 PRIVATE "${test_BINARY_DIR}/protolib" + PUBLIC .) +add_custom_command( TARGET lib1 POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy "${test_BINARY_DIR}/protolib/proto1.h" "${test_BINARY_DIR}/p.h" + COMMENT "Copy ${test_BINARY_DIR}/protolib/proto1.h ${test_BINARY_DIR}/p.h" + BYPRODUCTS "${test_BINARY_DIR}/p.h") diff --git a/Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c b/Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c new file mode 100644 index 0000000..53334fe --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c @@ -0,0 +1,17 @@ +#include "lib1.h" +#include "proto1.h" + +int func1(void) +{ + return 1 + PROTO1; +} + +int func2(void) +{ + return 2 + PROTO2; +} + +int func3(void) +{ + return 3 + PROTO3; +} diff --git a/Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h b/Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h new file mode 100644 index 0000000..5e99f02 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h @@ -0,0 +1,3 @@ +extern int func1(void); +extern int func2(void); +extern int func3(void); diff --git a/Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt new file mode 100644 index 0000000..8cb6869 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt @@ -0,0 +1,28 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +add_custom_target(proto ALL + DEPENDS proto1.c + proto1.h + SOURCES + ${test_SOURCE_DIR}/protolib/proto1.c.in + ${test_SOURCE_DIR}/protolib/proto1.h.in + COMMENT "Creating proto files") + +add_custom_command( + OUTPUT proto1.c + COMMAND ${CMAKE_COMMAND} -E copy + ${test_SOURCE_DIR}/protolib/proto1.c.in proto1.c + DEPENDS ${test_SOURCE_DIR}/protolib/proto1.c.in + COMMENT "generate proto C files" +) + +add_custom_command( + OUTPUT proto1.h + COMMAND ${CMAKE_COMMAND} -E copy + ${test_SOURCE_DIR}/protolib/proto1.h.in proto1.h + DEPENDS ${test_SOURCE_DIR}/protolib/proto1.h.in + COMMENT "generate proto H files" +) diff --git a/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in new file mode 100644 index 0000000..0efb1bd --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in @@ -0,0 +1,16 @@ +#include "proto1.h" + +int func1p(void) +{ + return 1; +} + +int func2p(void) +{ + return 2; +} + +int func3p(void) +{ + return 3; +} diff --git a/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in new file mode 100644 index 0000000..f2f93af --- /dev/null +++ b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in @@ -0,0 +1,7 @@ +extern int func1p(void); +extern int func2p(void); +extern int func3p(void); + +#define PROTO1 0x1 +#define PROTO2 0x2 +#define PROTO3 0x3 diff --git a/Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt b/Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt new file mode 100644 index 0000000..24126c8 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt @@ -0,0 +1,14 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +project(test C) +include(ExternalProject) + +ExternalProject_Add(another_project + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/empty + BINARY_DIR empty_build + INSTALL_COMMAND "" + TEST_COMMAND "" + ) diff --git a/Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt b/Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt new file mode 100644 index 0000000..6846a98 --- /dev/null +++ b/Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt @@ -0,0 +1,8 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + +project(empty NONE) + +message("EMPTY PROJECT") diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt index e431217..3837b5a 100644 --- a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt +++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt @@ -1,4 +1,3 @@ add_executable(App Main.c) -target_include_directories(App PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../Lib) target_link_libraries(App Lib) target_compile_options(App PUBLIC "-non_shared") diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt index 00e0f59..bb9849a 100644 --- a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt +++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt @@ -1 +1,2 @@ add_library(Lib HelperFun.c HelperFun.h) +target_include_directories(Lib PUBLIC .) diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt index c5db155..3f2f0eb 100644 --- a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt +++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt @@ -18,3 +18,4 @@ target_link_options(kernel PRIVATE -kernel) # create monolith INTEGRITY application add_executable(monolith test.int) +add_dependencies(monolith vas) diff --git a/Tests/GhsMulti/GhsMultiPlatform/file1.c b/Tests/GhsMulti/GhsMultiPlatform/file1.c deleted file mode 100644 index 4132aa4..0000000 --- a/Tests/GhsMulti/GhsMultiPlatform/file1.c +++ /dev/null @@ -1,4 +0,0 @@ -int main(void) -{ - return -42; -} diff --git a/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt b/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt index f5792b4..b2540d9 100644 --- a/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt +++ b/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt @@ -13,7 +13,7 @@ endif() if(RUN_TEST STREQUAL "SINGLE_EXEC") add_executable(exe1 exe.c) - set(targets_to_install ${targets_to_install} exe1) + set(targets_to_install exe1) endif() if(RUN_TEST STREQUAL "SINGLE_EXEC_RENAMED") @@ -22,7 +22,7 @@ if(RUN_TEST STREQUAL "SINGLE_EXEC_RENAMED") set_property(TARGET exe1 PROPERTY RUNTIME_OUTPUT_DIRECTORY ${name}_bin_$<CONFIG>) set_property(TARGET exe1 PROPERTY OUTPUT_NAME ${name}_$<CONFIG>) set_property(TARGET exe1 PROPERTY SUFFIX .bin) - set(targets_to_install ${targets_to_install} exe1) + set(targets_to_install exe1) endif() if(RUN_TEST STREQUAL "EXEC_AND_LIB") @@ -33,7 +33,7 @@ if(RUN_TEST STREQUAL "EXEC_AND_LIB") add_executable(exe1 exe1.c) target_link_libraries(exe1 lib1) - set(targets_to_install ${targets_to_install} exe1 lib1) + set(targets_to_install exe1 lib1) endif() install(TARGETS ${targets_to_install} diff --git a/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt b/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt index ed3094b..f5f3c55 100644 --- a/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt +++ b/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt @@ -5,8 +5,6 @@ cmake_minimum_required(VERSION 3.12 FATAL_ERROR) project(test C) -add_custom_target(testTarget ALL echo this is a test) - add_library(sharedLib SHARED file.c) add_library(moduleLib MODULE file.c) diff --git a/Tests/MSVCRuntimeLibrary/CMakeLists.txt b/Tests/MSVCRuntimeLibrary/CMakeLists.txt new file mode 100644 index 0000000..6994d8d --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/CMakeLists.txt @@ -0,0 +1,64 @@ +cmake_minimum_required(VERSION 3.14) +cmake_policy(SET CMP0091 NEW) +project(MSVCRuntimeLibrary) + +function(verify_combinations threads lang src) + set(verify_tc_config_ Release) + set(verify_tc_config_Debug Debug) + set(verify_def_MultiThreaded -DVERIFY_MT) + set(verify_def_Debug -DVERIFY_DEBUG) + set(verify_def_DLL -DVERIFY_DLL) + foreach(dbg "" Debug) + foreach(dll "" DLL) + # Construct the name of this runtime library combination. + set(rtl "${threads}${dbg}${dll}") + + # Test that try_compile builds with this RTL. + set(CMAKE_MSVC_RUNTIME_LIBRARY "${rtl}") + set(CMAKE_TRY_COMPILE_CONFIGURATION "${verify_tc_config_${dbg}}") + set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY") + try_compile(${rtl}_COMPILES + ${CMAKE_CURRENT_BINARY_DIR}/try_compile/${rtl} + ${CMAKE_CURRENT_SOURCE_DIR}/${src} + COMPILE_DEFINITIONS ${verify_def_${threads}} ${verify_def_${dbg}} ${verify_def_${dll}} + OUTPUT_VARIABLE ${rtl}_OUTPUT + ) + if(${rtl}_COMPILES) + message(STATUS "try_compile with ${rtl} worked") + else() + string(REPLACE "\n" "\n " ${rtl}_OUTPUT " ${${rtl}_OUTPUT}") + message(SEND_ERROR "try_compile with ${rtl} failed:\n${${rtl}_OUTPUT}") + endif() + + # Test that targets build with this RTL. + set(CMAKE_MSVC_RUNTIME_LIBRARY "$<$<BOOL:$<TARGET_PROPERTY:BOOL_TRUE>>:${rtl}>$<$<BOOL:$<TARGET_PROPERTY:BOOL_FALSE>>:BadContent>") + add_library(${rtl}-${lang} ${src}) + set_property(TARGET ${rtl}-${lang} PROPERTY BOOL_TRUE TRUE) + target_compile_definitions(${rtl}-${lang} PRIVATE ${verify_def_${threads}} ${verify_def_${dbg}} ${verify_def_${dll}}) + endforeach() + endforeach() +endfunction() + +function(verify lang src) + add_library(default-${lang} ${src}) + target_compile_definitions(default-${lang} PRIVATE VERIFY_MT VERIFY_DLL "$<$<CONFIG:Debug>:VERIFY_DEBUG>") + + verify_combinations(MultiThreaded ${lang} ${src}) + + # Test known MSVC default behavior when no flag is given. + if(CMAKE_${lang}_COMPILER_ID STREQUAL "MSVC") + set(CMAKE_MSVC_RUNTIME_LIBRARY "") + add_library(empty-${lang} ${src}) + if(CMAKE_${lang}_COMPILER_VERSION VERSION_GREATER_EQUAL 14) + # VS 2005 and above default to multi-threaded. + target_compile_definitions(empty-${lang} PRIVATE VERIFY_MT) + endif() + if(CMAKE_GENERATOR MATCHES "Visual Studio ([^9]|9[0-9])") + # VS 2010 and above have a different default runtime library for projects than 'cl'. + target_compile_definitions(empty-${lang} PRIVATE VERIFY_DLL) + endif() + endif() +endfunction() + +verify(C verify.c) +verify(CXX verify.cxx) diff --git a/Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt b/Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt new file mode 100644 index 0000000..169ba07 --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt @@ -0,0 +1,50 @@ +cmake_minimum_required(VERSION 3.14) +cmake_policy(SET CMP0091 NEW) +project(MSVCRuntimeLibraryFortran Fortran) + +foreach(t MultiThreaded SingleThreaded) + foreach(dbg "" Debug) + foreach(dll "" DLL) + set(var "CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_${t}${dbg}${dll}") + # ifort does not actually define these, so inject them + string(REPLACE "-threads" "-threads;-D_MT" "${var}" "${${var}}") + string(REPLACE "-dbglibs" "-dbglibs;-D_DEBUG" "${var}" "${${var}}") + endforeach() + endforeach() +endforeach() +string(APPEND CMAKE_Fortran_FLAGS " -w") + +function(verify_combinations threads lang src) + set(verify_tc_config_ Release) + set(verify_tc_config_Debug Debug) + set(verify_def_MultiThreaded -DVERIFY_MT) + set(verify_def_Debug -DVERIFY_DEBUG) + set(verify_def_DLL -DVERIFY_DLL) + foreach(dbg "" Debug) + foreach(dll "" DLL) + # Construct the name of this runtime library combination. + set(rtl "${threads}${dbg}${dll}") + + # Test that targets build with this RTL. + set(CMAKE_MSVC_RUNTIME_LIBRARY "$<$<BOOL:$<TARGET_PROPERTY:BOOL_TRUE>>:${rtl}>$<$<BOOL:$<TARGET_PROPERTY:BOOL_FALSE>>:BadContent>") + add_library(${rtl}-${lang} ${src}) + set_property(TARGET ${rtl}-${lang} PROPERTY BOOL_TRUE TRUE) + target_compile_definitions(${rtl}-${lang} PRIVATE ${verify_def_${threads}} ${verify_def_${dbg}} ${verify_def_${dll}}) + endforeach() + endforeach() +endfunction() + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +function(verify lang src) + add_library(default-${lang} ${src}) + target_compile_definitions(default-${lang} PRIVATE VERIFY_MT VERIFY_DLL "$<$<CONFIG:Debug>:VERIFY_DEBUG>") + verify_combinations(MultiThreaded ${lang} ${src}) +endfunction() + +verify(Fortran verify.F90) +# Intel Fortran for Windows supports single-threaded RTL but it is +# not implemented by the Visual Studio integration. +if(NOT CMAKE_GENERATOR MATCHES "Visual Studio") + verify_combinations(SingleThreaded Fortran verify.F90) +endif() diff --git a/Tests/MSVCRuntimeLibrary/Fortran/verify.F90 b/Tests/MSVCRuntimeLibrary/Fortran/verify.F90 new file mode 100644 index 0000000..6fe5e05 --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/Fortran/verify.F90 @@ -0,0 +1 @@ +#include "../verify.h" diff --git a/Tests/MSVCRuntimeLibrary/verify.c b/Tests/MSVCRuntimeLibrary/verify.c new file mode 100644 index 0000000..741bca6 --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/verify.c @@ -0,0 +1 @@ +#include "verify.h" diff --git a/Tests/MSVCRuntimeLibrary/verify.cxx b/Tests/MSVCRuntimeLibrary/verify.cxx new file mode 100644 index 0000000..741bca6 --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/verify.cxx @@ -0,0 +1 @@ +#include "verify.h" diff --git a/Tests/MSVCRuntimeLibrary/verify.h b/Tests/MSVCRuntimeLibrary/verify.h new file mode 100644 index 0000000..58d65fe --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/verify.h @@ -0,0 +1,29 @@ +#ifdef VERIFY_DEBUG +# ifndef _DEBUG +# error "_DEBUG not defined by debug runtime library selection" +# endif +#else +# ifdef _DEBUG +# error "_DEBUG defined by non-debug runtime library selection" +# endif +#endif + +#ifdef VERIFY_DLL +# ifndef _DLL +# error "_DLL not defined by DLL runtime library selection" +# endif +#else +# ifdef _DLL +# error "_DLL defined by non-DLL runtime library selection" +# endif +#endif + +#ifdef VERIFY_MT +# ifndef _MT +# error "_MT not defined by multi-threaded runtime library selection" +# endif +#else +# ifdef _MT +# error "_MT defined by single-threaded runtime library selection" +# endif +#endif diff --git a/Tests/ObjectLibrary/CMakeLists.txt b/Tests/ObjectLibrary/CMakeLists.txt index 4bffd12..7897ab9 100644 --- a/Tests/ObjectLibrary/CMakeLists.txt +++ b/Tests/ObjectLibrary/CMakeLists.txt @@ -62,4 +62,14 @@ add_custom_target(UseABinternalDep COMMAND ${CMAKE_COMMAND} -E touch UseABintern add_custom_command(TARGET UseABinternal POST_BUILD COMMAND ${CMAKE_COMMAND} -P UseABinternalDep.cmake) add_dependencies(UseABinternal UseABinternalDep) +# Test a static library with sources from a different static library +add_library(UseCstaticObjs STATIC $<TARGET_OBJECTS:Cstatic> $<TARGET_OBJECTS:A> $<TARGET_OBJECTS:Bexport>) + +# Test a shared library with sources from a different shared library +add_library(UseCsharedObjs SHARED $<TARGET_OBJECTS:Cshared> $<TARGET_OBJECTS:A> $<TARGET_OBJECTS:Bexport>) + +# Test a shared executable with sources from a different shared library +add_executable(UseABstaticObjs $<TARGET_OBJECTS:UseABstatic>) +target_link_libraries(UseABstaticObjs ABstatic) + add_subdirectory(ExportLanguages) diff --git a/Tests/QtAutogen/ManySources/CMakeLists.txt b/Tests/QtAutogen/ManySources/CMakeLists.txt new file mode 100644 index 0000000..df8a2a6 --- /dev/null +++ b/Tests/QtAutogen/ManySources/CMakeLists.txt @@ -0,0 +1,35 @@ +cmake_minimum_required(VERSION 3.10) +project(ManySources) +include("../AutogenGuiTest.cmake") + +# Test AUTOMOC and AUTOUIC on many source files to stress the concurrent +# parsing and processing framework. + +set(CSD ${CMAKE_CURRENT_SOURCE_DIR}) +set(CBD ${CMAKE_CURRENT_BINARY_DIR}) + +set(SRCS main.cpp) +set(MAIN_INCLUDES "\n// Item includes\n") +set(MAIN_ITEMS "\n// Items\n") + +set(NUM 24) +foreach(III RANGE 1 ${NUM}) + configure_file(${CSD}/object.h.in ${CBD}/object_${III}.h) + configure_file(${CSD}/item.h.in ${CBD}/item_${III}.h) + configure_file(${CSD}/item.cpp.in ${CBD}/item_${III}.cpp) + configure_file(${CSD}/view.ui.in ${CBD}/view_${III}.ui) + configure_file(${CSD}/data.qrc.in ${CBD}/data_${III}.qrc) + + list(APPEND SRCS ${CBD}/item_${III}.cpp) + list(APPEND SRCS ${CBD}/data_${III}.qrc) + + string(APPEND MAIN_INCLUDES "#include \"item_${III}.h\"\n") + string(APPEND MAIN_ITEMS "Item_${III} item_${III};\n") + string(APPEND MAIN_ITEMS "item_${III}.TheSlot();\n") +endforeach() + +configure_file(${CSD}/main.cpp.in ${CBD}/main.cpp) + +add_executable(manySources ${SRCS} ${CBD}/main.cpp) +target_link_libraries(manySources ${QT_LIBRARIES}) +set_target_properties(manySources PROPERTIES AUTOMOC 1 AUTOUIC 1 AUTORCC 1) diff --git a/Tests/QtAutogen/ManySources/data.qrc.in b/Tests/QtAutogen/ManySources/data.qrc.in new file mode 100644 index 0000000..870d486 --- /dev/null +++ b/Tests/QtAutogen/ManySources/data.qrc.in @@ -0,0 +1,7 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file>object_@III@.h</file> + <file>item_@III@.h</file> + <file>item_@III@.cpp</file> +</qresource> +</RCC> diff --git a/Tests/QtAutogen/ManySources/item.cpp.in b/Tests/QtAutogen/ManySources/item.cpp.in new file mode 100644 index 0000000..c34ad16 --- /dev/null +++ b/Tests/QtAutogen/ManySources/item.cpp.in @@ -0,0 +1,27 @@ +#include "item_@III@.h" +#include "object_@III@.h" +// AUTOUIC include +#include <ui_view_@III@.h> + +class LocalObject_@III@ : public QObject +{ + Q_OBJECT; + +public: + LocalObject_@III@() = default; + ~LocalObject_@III@() = default; +}; + +void Item_@III@ ::TheSlot() +{ + LocalObject_@III@ localObject; + Object_@III@ obj; + obj.ObjectSlot(); + + Ui_View_@III@ ui_view; +} + +// AUTOMOC includes +#include "item_@III@.moc" +#include "moc_item_@III@.cpp" +#include "moc_object_@III@.cpp" diff --git a/Tests/QtAutogen/ManySources/item.h.in b/Tests/QtAutogen/ManySources/item.h.in new file mode 100644 index 0000000..67ad794 --- /dev/null +++ b/Tests/QtAutogen/ManySources/item.h.in @@ -0,0 +1,15 @@ +#ifndef ITEM_@III@HPP +#define ITEM_@III@HPP + +#include <QObject> + +class Item_@III@ : public QObject +{ + Q_OBJECT + +public: + Q_SLOT + void TheSlot(); +}; + +#endif diff --git a/Tests/QtAutogen/ManySources/main.cpp.in b/Tests/QtAutogen/ManySources/main.cpp.in new file mode 100644 index 0000000..e1dda40 --- /dev/null +++ b/Tests/QtAutogen/ManySources/main.cpp.in @@ -0,0 +1,7 @@ +@MAIN_INCLUDES@ + +int main(int argv, char** args) +{ + @MAIN_ITEMS@ + return 0; +} diff --git a/Tests/QtAutogen/ManySources/object.h.in b/Tests/QtAutogen/ManySources/object.h.in new file mode 100644 index 0000000..a747cbc --- /dev/null +++ b/Tests/QtAutogen/ManySources/object.h.in @@ -0,0 +1,15 @@ +#ifndef OBJECT_@III@H +#define OBJECT_@III@H + +#include <QObject> + +class Object_@III@ : public QObject +{ + Q_OBJECT + +public: + Q_SLOT + void ObjectSlot(){}; +}; + +#endif diff --git a/Tests/QtAutogen/ManySources/view.ui.in b/Tests/QtAutogen/ManySources/view.ui.in new file mode 100644 index 0000000..6901fe3 --- /dev/null +++ b/Tests/QtAutogen/ManySources/view.ui.in @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>View_@III@</class> + <widget class="QWidget" name="Base"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QTreeView" name="treeView"/> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/Tests/QtAutogen/Tests.cmake b/Tests/QtAutogen/Tests.cmake index 096d5e3..6771828 100644 --- a/Tests/QtAutogen/Tests.cmake +++ b/Tests/QtAutogen/Tests.cmake @@ -5,6 +5,7 @@ ADD_AUTOGEN_TEST(AutogenTargetDepends) ADD_AUTOGEN_TEST(Complex QtAutogen) ADD_AUTOGEN_TEST(GlobalAutogenTarget) ADD_AUTOGEN_TEST(LowMinimumVersion lowMinimumVersion) +ADD_AUTOGEN_TEST(ManySources manySources) ADD_AUTOGEN_TEST(MocOnly mocOnly) ADD_AUTOGEN_TEST(MocOptions mocOptions) ADD_AUTOGEN_TEST(ObjectLibrary someProgram) diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt index 68411d6..2b78171 100644 --- a/Tests/RunCMake/CMakeLists.txt +++ b/Tests/RunCMake/CMakeLists.txt @@ -195,6 +195,10 @@ add_RunCMake_test(LinkStatic) if(CMAKE_CXX_COMPILER_ID MATCHES "^(Cray|PGI|XL|XLClang)$") add_RunCMake_test(MetaCompileFeatures) endif() +if(MSVC) + add_RunCMake_test(MSVCRuntimeLibrary) + add_RunCMake_test(MSVCWarningFlags) +endif() add_RunCMake_test(ObjectLibrary) add_RunCMake_test(ParseImplicitIncludeInfo) if(UNIX AND CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG AND CMAKE_EXECUTABLE_FORMAT STREQUAL "ELF") @@ -255,6 +259,7 @@ add_RunCMake_test(ctest_submit) add_RunCMake_test(ctest_test) add_RunCMake_test(ctest_disabled_test) add_RunCMake_test(ctest_skipped_test) +add_RunCMake_test(ctest_update -DGIT_EXECUTABLE=${GIT_EXECUTABLE}) add_RunCMake_test(ctest_upload) add_RunCMake_test(ctest_fixtures) add_RunCMake_test(file) diff --git a/Tests/RunCMake/File_Generate/OutputNameMatchesObjects-stderr.txt b/Tests/RunCMake/File_Generate/OutputNameMatchesObjects-stderr.txt index b08ef5a..4c2e35f 100644 --- a/Tests/RunCMake/File_Generate/OutputNameMatchesObjects-stderr.txt +++ b/Tests/RunCMake/File_Generate/OutputNameMatchesObjects-stderr.txt @@ -3,6 +3,7 @@ CMake Error at OutputNameMatchesObjects.cmake:[0-9]+ \(file\): \$<TARGET_OBJECTS:foo> - Objects of target "foo" referenced but is not an OBJECT library. + Objects of target "foo" referenced but is not an allowed library types + \(EXECUTABLE, STATIC, SHARED, MODULE, OBJECT\). Call Stack \(most recent call first\): CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/File_Generate/OutputNameMatchesObjects.cmake b/Tests/RunCMake/File_Generate/OutputNameMatchesObjects.cmake index daa7c49..84825fe 100644 --- a/Tests/RunCMake/File_Generate/OutputNameMatchesObjects.cmake +++ b/Tests/RunCMake/File_Generate/OutputNameMatchesObjects.cmake @@ -1,11 +1,8 @@ enable_language(CXX) file(GENERATE - OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<BOOL:$<TARGET_OBJECTS:foo>>somefile.cpp" + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<LOWER_CASE:$<CONFIG>/somefile.cpp" CONTENT "static const char content[] = \"$<TARGET_OBJECTS:foo>\";\n" ) -add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/input.txt" - COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/input.txt" "${CMAKE_CURRENT_BINARY_DIR}") - -add_executable(foo empty.cpp "${CMAKE_CURRENT_BINARY_DIR}/1somefile.cpp" "${CMAKE_CURRENT_BINARY_DIR}/input.txt") +add_library(foo INTERFACE ) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target-result.txt +++ b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt new file mode 100644 index 0000000..3b2a814 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt @@ -0,0 +1,8 @@ +CMake Error at ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake:2 \(add_custom_target\): + Error evaluating generator expression: + + \$<TARGET_PDB_FILE_BASE_NAME:empty> + + TARGET_PDB_FILE_BASE_NAME not allowed for IMPORTED targets. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake new file mode 100644 index 0000000..489d8e6 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake @@ -0,0 +1,2 @@ +add_library(empty UNKNOWN IMPORTED) +add_custom_target(custom COMMAND echo $<TARGET_PDB_FILE_BASE_NAME:empty>) diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME-stderr.txt deleted file mode 100644 index 783bfb3..0000000 --- a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME-stderr.txt +++ /dev/null @@ -1,8 +0,0 @@ -CMake Error at ImportedTarget-TARGET_PDB_OUTPUT_NAME.cmake:2 \(add_custom_target\): - Error evaluating generator expression: - - \$<TARGET_PDB_OUTPUT_NAME:empty> - - TARGET_PDB_OUTPUT_NAME not allowed for IMPORTED targets. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME.cmake b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME.cmake deleted file mode 100644 index 010b38e..0000000 --- a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME.cmake +++ /dev/null @@ -1,2 +0,0 @@ -add_library(empty UNKNOWN IMPORTED) -add_custom_target(custom COMMAND echo $<TARGET_PDB_OUTPUT_NAME:empty>) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target-result.txt +++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt new file mode 100644 index 0000000..b061ce3 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt @@ -0,0 +1,8 @@ +CMake Error at NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake:6 \(file\): + Error evaluating generator expression: + + \$<TARGET_PDB_FILE_BASE_NAME:empty> + + TARGET_PDB_FILE_BASE_NAME is not supported by the target linker. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME.cmake b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake index 07951de..811c3f7 100644 --- a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME.cmake +++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake @@ -5,5 +5,5 @@ add_library(empty STATIC empty.c) file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt" - CONTENT "[$<TARGET_PDB_OUTPUT_NAME:empty>]" + CONTENT "[$<TARGET_PDB_FILE_BASE_NAME:empty>]" ) diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME-stderr.txt deleted file mode 100644 index 00ec496..0000000 --- a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME-stderr.txt +++ /dev/null @@ -1,8 +0,0 @@ -CMake Error at NonValidCompiler-TARGET_PDB_OUTPUT_NAME.cmake:6 \(file\): - Error evaluating generator expression: - - \$<TARGET_PDB_OUTPUT_NAME:empty> - - TARGET_PDB_OUTPUT_NAME is not supported by the target linker. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME-result.txt +++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt new file mode 100644 index 0000000..c7d245c --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt @@ -0,0 +1,9 @@ +CMake Error at NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake:6 \(file\): + Error evaluating generator expression: + + \$<TARGET_PDB_FILE_BASE_NAME:empty> + + TARGET_PDB_FILE_BASE_NAME is allowed only for targets with linker created + artifacts. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME.cmake b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake index 07951de..811c3f7 100644 --- a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME.cmake +++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake @@ -5,5 +5,5 @@ add_library(empty STATIC empty.c) file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt" - CONTENT "[$<TARGET_PDB_OUTPUT_NAME:empty>]" + CONTENT "[$<TARGET_PDB_FILE_BASE_NAME:empty>]" ) diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME-stderr.txt deleted file mode 100644 index 8ac349e..0000000 --- a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_OUTPUT_NAME-stderr.txt +++ /dev/null @@ -1,9 +0,0 @@ -CMake Error at NonValidTarget-TARGET_PDB_OUTPUT_NAME.cmake:6 \(file\): - Error evaluating generator expression: - - \$<TARGET_PDB_OUTPUT_NAME:empty> - - TARGET_PDB_OUTPUT_NAME is allowed only for targets with linker created - artifacts. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/OUTPUT_NAME-recursion.cmake b/Tests/RunCMake/GeneratorExpression/OUTPUT_NAME-recursion.cmake index 775f68a..006b0da 100644 --- a/Tests/RunCMake/GeneratorExpression/OUTPUT_NAME-recursion.cmake +++ b/Tests/RunCMake/GeneratorExpression/OUTPUT_NAME-recursion.cmake @@ -3,4 +3,4 @@ add_executable(empty1 empty.c) set_property(TARGET empty1 PROPERTY OUTPUT_NAME $<TARGET_FILE_NAME:empty1>) add_executable(empty2 empty.c) -set_property(TARGET empty2 PROPERTY OUTPUT_NAME $<TARGET_OUTPUT_NAME:empty2>) +set_property(TARGET empty2 PROPERTY OUTPUT_NAME $<TARGET_FILE_BASE_NAME:empty2>) diff --git a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake index 0b0fb78..477b593 100644 --- a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake +++ b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake @@ -41,10 +41,10 @@ run_cmake(TARGET_FILE_SUFFIX) run_cmake(TARGET_FILE_SUFFIX-imported-target) run_cmake(TARGET_FILE_SUFFIX-non-valid-target) run_cmake(TARGET_LINKER_FILE_SUFFIX-non-valid-target) -run_cmake(TARGET_OUTPUT_NAME) -run_cmake(TARGET_OUTPUT_NAME-imported-target) -run_cmake(TARGET_OUTPUT_NAME-non-valid-target) -run_cmake(TARGET_LINKER_OUTPUT_NAME-non-valid-target) +run_cmake(TARGET_FILE_BASE_NAME) +run_cmake(TARGET_FILE_BASE_NAME-imported-target) +run_cmake(TARGET_FILE_BASE_NAME-non-valid-target) +run_cmake(TARGET_LINKER_FILE_BASE_NAME-non-valid-target) run_cmake(TARGET_PROPERTY-LOCATION) run_cmake(TARGET_PROPERTY-SOURCES) run_cmake(LINK_ONLY-not-linking) @@ -78,15 +78,15 @@ run_cmake(FILTER-Include) run_cmake(ImportedTarget-TARGET_BUNDLE_DIR) run_cmake(ImportedTarget-TARGET_BUNDLE_CONTENT_DIR) run_cmake(ImportedTarget-TARGET_PDB_FILE) -run_cmake(ImportedTarget-TARGET_PDB_OUTPUT_NAME) +run_cmake(ImportedTarget-TARGET_PDB_FILE_BASE_NAME) if(LINKER_SUPPORTS_PDB) run_cmake(NonValidTarget-TARGET_PDB_FILE) run_cmake(ValidTarget-TARGET_PDB_FILE) - run_cmake(NonValidTarget-TARGET_PDB_OUTPUT_NAME) - run_cmake(ValidTarget-TARGET_PDB_OUTPUT_NAME) + run_cmake(NonValidTarget-TARGET_PDB_FILE_BASE_NAME) + run_cmake(ValidTarget-TARGET_PDB_FILE_BASE_NAME) else() run_cmake(NonValidCompiler-TARGET_PDB_FILE) - run_cmake(NonValidCompiler-TARGET_PDB_OUTPUT_NAME) + run_cmake(NonValidCompiler-TARGET_PDB_FILE_BASE_NAME) endif() set(RunCMake_TEST_OPTIONS -DCMAKE_POLICY_DEFAULT_CMP0085:STRING=OLD) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake new file mode 100644 index 0000000..793edb1 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake @@ -0,0 +1,2 @@ + +include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake new file mode 100644 index 0000000..793edb1 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake @@ -0,0 +1,2 @@ + +include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-imported-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target.cmake index 548a2d7..aa54b31 100644 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-imported-target.cmake +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target.cmake @@ -17,11 +17,11 @@ add_library (static1 STATIC IMPORTED) string (APPEND GENERATE_CONTENT [[ -check_value ("TARGET_OUTPUT_NAME executable default" "$<TARGET_OUTPUT_NAME:exec1>" "exec1") -check_value ("TARGET_OUTPUT_NAME shared default" "$<TARGET_OUTPUT_NAME:shared1>" "shared1") -check_value ("TARGET_LINKER_OUTPUT_NAME shared linker default" "$<TARGET_LINKER_OUTPUT_NAME:shared1>" "shared1") -check_value ("TARGET_OUTPUT_NAME static default" "$<TARGET_OUTPUT_NAME:static1>" "static1") -check_value ("TARGET_LINKER_OUTPUT_NAME static linker default" "$<TARGET_LINKER_OUTPUT_NAME:static1>" "static1") +check_value ("TARGET_FILE_BASE_NAME executable default" "$<TARGET_FILE_BASE_NAME:exec1>" "exec1") +check_value ("TARGET_FILE_BASE_NAME shared default" "$<TARGET_FILE_BASE_NAME:shared1>" "shared1") +check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker default" "$<TARGET_LINKER_FILE_BASE_NAME:shared1>" "shared1") +check_value ("TARGET_FILE_BASE_NAME static default" "$<TARGET_FILE_BASE_NAME:static1>" "static1") +check_value ("TARGET_LINKER_FILE_BASE_NAME static linker default" "$<TARGET_LINKER_FILE_BASE_NAME:static1>" "static1") ]]) @@ -34,11 +34,11 @@ set_property (TARGET static2 PROPERTY OUTPUT_NAME static2_custom) string (APPEND GENERATE_CONTENT [[ -check_value ("TARGET_OUTPUT_NAME executable custom" "$<TARGET_OUTPUT_NAME:exec2>" "exec2_custom") -check_value ("TARGET_OUTPUT_NAME shared custom" "$<TARGET_OUTPUT_NAME:shared2>" "shared2_custom") -check_value ("TARGET_LINKER_OUTPUT_NAME shared linker custom" "$<TARGET_LINKER_OUTPUT_NAME:shared2>" "shared2_custom") -check_value ("TARGET_OUTPUT_NAME static custom" "$<TARGET_OUTPUT_NAME:static2>" "static2_custom") -check_value ("TARGET_LINKER_OUTPUT_NAME static linker custom" "$<TARGET_LINKER_OUTPUT_NAME:static2>" "static2_custom") +check_value ("TARGET_FILE_BASE_NAME executable custom" "$<TARGET_FILE_BASE_NAME:exec2>" "exec2_custom") +check_value ("TARGET_FILE_BASE_NAME shared custom" "$<TARGET_FILE_BASE_NAME:shared2>" "shared2_custom") +check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:shared2>" "shared2_custom") +check_value ("TARGET_FILE_BASE_NAME static custom" "$<TARGET_FILE_BASE_NAME:static2>" "static2_custom") +check_value ("TARGET_LINKER_FILE_BASE_NAME static linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:static2>" "static2_custom") ]]) @@ -60,11 +60,11 @@ set_property (TARGET static3 PROPERTY PDB_NAME static3_pdb) string (APPEND GENERATE_CONTENT [[ -check_value ("TARGET_OUTPUT_NAME executable all properties" "$<TARGET_OUTPUT_NAME:exec3>" "exec3_runtime") -check_value ("TARGET_OUTPUT_NAME shared all properties" "$<TARGET_OUTPUT_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_runtime,shared3_library>") -check_value ("TARGET_LINKER_OUTPUT_NAME shared linker all properties" "$<TARGET_LINKER_OUTPUT_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_archive,shared3_library>") -check_value ("TARGET_OUTPUT_NAME static all properties" "$<TARGET_OUTPUT_NAME:static3>" "static3_archive") -check_value ("TARGET_LINKER_OUTPUT_NAME static linker all properties" "$<TARGET_LINKER_OUTPUT_NAME:static3>" "static3_archive") +check_value ("TARGET_FILE_BASE_NAME executable all properties" "$<TARGET_FILE_BASE_NAME:exec3>" "exec3_runtime") +check_value ("TARGET_FILE_BASE_NAME shared all properties" "$<TARGET_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_runtime,shared3_library>") +check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_archive,shared3_library>") +check_value ("TARGET_FILE_BASE_NAME static all properties" "$<TARGET_FILE_BASE_NAME:static3>" "static3_archive") +check_value ("TARGET_LINKER_FILE_BASE_NAME static linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:static3>" "static3_archive") ]]) @@ -75,5 +75,5 @@ if(_isMultiConfig) set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>) endif() -file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_OUTPUT_NAME-generated.cmake" +file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake" CONTENT "${GENERATE_CONTENT}" ${GENERATE_CONDITION}) diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_OUTPUT_NAME-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt new file mode 100644 index 0000000..ecb9e5d --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt @@ -0,0 +1,6 @@ +CMake Error at TARGET_FILE_BASE_NAME-non-valid-target.cmake:[0-9]+ \(file\): + Error evaluating generator expression: + + \$<TARGET_FILE_BASE_NAME:empty> + + Target "empty" is not an executable or library\. diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target.cmake index 5248dfa..8622b7d 100644 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target.cmake +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target.cmake @@ -3,5 +3,5 @@ add_custom_target(empty) file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt" - CONTENT "[$<TARGET_OUTPUT_NAME:empty>]" + CONTENT "[$<TARGET_FILE_BASE_NAME:empty>]" ) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake new file mode 100644 index 0000000..5ea53a0 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake @@ -0,0 +1,96 @@ + +cmake_minimum_required(VERSION 3.14) + +enable_language (C) + +set (GENERATE_CONTENT [[ +macro (CHECK_VALUE test_msg value expected) + if (NOT "${value}" STREQUAL "${expected}") + string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n") + endif() +endmacro() +]]) + +add_executable (exec1 empty.c) +add_library (shared1 SHARED empty.c) +add_library (static1 STATIC empty.c) + +string (APPEND GENERATE_CONTENT [[ + +check_value ("TARGET_FILE_BASE_NAME executable default" "$<TARGET_FILE_BASE_NAME:exec1>" "exec1") +check_value ("TARGET_FILE_BASE_NAME shared default" "$<TARGET_FILE_BASE_NAME:shared1>" "shared1") +check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker default" "$<TARGET_LINKER_FILE_BASE_NAME:shared1>" "shared1") +check_value ("TARGET_FILE_BASE_NAME static default" "$<TARGET_FILE_BASE_NAME:static1>" "static1") +check_value ("TARGET_LINKER_FILE_BASE_NAME static linker default" "$<TARGET_LINKER_FILE_BASE_NAME:static1>" "static1") +]]) +if (CMAKE_C_LINKER_SUPPORTS_PDB) + string(APPEND GENERATE_CONTENT [[ +check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB default" "$<TARGET_PDB_FILE_BASE_NAME:exec1>" "exec1") +check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB default" "$<TARGET_PDB_FILE_BASE_NAME:shared1>" "shared1") +]]) +endif() + + +add_executable (exec2 empty.c) +set_property (TARGET exec2 PROPERTY OUTPUT_NAME exec2_custom) +add_library (shared2 SHARED empty.c) +set_property (TARGET shared2 PROPERTY OUTPUT_NAME shared2_custom) +add_library (static2 STATIC empty.c) +set_property (TARGET static2 PROPERTY OUTPUT_NAME static2_custom) + +string (APPEND GENERATE_CONTENT [[ + +check_value ("TARGET_FILE_BASE_NAME executable custom" "$<TARGET_FILE_BASE_NAME:exec2>" "exec2_custom") +check_value ("TARGET_FILE_BASE_NAME shared custom" "$<TARGET_FILE_BASE_NAME:shared2>" "shared2_custom") +check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:shared2>" "shared2_custom") +check_value ("TARGET_FILE_BASE_NAME static custom" "$<TARGET_FILE_BASE_NAME:static2>" "static2_custom") +check_value ("TARGET_LINKER_FILE_BASE_NAME static linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:static2>" "static2_custom") +]]) +if (CMAKE_C_LINKER_SUPPORTS_PDB) + string (APPEND GENERATE_CONTENT [[ +check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB custom" "$<TARGET_PDB_FILE_BASE_NAME:exec2>" "exec2_custom") +check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB custom" "$<TARGET_PDB_FILE_BASE_NAME:shared2>" "shared2_custom") + ]]) +endif() + +add_executable (exec3 empty.c) +set_property (TARGET exec3 PROPERTY RUNTIME_OUTPUT_NAME exec3_runtime) +set_property (TARGET exec3 PROPERTY LIBRARY_OUTPUT_NAME exec3_library) +set_property (TARGET exec3 PROPERTY ARCHIVE_OUTPUT_NAME exec3_archive) +set_property (TARGET exec3 PROPERTY PDB_NAME exec3_pdb) +add_library (shared3 SHARED empty.c) +set_property (TARGET shared3 PROPERTY RUNTIME_OUTPUT_NAME shared3_runtime) +set_property (TARGET shared3 PROPERTY LIBRARY_OUTPUT_NAME shared3_library) +set_property (TARGET shared3 PROPERTY ARCHIVE_OUTPUT_NAME shared3_archive) +set_property (TARGET shared3 PROPERTY PDB_NAME shared3_pdb) +add_library (static3 STATIC empty.c) +set_property (TARGET static3 PROPERTY RUNTIME_OUTPUT_NAME static3_runtime) +set_property (TARGET static3 PROPERTY LIBRARY_OUTPUT_NAME static3_library) +set_property (TARGET static3 PROPERTY ARCHIVE_OUTPUT_NAME static3_archive) +set_property (TARGET static3 PROPERTY PDB_NAME static3_pdb) + +string (APPEND GENERATE_CONTENT [[ + +check_value ("TARGET_FILE_BASE_NAME executable all properties" "$<TARGET_FILE_BASE_NAME:exec3>" "exec3_runtime") +check_value ("TARGET_FILE_BASE_NAME shared all properties" "$<TARGET_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_runtime,shared3_library>") +check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_archive,shared3_library>") +check_value ("TARGET_FILE_BASE_NAME static all properties" "$<TARGET_FILE_BASE_NAME:static3>" "static3_archive") +check_value ("TARGET_LINKER_FILE_BASE_NAME static linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:static3>" "static3_archive") +]]) +if (CMAKE_C_LINKER_SUPPORTS_PDB) + string (APPEND GENERATE_CONTENT [[ +check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB all properties" "$<TARGET_PDB_FILE_BASE_NAME:exec3>" "exec3_pdb") +check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB all properties" "$<TARGET_PDB_FILE_BASE_NAME:shared3>" "shared3_pdb") +]]) +endif() + + +unset(GENERATE_CONDITION) +get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(_isMultiConfig) + list(GET CMAKE_CONFIGURATION_TYPES 0 FIRST_CONFIG) + set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>) +endif() + +file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake" + CONTENT "${GENERATE_CONTENT}" ${GENERATE_CONDITION}) diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_OUTPUT_NAME-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt new file mode 100644 index 0000000..1ae2f2c --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt @@ -0,0 +1,6 @@ +CMake Error at TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake:[0-9]+ \(file\): + Error evaluating generator expression: + + \$<TARGET_LINKER_FILE_BASE_NAME:empty> + + Target "empty" is not an executable or library\. diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake index c439535..776fb4b 100644 --- a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target.cmake +++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake @@ -3,5 +3,5 @@ add_custom_target(empty) file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt" - CONTENT "[$<TARGET_LINKER_OUTPUT_NAME:empty>]" + CONTENT "[$<TARGET_LINKER_FILE_BASE_NAME:empty>]" ) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target-stderr.txt deleted file mode 100644 index 0e09469..0000000 --- a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_OUTPUT_NAME-non-valid-target-stderr.txt +++ /dev/null @@ -1,6 +0,0 @@ -CMake Error at TARGET_LINKER_OUTPUT_NAME-non-valid-target.cmake:[0-9]+ \(file\): - Error evaluating generator expression: - - \$<TARGET_LINKER_OUTPUT_NAME:empty> - - Target "empty" is not an executable or library\. diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-check.cmake deleted file mode 100644 index fa4f2b9..0000000 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-check.cmake +++ /dev/null @@ -1,2 +0,0 @@ - -include ("${RunCMake_TEST_BINARY_DIR}/TARGET_OUTPUT_NAME-generated.cmake") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-imported-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-imported-target-check.cmake deleted file mode 100644 index fa4f2b9..0000000 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-imported-target-check.cmake +++ /dev/null @@ -1,2 +0,0 @@ - -include ("${RunCMake_TEST_BINARY_DIR}/TARGET_OUTPUT_NAME-generated.cmake") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target-stderr.txt deleted file mode 100644 index 9672a99..0000000 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME-non-valid-target-stderr.txt +++ /dev/null @@ -1,6 +0,0 @@ -CMake Error at TARGET_OUTPUT_NAME-non-valid-target.cmake:[0-9]+ \(file\): - Error evaluating generator expression: - - \$<TARGET_OUTPUT_NAME:empty> - - Target "empty" is not an executable or library\. diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME.cmake deleted file mode 100644 index b7bae15..0000000 --- a/Tests/RunCMake/GeneratorExpression/TARGET_OUTPUT_NAME.cmake +++ /dev/null @@ -1,96 +0,0 @@ - -cmake_minimum_required(VERSION 3.14) - -enable_language (C) - -set (GENERATE_CONTENT [[ -macro (CHECK_VALUE test_msg value expected) - if (NOT "${value}" STREQUAL "${expected}") - string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n") - endif() -endmacro() -]]) - -add_executable (exec1 empty.c) -add_library (shared1 SHARED empty.c) -add_library (static1 STATIC empty.c) - -string (APPEND GENERATE_CONTENT [[ - -check_value ("TARGET_OUTPUT_NAME executable default" "$<TARGET_OUTPUT_NAME:exec1>" "exec1") -check_value ("TARGET_OUTPUT_NAME shared default" "$<TARGET_OUTPUT_NAME:shared1>" "shared1") -check_value ("TARGET_LINKER_OUTPUT_NAME shared linker default" "$<TARGET_LINKER_OUTPUT_NAME:shared1>" "shared1") -check_value ("TARGET_OUTPUT_NAME static default" "$<TARGET_OUTPUT_NAME:static1>" "static1") -check_value ("TARGET_LINKER_OUTPUT_NAME static linker default" "$<TARGET_LINKER_OUTPUT_NAME:static1>" "static1") -]]) -if (CMAKE_C_LINKER_SUPPORTS_PDB) - string(APPEND GENERATE_CONTENT [[ -check_value ("TARGET_PDB_OUTPUT_NAME executable PDB default" "$<TARGET_PDB_OUTPUT_NAME:exec1>" "exec1") -check_value ("TARGET_PDB_OUTPUT_NAME shared PDB default" "$<TARGET_PDB_OUTPUT_NAME:shared1>" "shared1") -]]) -endif() - - -add_executable (exec2 empty.c) -set_property (TARGET exec2 PROPERTY OUTPUT_NAME exec2_custom) -add_library (shared2 SHARED empty.c) -set_property (TARGET shared2 PROPERTY OUTPUT_NAME shared2_custom) -add_library (static2 STATIC empty.c) -set_property (TARGET static2 PROPERTY OUTPUT_NAME static2_custom) - -string (APPEND GENERATE_CONTENT [[ - -check_value ("TARGET_OUTPUT_NAME executable custom" "$<TARGET_OUTPUT_NAME:exec2>" "exec2_custom") -check_value ("TARGET_OUTPUT_NAME shared custom" "$<TARGET_OUTPUT_NAME:shared2>" "shared2_custom") -check_value ("TARGET_LINKER_OUTPUT_NAME shared linker custom" "$<TARGET_LINKER_OUTPUT_NAME:shared2>" "shared2_custom") -check_value ("TARGET_OUTPUT_NAME static custom" "$<TARGET_OUTPUT_NAME:static2>" "static2_custom") -check_value ("TARGET_LINKER_OUTPUT_NAME static linker custom" "$<TARGET_LINKER_OUTPUT_NAME:static2>" "static2_custom") -]]) -if (CMAKE_C_LINKER_SUPPORTS_PDB) - string (APPEND GENERATE_CONTENT [[ -check_value ("TARGET_PDB_OUTPUT_NAME executable PDB custom" "$<TARGET_PDB_OUTPUT_NAME:exec2>" "exec2_custom") -check_value ("TARGET_PDB_OUTPUT_NAME shared PDB custom" "$<TARGET_PDB_OUTPUT_NAME:shared2>" "shared2_custom") - ]]) -endif() - -add_executable (exec3 empty.c) -set_property (TARGET exec3 PROPERTY RUNTIME_OUTPUT_NAME exec3_runtime) -set_property (TARGET exec3 PROPERTY LIBRARY_OUTPUT_NAME exec3_library) -set_property (TARGET exec3 PROPERTY ARCHIVE_OUTPUT_NAME exec3_archive) -set_property (TARGET exec3 PROPERTY PDB_NAME exec3_pdb) -add_library (shared3 SHARED empty.c) -set_property (TARGET shared3 PROPERTY RUNTIME_OUTPUT_NAME shared3_runtime) -set_property (TARGET shared3 PROPERTY LIBRARY_OUTPUT_NAME shared3_library) -set_property (TARGET shared3 PROPERTY ARCHIVE_OUTPUT_NAME shared3_archive) -set_property (TARGET shared3 PROPERTY PDB_NAME shared3_pdb) -add_library (static3 STATIC empty.c) -set_property (TARGET static3 PROPERTY RUNTIME_OUTPUT_NAME static3_runtime) -set_property (TARGET static3 PROPERTY LIBRARY_OUTPUT_NAME static3_library) -set_property (TARGET static3 PROPERTY ARCHIVE_OUTPUT_NAME static3_archive) -set_property (TARGET static3 PROPERTY PDB_NAME static3_pdb) - -string (APPEND GENERATE_CONTENT [[ - -check_value ("TARGET_OUTPUT_NAME executable all properties" "$<TARGET_OUTPUT_NAME:exec3>" "exec3_runtime") -check_value ("TARGET_OUTPUT_NAME shared all properties" "$<TARGET_OUTPUT_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_runtime,shared3_library>") -check_value ("TARGET_LINKER_OUTPUT_NAME shared linker all properties" "$<TARGET_LINKER_OUTPUT_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_archive,shared3_library>") -check_value ("TARGET_OUTPUT_NAME static all properties" "$<TARGET_OUTPUT_NAME:static3>" "static3_archive") -check_value ("TARGET_LINKER_OUTPUT_NAME static linker all properties" "$<TARGET_LINKER_OUTPUT_NAME:static3>" "static3_archive") -]]) -if (CMAKE_C_LINKER_SUPPORTS_PDB) - string (APPEND GENERATE_CONTENT [[ -check_value ("TARGET_PDB_OUTPUT_NAME executable PDB all properties" "$<TARGET_PDB_OUTPUT_NAME:exec3>" "exec3_pdb") -check_value ("TARGET_PDB_OUTPUT_NAME shared PDB all properties" "$<TARGET_PDB_OUTPUT_NAME:shared3>" "shared3_pdb") -]]) -endif() - - -unset(GENERATE_CONDITION) -get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(_isMultiConfig) - list(GET CMAKE_CONFIGURATION_TYPES 0 FIRST_CONFIG) - set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>) -endif() - -file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_OUTPUT_NAME-generated.cmake" - CONTENT "${GENERATE_CONTENT}" ${GENERATE_CONDITION}) diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake new file mode 100644 index 0000000..996d2d4 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake @@ -0,0 +1,7 @@ +file(STRINGS ${RunCMake_TEST_BINARY_DIR}/test.txt TEST_TXT ENCODING UTF-8) + +list(GET TEST_TXT 0 PDB_FILE_BASE_NAME) + +if(NOT PDB_FILE_BASE_NAME MATCHES "empty") + set(RunCMake_TEST_FAILED "unexpected PDB_FILE_BASE_NAME [${PDB_FILE_BASE_NAME}]") +endif() diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_OUTPUT_NAME.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake index ba70b43..cc53bdf 100644 --- a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_OUTPUT_NAME.cmake +++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake @@ -11,6 +11,6 @@ endif() file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt" - CONTENT "$<TARGET_PDB_OUTPUT_NAME:empty>" + CONTENT "$<TARGET_PDB_FILE_BASE_NAME:empty>" ${GENERATE_CONDITION} ) diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_OUTPUT_NAME-check.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_OUTPUT_NAME-check.cmake deleted file mode 100644 index 8d1103e..0000000 --- a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_OUTPUT_NAME-check.cmake +++ /dev/null @@ -1,7 +0,0 @@ -file(STRINGS ${RunCMake_TEST_BINARY_DIR}/test.txt TEST_TXT ENCODING UTF-8) - -list(GET TEST_TXT 0 PDB_OUTPUT_NAME) - -if(NOT PDB_OUTPUT_NAME MATCHES "empty") - set(RunCMake_TEST_FAILED "unexpected PDB_OUTPUT_NAME [${PDB_OUTPUT_NAME}]") -endif() diff --git a/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake b/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake index 763478c..d8138b8 100644 --- a/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake +++ b/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake @@ -1 +1,2 @@ +message("CMAKE_VS_PLATFORM_NAME_DEFAULT is \"${CMAKE_VS_PLATFORM_NAME_DEFAULT}\"") set(CMAKE_GENERATOR_PLATFORM "Test Platform") diff --git a/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt index b9bb3b2..6867790 100644 --- a/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt +++ b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt @@ -1,3 +1,4 @@ +CMAKE_VS_PLATFORM_NAME_DEFAULT is "[^"]+" CMake Error at TestPlatformToolchain.cmake:[0-9]+ \(message\): CMAKE_GENERATOR_PLATFORM is "Test Platform" as expected. Call Stack \(most recent call first\): diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt new file mode 100644 index 0000000..803058d --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt @@ -0,0 +1,2 @@ +^CMake Error in CMakeLists.txt: + MSVC_RUNTIME_LIBRARY value 'BogusValue' not known for this C compiler.$ diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake new file mode 100644 index 0000000..c3ea2fd --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0091 NEW) +include(CMP0091-common.cmake) diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake new file mode 100644 index 0000000..734cc9f --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0091 OLD) +include(CMP0091-common.cmake) diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake new file mode 100644 index 0000000..26f86a0 --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake @@ -0,0 +1,2 @@ + +include(CMP0091-common.cmake) diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake new file mode 100644 index 0000000..7827d2a --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake @@ -0,0 +1,37 @@ +enable_language(C) + +cmake_policy(GET CMP0091 cmp0091) +if(cmp0091 STREQUAL "NEW") + if(NOT CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT) + message(SEND_ERROR "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT not set under NEW behavior") + endif() +else() + if(CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT) + message(SEND_ERROR "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT is set under OLD behavior") + endif() +endif() + +if(CMAKE_C_COMPILER_ID STREQUAL "MSVC") + if(CMAKE_C_FLAGS_DEBUG MATCHES "[/-]MDd( |$)") + set(have_MDd 1) + else() + set(have_MDd 0) + endif() + if(CMAKE_C_FLAGS_RELEASE MATCHES "[/-]MD( |$)") + set(have_MD 1) + else() + set(have_MD 0) + endif() + if(cmp0091 STREQUAL "NEW") + if(have_MDd OR have_MD) + message(SEND_ERROR "Have a -MD* flag under NEW behavior.") + endif() + else() + if(NOT (have_MDd AND have_MD)) + message(SEND_ERROR "Do not have -MD* flags under OLD behavior.") + endif() + endif() +endif() + +set(CMAKE_MSVC_RUNTIME_LIBRARY BogusValue) +add_library(foo empty.c) diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt b/Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt new file mode 100644 index 0000000..3e470a2 --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.14) +project(${RunCMake_TEST} NONE) +include(${RunCMake_TEST}.cmake) diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake new file mode 100644 index 0000000..fad18da --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake @@ -0,0 +1,5 @@ +include(RunCMake) + +run_cmake(CMP0091-WARN) +run_cmake(CMP0091-OLD) +run_cmake(CMP0091-NEW) diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/empty.c b/Tests/RunCMake/MSVCRuntimeLibrary/empty.c new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/MSVCRuntimeLibrary/empty.c diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake new file mode 100644 index 0000000..15c52d2 --- /dev/null +++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0092 NEW) +include(CMP0092-common.cmake) diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake new file mode 100644 index 0000000..ea75445 --- /dev/null +++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0092 OLD) +include(CMP0092-common.cmake) diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake new file mode 100644 index 0000000..45e183f --- /dev/null +++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake @@ -0,0 +1,2 @@ + +include(CMP0092-common.cmake) diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake new file mode 100644 index 0000000..87d7f67 --- /dev/null +++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake @@ -0,0 +1,12 @@ +enable_language(C) + +cmake_policy(GET CMP0092 cmp0092) +if(cmp0092 STREQUAL "NEW") + if("${CMAKE_C_FLAGS}" MATCHES "([/-]W[0-9])") + message(SEND_ERROR "CMAKE_C_FLAGS has '${CMAKE_MATCH_1}' under NEW behavior") + endif() +else() + if(NOT " ${CMAKE_C_FLAGS} " MATCHES " /W3 ") + message(SEND_ERROR "CMAKE_C_FLAGS does not have '/W3' under OLD behavior") + endif() +endif() diff --git a/Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt b/Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt new file mode 100644 index 0000000..3e470a2 --- /dev/null +++ b/Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.14) +project(${RunCMake_TEST} NONE) +include(${RunCMake_TEST}.cmake) diff --git a/Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake b/Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake new file mode 100644 index 0000000..7ce448d --- /dev/null +++ b/Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake @@ -0,0 +1,5 @@ +include(RunCMake) + +run_cmake(CMP0092-WARN) +run_cmake(CMP0092-OLD) +run_cmake(CMP0092-NEW) diff --git a/Tests/RunCMake/ObjectLibrary/BadSourceExpression3-stderr.txt b/Tests/RunCMake/ObjectLibrary/BadSourceExpression3-stderr.txt index 838b3d8..4dbd861 100644 --- a/Tests/RunCMake/ObjectLibrary/BadSourceExpression3-stderr.txt +++ b/Tests/RunCMake/ObjectLibrary/BadSourceExpression3-stderr.txt @@ -3,6 +3,7 @@ CMake Error at BadSourceExpression3.cmake:2 \(add_library\): \$<TARGET_OBJECTS:NotObjLib> - Objects of target "NotObjLib" referenced but is not an OBJECT library. + Objects of target "NotObjLib" referenced but is not an allowed library + types \(EXECUTABLE, STATIC, SHARED, MODULE, OBJECT\). Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/BadSourceExpression3.cmake b/Tests/RunCMake/ObjectLibrary/BadSourceExpression3.cmake index c3d9a62..4e07ea6 100644 --- a/Tests/RunCMake/ObjectLibrary/BadSourceExpression3.cmake +++ b/Tests/RunCMake/ObjectLibrary/BadSourceExpression3.cmake @@ -1,2 +1,2 @@ -add_library(NotObjLib STATIC a.c) +add_library(NotObjLib INTERFACE) add_library(A STATIC a.c $<TARGET_OBJECTS:NotObjLib>) diff --git a/Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake b/Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake new file mode 100644 index 0000000..0c85c72 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake @@ -0,0 +1,32 @@ +add_library(StaticLib STATIC a.c) + +add_custom_command(TARGET StaticLib POST_BUILD + VERBATIM + COMMAND ${CMAKE_COMMAND} + "-DTARGET_OBJECTS=$<TARGET_OBJECTS:StaticLib>" + -DEXPECTED_NUM_OBJECTFILES=2 + -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" + ) + +add_library(SharedLib SHARED a.c b.c) +target_compile_definitions(SharedLib PRIVATE REQUIRED) + +add_custom_command(TARGET SharedLib POST_BUILD + VERBATIM + COMMAND ${CMAKE_COMMAND} + "-DTARGET_OBJECTS:STRING=$<TARGET_OBJECTS:SharedLib>" + -DEXPECTED_NUM_OBJECTFILES=2 + -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" + ) + +add_executable(ExecObjs a.c b.c exe.c) +target_compile_definitions(ExecObjs PRIVATE REQUIRED) + +add_custom_target(check_exec_objs ALL + VERBATIM + COMMAND ${CMAKE_COMMAND} + "-DTARGET_OBJECTS=$<TARGET_OBJECTS:ExecObjs>" + -DEXPECTED_NUM_OBJECTFILES=3 + -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake" + DEPENDS ExecObjs + ) diff --git a/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake b/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake index 6ca33b8..5ec4018 100644 --- a/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake +++ b/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake @@ -37,6 +37,10 @@ function (run_object_lib_build2 name) run_cmake_command(${name}-build ${CMAKE_COMMAND} --build .) endfunction () +if(NOT (RunCMake_GENERATOR STREQUAL "Xcode" AND "$ENV{CMAKE_OSX_ARCHITECTURES}" MATCHES "[;$]")) + run_object_lib_build(CheckTargetObjects) +endif() + run_object_lib_build(LinkObjLHSShared) run_object_lib_build(LinkObjLHSStatic) run_object_lib_build(LinkObjRHSShared) @@ -54,6 +58,7 @@ run_cmake(PostBuild) run_cmake(PreBuild) run_cmake(PreLink) + function(run_Dependencies) set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/Dependencies-build) set(RunCMake_TEST_NO_CLEAN 1) diff --git a/Tests/RunCMake/ObjectLibrary/check_object_files.cmake b/Tests/RunCMake/ObjectLibrary/check_object_files.cmake new file mode 100644 index 0000000..3c34229 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/check_object_files.cmake @@ -0,0 +1,17 @@ + +if (NOT TARGET_OBJECTS) + message(SEND_ERROR "Object not passed as -DTARGET_OBJECTS") +endif() + +foreach(objlib_file IN LISTS objects) + message(STATUS "objlib_file: =${objlib_file}=") + + set(file_exists False) + if (EXISTS "${objlib_file}") + set(file_exists True) + endif() + + if (NOT file_exists) + message(SEND_ERROR "File \"${objlib_file}\" does not exist!${tried}") + endif() +endforeach() diff --git a/Tests/RunCMake/TargetObjects/NotObjlibTarget-stderr.txt b/Tests/RunCMake/TargetObjects/NotObjlibTarget-stderr.txt index a66794c..77c4afd 100644 --- a/Tests/RunCMake/TargetObjects/NotObjlibTarget-stderr.txt +++ b/Tests/RunCMake/TargetObjects/NotObjlibTarget-stderr.txt @@ -1,8 +1,9 @@ -CMake Error at NotObjlibTarget.cmake:3 \(file\): +CMake Error at NotObjlibTarget.cmake:[0-9]+ \(file\): Error evaluating generator expression: - \$<TARGET_OBJECTS:StaticLib> + \$<TARGET_OBJECTS:IFaceLib> - Objects of target "StaticLib" referenced but is not an OBJECT library. + Objects of target "IFaceLib" referenced but is not an allowed library types + \(EXECUTABLE, STATIC, SHARED, MODULE, OBJECT\). Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake b/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake index 3bb3e37..9fec369 100644 --- a/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake +++ b/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake @@ -1,3 +1,3 @@ -add_library(StaticLib empty.cpp) +add_library(IFaceLib INTERFACE ) -file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_output CONTENT $<TARGET_OBJECTS:StaticLib>) +file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_output CONTENT $<TARGET_OBJECTS:IFaceLib>) diff --git a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake index df253a9..0ac589d 100644 --- a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake +++ b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake @@ -2,6 +2,7 @@ include(RunCMake) run_cmake(VsCSharpCompilerOpts) run_cmake(ExplicitCMakeLists) +run_cmake(RuntimeLibrary) run_cmake(SourceGroupCMakeLists) run_cmake(VsConfigurationType) @@ -18,3 +19,4 @@ run_cmake(VsCSharpDeployFiles) run_cmake(VSCSharpDefines) run_cmake(VsSdkDirectories) run_cmake(VsGlobals) +run_cmake(VsProjectImport) diff --git a/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake b/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake new file mode 100644 index 0000000..689b35f --- /dev/null +++ b/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake @@ -0,0 +1,36 @@ +macro(RuntimeLibrary_check tgt rtl_expect) + set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${tgt}.vcxproj") + if(NOT EXISTS "${vcProjectFile}") + set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not exist.") + return() + endif() + + set(HAVE_Runtimelibrary 0) + + file(STRINGS "${vcProjectFile}" lines) + foreach(line IN LISTS lines) + if(line MATCHES "^ *<RuntimeLibrary>([^<>]+)</RuntimeLibrary>") + set(rtl_actual "${CMAKE_MATCH_1}") + if(NOT "${rtl_actual}" STREQUAL "${rtl_expect}") + set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj has RuntimeLibrary '${rtl_actual}', not '${rtl_expect}'.") + return() + endif() + set(HAVE_Runtimelibrary 1) + break() + endif() + endforeach() + + if(NOT HAVE_Runtimelibrary AND NOT "${rtl_expect}" STREQUAL "") + set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not have a RuntimeLibrary field.") + return() + endif() +endmacro() + +RuntimeLibrary_check(default-C MultiThreadedDebugDLL) +RuntimeLibrary_check(default-CXX MultiThreadedDebugDLL) +RuntimeLibrary_check(empty-C "") +RuntimeLibrary_check(empty-CXX "") +RuntimeLibrary_check(MTd-C MultiThreadedDebug) +RuntimeLibrary_check(MTd-CXX MultiThreadedDebug) +RuntimeLibrary_check(MT-C MultiThreaded) +RuntimeLibrary_check(MT-CXX MultiThreaded) diff --git a/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake b/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake new file mode 100644 index 0000000..d7787c8 --- /dev/null +++ b/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake @@ -0,0 +1,20 @@ +set(CMAKE_CONFIGURATION_TYPES Debug) +cmake_policy(SET CMP0091 NEW) +enable_language(C) +enable_language(CXX) + +add_library(default-C empty.c) +add_library(default-CXX empty.cxx) + +set(CMAKE_MSVC_RUNTIME_LIBRARY "") +add_library(empty-C empty.c) +add_library(empty-CXX empty.cxx) + +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDebug") +add_library(MTd-C empty.c) +add_library(MTd-CXX empty.cxx) + +add_library(MT-C empty.c) +set_property(TARGET MT-C PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded") +add_library(MT-CXX empty.cxx) +set_property(TARGET MT-CXX PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded") diff --git a/Tests/RunCMake/VS10Project/VsProjectImport-check.cmake b/Tests/RunCMake/VS10Project/VsProjectImport-check.cmake new file mode 100644 index 0000000..e438bf4 --- /dev/null +++ b/Tests/RunCMake/VS10Project/VsProjectImport-check.cmake @@ -0,0 +1,28 @@ +set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj") +if(NOT EXISTS "${vcProjectFile}") + set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.") + return() +endif() + +set(test1Import "path\\\\to\\\\nuget_packages\\\\Foo.1.0.0\\\\build\\\\Foo.props") +set(test2Import "path\\\\to\\\\nuget_packages\\\\Bar.1.0.0\\\\build\\\\Bar.props") + +set(import1Found FALSE) +set(import2Found FALSE) + +file(STRINGS "${vcProjectFile}" lines) + +foreach(i 1 2) + set(testImport "${test${i}Import}") + foreach(line IN LISTS lines) + if(line MATCHES "^ *<Import Project=\".*${test1Import}\" />$") + message(STATUS "foo.vcxproj is using project import ${testImport}") + set(import${i}Found TRUE) + endif() + endforeach() +endforeach() + +if(NOT import1Found OR NOT import2Found) + set(RunCMake_TEST_FAILED "Imported project not found.") + return() +endif() diff --git a/Tests/RunCMake/VS10Project/VsProjectImport.cmake b/Tests/RunCMake/VS10Project/VsProjectImport.cmake new file mode 100644 index 0000000..70bdded --- /dev/null +++ b/Tests/RunCMake/VS10Project/VsProjectImport.cmake @@ -0,0 +1,11 @@ +enable_language(CXX) +add_library(foo foo.cpp) + +set(test1Import "path/to/nuget_packages/Foo.1.0.0/build/Foo.props") +set(test2Import "path/to/nuget_packages/Bar.1.0.0/build/Bar.props") + +set_property(TARGET foo PROPERTY + VS_PROJECT_IMPORT + ${test1Import} + ${test2Import} + ) diff --git a/Tests/RunCMake/VS10Project/empty.c b/Tests/RunCMake/VS10Project/empty.c new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/VS10Project/empty.c diff --git a/Tests/RunCMake/VS10Project/empty.cxx b/Tests/RunCMake/VS10Project/empty.cxx new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/Tests/RunCMake/VS10Project/empty.cxx diff --git a/Tests/RunCMake/ctest_update/CMakeLists.txt.in b/Tests/RunCMake/ctest_update/CMakeLists.txt.in new file mode 100644 index 0000000..ecf0e54 --- /dev/null +++ b/Tests/RunCMake/ctest_update/CMakeLists.txt.in @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.1) +project(CTestTest@CASE_NAME@ NONE) +include(CTest) +@CASE_CMAKELISTS_SUFFIX_CODE@ diff --git a/Tests/RunCMake/ctest_update/RunCMakeTest.cmake b/Tests/RunCMake/ctest_update/RunCMakeTest.cmake new file mode 100644 index 0000000..0e1748f --- /dev/null +++ b/Tests/RunCMake/ctest_update/RunCMakeTest.cmake @@ -0,0 +1,17 @@ +include(RunCTest) +set(CASE_CTEST_UPDATE_ARGS "") +function(run_ctest_update CASE_NAME) + set(CASE_CTEST_UPDATE_ARGS "${ARGN}") + run_ctest(${CASE_NAME}) +endfunction() + +run_ctest_update(TestQuiet QUIET) + +function(run_TestChangeId) + set(CASE_TEST_PREFIX_CODE [[ + set(CTEST_CHANGE_ID "<>1") + ]]) + + run_ctest(TestChangeId) +endfunction() +run_TestChangeId() diff --git a/Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake b/Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake new file mode 100644 index 0000000..9269fbc --- /dev/null +++ b/Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake @@ -0,0 +1,12 @@ +file(GLOB update_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Update.xml") +if(update_xml_file) + file(READ "${update_xml_file}" update_xml LIMIT 4096) + if(NOT update_xml MATCHES [[ChangeId="<>1"]]) + string(REPLACE "\n" "\n " update_xml " ${update_xml}") + set(RunCMake_TEST_FAILED + "Update.xml does not have expected ChangeId:\n${update_xml}" + ) + endif() +else() + set(RunCMake_TEST_FAILED "Update.xml not found") +endif() diff --git a/Tests/RunCMake/ctest_update/test.cmake.in b/Tests/RunCMake/ctest_update/test.cmake.in new file mode 100644 index 0000000..abbef74 --- /dev/null +++ b/Tests/RunCMake/ctest_update/test.cmake.in @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.1) +@CASE_TEST_PREFIX_CODE@ + +set(CTEST_SITE "test-site") +set(CTEST_BUILD_NAME "test-build-name") +set(CTEST_SOURCE_DIRECTORY "@RunCMake_BINARY_DIR@/@CASE_NAME@") +set(CTEST_BINARY_DIRECTORY "@RunCMake_BINARY_DIR@/@CASE_NAME@-build") +set(CTEST_CMAKE_GENERATOR "@RunCMake_GENERATOR@") +set(CTEST_CMAKE_GENERATOR_PLATFORM "@RunCMake_GENERATOR_PLATFORM@") +set(CTEST_CMAKE_GENERATOR_TOOLSET "@RunCMake_GENERATOR_TOOLSET@") +set(CTEST_BUILD_CONFIGURATION "$ENV{CMAKE_CONFIG_TYPE}") +set(CTEST_UPDATE_COMMAND "@GIT_EXECUTABLE@") + +set(ctest_test_args "@CASE_CTEST_UPDATE_ARGS@") +ctest_start(Experimental) +ctest_update(${ctest_update_args}) diff --git a/Tests/RunCMake/execute_process/EchoCommand-result.txt b/Tests/RunCMake/execute_process/EchoCommand-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/execute_process/EchoCommand-stderr.txt b/Tests/RunCMake/execute_process/EchoCommand-stderr.txt new file mode 100644 index 0000000..f10ece8 --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand-stderr.txt @@ -0,0 +1,5 @@ +.*cmake.*-E' 'echo' '-- 2 COMMAND_ECHO STDERR' +.*cmake.*-E' 'echo' '-- 4 COMMAND_ECHO STDERR' +.*cmake.*-E' 'echo' '-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR' +CMake Error at .*EchoCommand.cmake:.* \(execute_process\): + CMAKE_EXECUTE_PROCESS_COMMAND_ECHO set to 'BAD' expected STDERR|STDOUT|NONE$ diff --git a/Tests/RunCMake/execute_process/EchoCommand-stdout.txt b/Tests/RunCMake/execute_process/EchoCommand-stdout.txt new file mode 100644 index 0000000..0954b3b --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand-stdout.txt @@ -0,0 +1,12 @@ +.*cmake.*-E' 'echo' '-- 1 COMMAND_ECHO STDOUT' +-- 1 COMMAND_ECHO STDOUT +-- 2 COMMAND_ECHO STDERR +.*cmake.* '-E' 'echo' '-- 3 COMMAND_ECHO STDOUT' +-- 3 COMMAND_ECHO STDOUT +-- 4 COMMAND_ECHO STDERR +.*cmake.* '-E' 'echo' '-- 5 COMMAND_ECHO STDOUT' +-- 5 COMMAND_ECHO STDOUT +-- 6 COMMAND_ECHO NONE +.*cmake.* '-E' 'echo' '-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT' +-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT +-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR$ diff --git a/Tests/RunCMake/execute_process/EchoCommand.cmake b/Tests/RunCMake/execute_process/EchoCommand.cmake new file mode 100644 index 0000000..9c7d13d --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand.cmake @@ -0,0 +1,41 @@ +if(CHECK_ERROR_OUTPUT_LOCATION) + execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 1 COMMAND_ECHO " COMMAND_ECHO ) +endif() +# test COMMAND_ECHO STDOUT +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 1 COMMAND_ECHO STDOUT" COMMAND_ECHO STDOUT ) +# test COMMAND_ECHO STDERR +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 2 COMMAND_ECHO STDERR" COMMAND_ECHO STDERR ) +# test CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDOUT +set(CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDOUT) +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 3 COMMAND_ECHO STDOUT" ) +# test CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDERR +set(CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDERR) +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 4 COMMAND_ECHO STDERR" ) +# make sure local will override global settings +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 5 COMMAND_ECHO STDOUT" COMMAND_ECHO STDOUT ) +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 6 COMMAND_ECHO NONE" COMMAND_ECHO NONE) +# test both and make sure override works +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT" COMMAND_ECHO STDERR + COMMAND_ECHO STDOUT) +execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR" COMMAND_ECHO STDOUT + COMMAND_ECHO STDERR) + +# check for bad arguments to global and local +if(CHECK_GLOBAL) + # make sure a non STDERR or STDOUT value is an error + set(CMAKE_EXECUTE_PROCESS_COMMAND_ECHO BAD) + execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 9 - 1 CMAKE_EXECUTE_PROCESS_COMMAND_ECHO BAD" ) +else() + execute_process(COMMAND ${CMAKE_COMMAND} -E echo + "-- 9 - 2 COMMAND_ECHO BAD" COMMAND_ECHO BAD) +endif() diff --git a/Tests/RunCMake/execute_process/EchoCommand2-result.txt b/Tests/RunCMake/execute_process/EchoCommand2-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand2-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/execute_process/EchoCommand2-stderr.txt b/Tests/RunCMake/execute_process/EchoCommand2-stderr.txt new file mode 100644 index 0000000..4ae01c4 --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand2-stderr.txt @@ -0,0 +1,5 @@ +.*cmake.*-E' 'echo' '-- 2 COMMAND_ECHO STDERR' +.*cmake.*-E' 'echo' '-- 4 COMMAND_ECHO STDERR' +.*cmake.*-E' 'echo' '-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR' +CMake Error at .*EchoCommand.cmake:.* \(execute_process\): + called with 'BAD' expected STDERR|STDOUT|NONE for COMMAND_ECHO.$ diff --git a/Tests/RunCMake/execute_process/EchoCommand2-stdout.txt b/Tests/RunCMake/execute_process/EchoCommand2-stdout.txt new file mode 100644 index 0000000..0954b3b --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand2-stdout.txt @@ -0,0 +1,12 @@ +.*cmake.*-E' 'echo' '-- 1 COMMAND_ECHO STDOUT' +-- 1 COMMAND_ECHO STDOUT +-- 2 COMMAND_ECHO STDERR +.*cmake.* '-E' 'echo' '-- 3 COMMAND_ECHO STDOUT' +-- 3 COMMAND_ECHO STDOUT +-- 4 COMMAND_ECHO STDERR +.*cmake.* '-E' 'echo' '-- 5 COMMAND_ECHO STDOUT' +-- 5 COMMAND_ECHO STDOUT +-- 6 COMMAND_ECHO NONE +.*cmake.* '-E' 'echo' '-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT' +-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT +-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR$ diff --git a/Tests/RunCMake/execute_process/EchoCommand3-result.txt b/Tests/RunCMake/execute_process/EchoCommand3-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand3-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/execute_process/EchoCommand3-stderr.txt b/Tests/RunCMake/execute_process/EchoCommand3-stderr.txt new file mode 100644 index 0000000..e27f1e6 --- /dev/null +++ b/Tests/RunCMake/execute_process/EchoCommand3-stderr.txt @@ -0,0 +1,2 @@ +CMake Error at .*EchoCommand.cmake:.*\(execute_process\): + execute_process called with no value for COMMAND_ECHO. diff --git a/Tests/RunCMake/execute_process/RunCMakeTest.cmake b/Tests/RunCMake/execute_process/RunCMakeTest.cmake index cb40b40..b203aab 100644 --- a/Tests/RunCMake/execute_process/RunCMakeTest.cmake +++ b/Tests/RunCMake/execute_process/RunCMakeTest.cmake @@ -16,3 +16,11 @@ endif() if(EXIT_CODE_EXE) run_cmake_command(ExitValues ${CMAKE_COMMAND} -DEXIT_CODE_EXE=${EXIT_CODE_EXE} -P ${RunCMake_SOURCE_DIR}/ExitValues.cmake) endif() + +run_cmake_command(EchoCommand ${CMAKE_COMMAND} -DCHECK_GLOBAL=TRUE + -P ${RunCMake_SOURCE_DIR}/EchoCommand.cmake) +run_cmake_command(EchoCommand2 ${CMAKE_COMMAND} -P + ${RunCMake_SOURCE_DIR}/EchoCommand.cmake) +run_cmake_command(EchoCommand3 ${CMAKE_COMMAND} + -DCHECK_ERROR_OUTPUT_LOCATION=TRUE -P + ${RunCMake_SOURCE_DIR}/EchoCommand.cmake) diff --git a/Tests/RunCMake/message/RunCMakeTest.cmake b/Tests/RunCMake/message/RunCMakeTest.cmake index 24dad03..cecfc7f 100644 --- a/Tests/RunCMake/message/RunCMakeTest.cmake +++ b/Tests/RunCMake/message/RunCMakeTest.cmake @@ -10,3 +10,45 @@ run_cmake(warnmessage) # separately run_cmake(errormessage_deprecated) run_cmake(errormessage_dev) + +run_cmake_command( + message-loglevel-invalid + ${CMAKE_COMMAND} --loglevel=blah -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) + +# Checking various combinations of `message(...)` and log levels `WARNING` to `TRACE` +# - no CLI option -> `WARNING` to `STATUS` output +run_cmake_command( + message-loglevel-default + ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) +# - Only `WARNING` output +run_cmake_command( + message-loglevel-warning + ${CMAKE_COMMAND} --loglevel=warning -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) +# - Only `WARNING` and `NOTICE` output +run_cmake_command( + message-loglevel-notice + ${CMAKE_COMMAND} --loglevel=notice -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) +# - `WARNING` to `STATUS` output +run_cmake_command( + message-loglevel-status + ${CMAKE_COMMAND} --loglevel=status -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) +# - `WARNING` to `VERBOSE` output +run_cmake_command( + message-loglevel-verbose + ${CMAKE_COMMAND} --loglevel=verbose -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) +# - `WARNING` to `DEBUG` output +run_cmake_command( + message-loglevel-debug + ${CMAKE_COMMAND} --loglevel=debug -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) +# - `WARNING` to `TRACE` output +run_cmake_command( + message-loglevel-trace + ${CMAKE_COMMAND} --loglevel=trace -P ${RunCMake_SOURCE_DIR}/message-all-loglevels.cmake + ) diff --git a/Tests/RunCMake/message/message-all-loglevels.cmake b/Tests/RunCMake/message/message-all-loglevels.cmake new file mode 100644 index 0000000..f8d8841 --- /dev/null +++ b/Tests/RunCMake/message/message-all-loglevels.cmake @@ -0,0 +1,10 @@ +# Produce a message for everything except FATAL_ERROR and SEND_ERROR +message(DEPRECATION "Deprecation warning") +message(AUTHOR_WARNING "Author warning message") +message(WARNING "Warning message") +message("Default NOTICE message") +message(NOTICE "NOTICE message") +message(STATUS "STATUS message") +message(VERBOSE "VERBOSE message") +message(DEBUG "DEBUG message") +message(TRACE "TRACE message") diff --git a/Tests/RunCMake/message/message-loglevel-debug-stderr.txt b/Tests/RunCMake/message/message-loglevel-debug-stderr.txt new file mode 100644 index 0000000..efec736 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-debug-stderr.txt @@ -0,0 +1,12 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message ++ +Default NOTICE message +NOTICE message$ diff --git a/Tests/RunCMake/message/message-loglevel-debug-stdout.txt b/Tests/RunCMake/message/message-loglevel-debug-stdout.txt new file mode 100644 index 0000000..1452137 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-debug-stdout.txt @@ -0,0 +1,3 @@ +-- STATUS message +-- VERBOSE message +-- DEBUG message diff --git a/Tests/RunCMake/message/message-loglevel-default-stderr.txt b/Tests/RunCMake/message/message-loglevel-default-stderr.txt new file mode 100644 index 0000000..efec736 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-default-stderr.txt @@ -0,0 +1,12 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message ++ +Default NOTICE message +NOTICE message$ diff --git a/Tests/RunCMake/message/message-loglevel-default-stdout.txt b/Tests/RunCMake/message/message-loglevel-default-stdout.txt new file mode 100644 index 0000000..809f4cc --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-default-stdout.txt @@ -0,0 +1 @@ +-- STATUS message diff --git a/Tests/RunCMake/message/message-loglevel-invalid-result.txt b/Tests/RunCMake/message/message-loglevel-invalid-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-invalid-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/message/message-loglevel-invalid-stderr.txt b/Tests/RunCMake/message/message-loglevel-invalid-stderr.txt new file mode 100644 index 0000000..f54d0f8 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-invalid-stderr.txt @@ -0,0 +1 @@ +CMake Error: Invalid level specified for --loglevel diff --git a/Tests/RunCMake/message/message-loglevel-notice-stderr.txt b/Tests/RunCMake/message/message-loglevel-notice-stderr.txt new file mode 100644 index 0000000..efec736 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-notice-stderr.txt @@ -0,0 +1,12 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message ++ +Default NOTICE message +NOTICE message$ diff --git a/Tests/RunCMake/message/message-loglevel-status-stderr.txt b/Tests/RunCMake/message/message-loglevel-status-stderr.txt new file mode 100644 index 0000000..efec736 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-status-stderr.txt @@ -0,0 +1,12 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message ++ +Default NOTICE message +NOTICE message$ diff --git a/Tests/RunCMake/message/message-loglevel-status-stdout.txt b/Tests/RunCMake/message/message-loglevel-status-stdout.txt new file mode 100644 index 0000000..809f4cc --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-status-stdout.txt @@ -0,0 +1 @@ +-- STATUS message diff --git a/Tests/RunCMake/message/message-loglevel-trace-stderr.txt b/Tests/RunCMake/message/message-loglevel-trace-stderr.txt new file mode 100644 index 0000000..efec736 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-trace-stderr.txt @@ -0,0 +1,12 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message ++ +Default NOTICE message +NOTICE message$ diff --git a/Tests/RunCMake/message/message-loglevel-trace-stdout.txt b/Tests/RunCMake/message/message-loglevel-trace-stdout.txt new file mode 100644 index 0000000..1cfce6f --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-trace-stdout.txt @@ -0,0 +1,4 @@ +-- STATUS message +-- VERBOSE message +-- DEBUG message +-- TRACE message diff --git a/Tests/RunCMake/message/message-loglevel-verbose-stderr.txt b/Tests/RunCMake/message/message-loglevel-verbose-stderr.txt new file mode 100644 index 0000000..efec736 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-verbose-stderr.txt @@ -0,0 +1,12 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message ++ +Default NOTICE message +NOTICE message$ diff --git a/Tests/RunCMake/message/message-loglevel-verbose-stdout.txt b/Tests/RunCMake/message/message-loglevel-verbose-stdout.txt new file mode 100644 index 0000000..c15d43f --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-verbose-stdout.txt @@ -0,0 +1,2 @@ +-- STATUS message +-- VERBOSE message diff --git a/Tests/RunCMake/message/message-loglevel-warning-stderr.txt b/Tests/RunCMake/message/message-loglevel-warning-stderr.txt new file mode 100644 index 0000000..c721b06 --- /dev/null +++ b/Tests/RunCMake/message/message-loglevel-warning-stderr.txt @@ -0,0 +1,9 @@ +^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\): + Deprecation warning ++ +CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\): + Author warning message +This warning is for project developers\. Use -Wno-dev to suppress it\. ++ +CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\): + Warning message$ diff --git a/Tests/RunCMake/string/Repeat.cmake b/Tests/RunCMake/string/Repeat.cmake new file mode 100644 index 0000000..fc390aa --- /dev/null +++ b/Tests/RunCMake/string/Repeat.cmake @@ -0,0 +1,45 @@ +string(REPEAT "q" 4 q_out) + +if(NOT DEFINED q_out) + message(FATAL_ERROR "q_out is not defined") +endif() + +if(NOT q_out STREQUAL "qqqq") + message(FATAL_ERROR "unexpected result") +endif() + +string(REPEAT "1234" 0 zero_out) + +if(NOT DEFINED zero_out) + message(FATAL_ERROR "zero_out is not defined") +endif() + +if(NOT zero_out STREQUAL "") + message(FATAL_ERROR "unexpected result") +endif() + +unset(zero_out) + +string(REPEAT "" 100 zero_out) + +if(NOT DEFINED zero_out) + message(FATAL_ERROR "zero_out is not defined") +endif() + +if(NOT zero_out STREQUAL "") + message(FATAL_ERROR "unexpected result") +endif() + +string(REPEAT "1" 1 one_out) + +if(NOT one_out STREQUAL "1") + message(FATAL_ERROR "unexpected result") +endif() + +unset(one_out) + +string(REPEAT "one" 1 one_out) + +if(NOT one_out STREQUAL "one") + message(FATAL_ERROR "unexpected result") +endif() diff --git a/Tests/RunCMake/string/RepeatNegativeCount-result.txt b/Tests/RunCMake/string/RepeatNegativeCount-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/string/RepeatNegativeCount-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/string/RepeatNegativeCount-stderr.txt b/Tests/RunCMake/string/RepeatNegativeCount-stderr.txt new file mode 100644 index 0000000..bbd498e --- /dev/null +++ b/Tests/RunCMake/string/RepeatNegativeCount-stderr.txt @@ -0,0 +1,4 @@ +CMake Error at RepeatNegativeCount.cmake:[0-9]+ \(string\): + repeat count is not a positive number. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/string/RepeatNegativeCount.cmake b/Tests/RunCMake/string/RepeatNegativeCount.cmake new file mode 100644 index 0000000..769e7c0 --- /dev/null +++ b/Tests/RunCMake/string/RepeatNegativeCount.cmake @@ -0,0 +1 @@ +string(REPEAT "blah" -1 out) diff --git a/Tests/RunCMake/string/RepeatNoArgs-result.txt b/Tests/RunCMake/string/RepeatNoArgs-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/string/RepeatNoArgs-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/string/RepeatNoArgs-stderr.txt b/Tests/RunCMake/string/RepeatNoArgs-stderr.txt new file mode 100644 index 0000000..5abcb3b --- /dev/null +++ b/Tests/RunCMake/string/RepeatNoArgs-stderr.txt @@ -0,0 +1,4 @@ +CMake Error at RepeatNoArgs.cmake:[0-9]+ \(string\): + sub-command REPEAT requires three arguments. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/string/RepeatNoArgs.cmake b/Tests/RunCMake/string/RepeatNoArgs.cmake new file mode 100644 index 0000000..e327e99 --- /dev/null +++ b/Tests/RunCMake/string/RepeatNoArgs.cmake @@ -0,0 +1 @@ +string(REPEAT) diff --git a/Tests/RunCMake/string/RunCMakeTest.cmake b/Tests/RunCMake/string/RunCMakeTest.cmake index 211337a..c432b4e 100644 --- a/Tests/RunCMake/string/RunCMakeTest.cmake +++ b/Tests/RunCMake/string/RunCMakeTest.cmake @@ -33,3 +33,7 @@ run_cmake(UTF-16BE) run_cmake(UTF-16LE) run_cmake(UTF-32BE) run_cmake(UTF-32LE) + +run_cmake(Repeat) +run_cmake(RepeatNoArgs) +run_cmake(RepeatNegativeCount) diff --git a/Tests/SourceGroups/CMakeLists.txt b/Tests/SourceGroups/CMakeLists.txt index 813774d..a5740bb 100644 --- a/Tests/SourceGroups/CMakeLists.txt +++ b/Tests/SourceGroups/CMakeLists.txt @@ -42,8 +42,16 @@ set(tree_files_with_prefix ${root}/tree_prefix_foo.c set(tree_files_with_empty_prefix ${root}/tree_empty_prefix_foo.c tree_empty_prefix_bar.c) +set(tree_files_which_are_actually_directories ${root} + ${root}/ + ${root}/sub1 + ${root}/sub1/) + source_group(TREE ${root} FILES ${tree_files_without_prefix}) +# Should not crash and not add any files - just silently ignore the directories +source_group(TREE ${root} FILES ${tree_files_which_are_actually_directories}) + source_group(FILES ${tree_files_with_prefix} PREFIX tree_root/subgroup TREE ${root}) source_group(PREFIX "" FILES ${tree_files_with_empty_prefix} TREE ${root}) @@ -685,6 +685,7 @@ cmake_kwsys_config_replace_string () 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; + s/@KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP@/${KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP}/g; }" "${INFILE}" >> "${OUTFILE}${_tmp}" if [ -f "${OUTFILE}${_tmp}" ]; then if "${_diff}" "${OUTFILE}" "${OUTFILE}${_tmp}" > /dev/null 2> /dev/null ; then @@ -1217,6 +1218,7 @@ KWSYS_CXX_HAS_UNSETENV=0 KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H=0 KWSYS_CXX_HAS_UTIMENSAT=0 KWSYS_CXX_HAS_UTIMES=0 +KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP=1 if cmake_try_run "${cmake_cxx_compiler}" \ "${cmake_cxx_flags} -DTEST_KWSYS_CXX_HAS_SETENV" \ |