From f621e7fa5df8d35cc379f9f7825f3d75b8489876 Mon Sep 17 00:00:00 2001 From: Brad King Date: Fri, 5 Apr 2019 17:48:06 -0400 Subject: VS: Fix Fortran runtime library flag map special case for '-' options --- Source/cmVisualStudioGeneratorOptions.cxx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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; } -- cgit v0.12 From fb3370b6a1681190ffd8daf63975c44ce8fc1c49 Mon Sep 17 00:00:00 2001 From: Brad King Date: Wed, 10 Apr 2019 13:38:41 -0400 Subject: MSVC: Add abstraction for runtime library selection Replace our hard-coded defaults for `/MD` and `/MDd` with a first-class abstraction to select the runtime library from an enumeration of logical names. We've long hesitated to do this because the idea of "runtime library selection" touches on related concepts on several platforms. Avoid that scope creep by simply defining an abstraction that applies only when targeting the MSVC ABI on Windows. Removing the old default flags requires a policy because existing projects may rely on string processing to edit them and choose a runtime library under the old behavior. Add policy CMP0091 to provide compatibility. Fixes: #19108 --- Help/command/try_compile.rst | 1 + Help/manual/cmake-policies.7.rst | 1 + Help/manual/cmake-properties.7.rst | 1 + Help/manual/cmake-variables.7.rst | 1 + Help/policy/CMP0091.rst | 47 ++++++++++++++++++++ Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt | 15 +++++++ Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst | 26 +++++++++++ Help/release/dev/msvc-runtime-library.rst | 7 +++ Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst | 27 ++++++++++++ Modules/Platform/Windows-Intel-Fortran.cmake | 30 ++++++++++++- Modules/Platform/Windows-MSVC.cmake | 38 ++++++++++++---- Source/cmCoreTryCompile.cxx | 11 +++++ Source/cmLocalGenerator.cxx | 37 +++++++++++++++- Source/cmPolicies.h | 5 ++- Source/cmTarget.cxx | 1 + Tests/CMakeLists.txt | 4 ++ Tests/MSVCRuntimeLibrary/CMakeLists.txt | 49 +++++++++++++++++++++ Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt | 50 ++++++++++++++++++++++ Tests/MSVCRuntimeLibrary/Fortran/verify.F90 | 1 + Tests/MSVCRuntimeLibrary/verify.c | 1 + Tests/MSVCRuntimeLibrary/verify.cxx | 1 + Tests/MSVCRuntimeLibrary/verify.h | 29 +++++++++++++ Tests/RunCMake/CMakeLists.txt | 3 ++ .../MSVCRuntimeLibrary/CMP0091-NEW-result.txt | 1 + .../MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt | 2 + .../RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake | 2 + .../RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake | 2 + .../RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake | 2 + .../MSVCRuntimeLibrary/CMP0091-common.cmake | 37 ++++++++++++++++ Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt | 3 ++ .../RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake | 5 +++ Tests/RunCMake/MSVCRuntimeLibrary/empty.c | 0 Tests/RunCMake/VS10Project/RunCMakeTest.cmake | 1 + .../VS10Project/RuntimeLibrary-check.cmake | 34 +++++++++++++++ Tests/RunCMake/VS10Project/RuntimeLibrary.cmake | 16 +++++++ Tests/RunCMake/VS10Project/empty.c | 0 Tests/RunCMake/VS10Project/empty.cxx | 0 37 files changed, 478 insertions(+), 13 deletions(-) create mode 100644 Help/policy/CMP0091.rst create mode 100644 Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt create mode 100644 Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst create mode 100644 Help/release/dev/msvc-runtime-library.rst create mode 100644 Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst create mode 100644 Tests/MSVCRuntimeLibrary/CMakeLists.txt create mode 100644 Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt create mode 100644 Tests/MSVCRuntimeLibrary/Fortran/verify.F90 create mode 100644 Tests/MSVCRuntimeLibrary/verify.c create mode 100644 Tests/MSVCRuntimeLibrary/verify.cxx create mode 100644 Tests/MSVCRuntimeLibrary/verify.h create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake create mode 100644 Tests/RunCMake/MSVCRuntimeLibrary/empty.c create mode 100644 Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake create mode 100644 Tests/RunCMake/VS10Project/RuntimeLibrary.cmake create mode 100644 Tests/RunCMake/VS10Project/empty.c create mode 100644 Tests/RunCMake/VS10Project/empty.cxx 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/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst index e89ea3da..043fb5c 100644 --- a/Help/manual/cmake-policies.7.rst +++ b/Help/manual/cmake-policies.7.rst @@ -57,6 +57,7 @@ Policies Introduced by CMake 3.15 .. toctree:: :maxdepth: 1 + CMP0091: MSVC runtime library flags are selected by an abstraction. CMP0090: export(PACKAGE) does not populate package registry by default. CMP0089: Compiler id for IBM Clang-based XL compilers is now XLClang. diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst index 4d4b9ff..3da9144 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 diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst index 18dd9d7..22e8add 100644 --- a/Help/manual/cmake-variables.7.rst +++ b/Help/manual/cmake-variables.7.rst @@ -386,6 +386,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/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__FLAGS_` 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__FLAGS_` 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__FLAGS_` 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__FLAGS_` 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/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt new file mode 100644 index 0000000..2bf71a9 --- /dev/null +++ b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt @@ -0,0 +1,15 @@ +``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. 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 ` 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$<$: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/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/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 ` to +support per-configuration specification. For example, the code: + +.. code-block:: cmake + + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$: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/Modules/Platform/Windows-Intel-Fortran.cmake b/Modules/Platform/Windows-Intel-Fortran.cmake index 3981a09..f00a8e4 100644 --- a/Modules/Platform/Windows-Intel-Fortran.cmake +++ b/Modules/Platform/Windows-Intel-Fortran.cmake @@ -4,8 +4,34 @@ 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() +string(APPEND CMAKE_Fortran_FLAGS_INIT " /W1 /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..4279a74 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$<$: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,35 @@ 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() 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_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_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(_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/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 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 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/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(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 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/cmPolicies.h b/Source/cmPolicies.h index 02a6295..113dd35 100644 --- a/Source/cmPolicies.h +++ b/Source/cmPolicies.h @@ -267,7 +267,10 @@ class cmMakefile; 15, 0, cmPolicies::WARN) \ SELECT(POLICY, CMP0090, \ "export(PACKAGE) does not populate package registry by default.", 3, \ - 15, 0, cmPolicies::WARN) + 15, 0, cmPolicies::WARN) \ + SELECT(POLICY, CMP0091, \ + "MSVC runtime library flags are selected by an abstraction.", 3, 15, \ + 0, cmPolicies::WARN) #define CM_SELECT_ID(F, A1, A2, A3, A4, A5, A6) F(A1) #define CM_FOR_EACH_POLICY_ID(POLICY) \ diff --git a/Source/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/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 3746965..4114a67 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") diff --git a/Tests/MSVCRuntimeLibrary/CMakeLists.txt b/Tests/MSVCRuntimeLibrary/CMakeLists.txt new file mode 100644 index 0000000..b7a6e86 --- /dev/null +++ b/Tests/MSVCRuntimeLibrary/CMakeLists.txt @@ -0,0 +1,49 @@ +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 "$<$>:${rtl}>$<$>: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 "$<$:VERIFY_DEBUG>") + verify_combinations(MultiThreaded ${lang} ${src}) +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 "$<$>:${rtl}>$<$>: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 "$<$: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/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt index 68411d6..a8dcb4b 100644 --- a/Tests/RunCMake/CMakeLists.txt +++ b/Tests/RunCMake/CMakeLists.txt @@ -195,6 +195,9 @@ 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) +endif() add_RunCMake_test(ObjectLibrary) add_RunCMake_test(ParseImplicitIncludeInfo) if(UNIX AND CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG AND CMAKE_EXECUTABLE_FORMAT STREQUAL "ELF") 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 diff --git a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake index df253a9..988312b 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) diff --git a/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake b/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake new file mode 100644 index 0000000..6b43d47 --- /dev/null +++ b/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake @@ -0,0 +1,34 @@ +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 "^ *([^<>]+)") + 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) + 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(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..6c77a25 --- /dev/null +++ b/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake @@ -0,0 +1,16 @@ +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 "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/empty.c b/Tests/RunCMake/VS10Project/empty.c new file mode 100644 index 0000000..e69de29 diff --git a/Tests/RunCMake/VS10Project/empty.cxx b/Tests/RunCMake/VS10Project/empty.cxx new file mode 100644 index 0000000..e69de29 -- cgit v0.12 href='#n1083'>1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764

/* Error handling */

#include "Python.h"
#include "pycore_initconfig.h"
#include "pycore_pyerrors.h"
#include "pycore_pystate.h"    // _PyThreadState_GET()
#include "pycore_sysmodule.h"
#include "pycore_traceback.h"

#ifndef __STDC__
#ifndef MS_WINDOWS
extern char *strerror(int);
#endif
#endif

#ifdef MS_WINDOWS
#include <windows.h>
#include <winbase.h>
#endif

#include <ctype.h>

#ifdef __cplusplus
extern "C" {
#endif

_Py_IDENTIFIER(__main__);
_Py_IDENTIFIER(__module__);
_Py_IDENTIFIER(builtins);
_Py_IDENTIFIER(stderr);
_Py_IDENTIFIER(flush);

/* Forward declarations */
static PyObject *
_PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
               const char *format, va_list vargs);


void
_PyErr_Restore(PyThreadState *tstate, PyObject *type, PyObject *value,
               PyObject *traceback)
{
    PyObject *oldtype, *oldvalue, *oldtraceback;

    if (traceback != NULL && !PyTraceBack_Check(traceback)) {
        /* XXX Should never happen -- fatal error instead? */
        /* Well, it could be None. */
        Py_DECREF(traceback);
        traceback = NULL;
    }

    /* Save these in locals to safeguard against recursive
       invocation through Py_XDECREF */
    oldtype = tstate->curexc_type;
    oldvalue = tstate->curexc_value;
    oldtraceback = tstate->curexc_traceback;

    tstate->curexc_type = type;
    tstate->curexc_value = value;
    tstate->curexc_traceback = traceback;

    Py_XDECREF(oldtype);
    Py_XDECREF(oldvalue);
    Py_XDECREF(oldtraceback);
}

void
PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_Restore(tstate, type, value, traceback);
}


_PyErr_StackItem *
_PyErr_GetTopmostException(PyThreadState *tstate)
{
    _PyErr_StackItem *exc_info = tstate->exc_info;
    while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) &&
           exc_info->previous_item != NULL)
    {
        exc_info = exc_info->previous_item;
    }
    return exc_info;
}

static PyObject*
_PyErr_CreateException(PyObject *exception_type, PyObject *value)
{
    PyObject *exc;

    if (value == NULL || value == Py_None) {
        exc = _PyObject_CallNoArg(exception_type);
    }
    else if (PyTuple_Check(value)) {
        exc = PyObject_Call(exception_type, value, NULL);
    }
    else {
        exc = PyObject_CallOneArg(exception_type, value);
    }

    if (exc != NULL && !PyExceptionInstance_Check(exc)) {
        PyErr_Format(PyExc_TypeError,
                     "calling %R should have returned an instance of "
                     "BaseException, not %s",
                     exception_type, Py_TYPE(exc)->tp_name);
        Py_CLEAR(exc);
    }

    return exc;
}

void
_PyErr_SetObject(PyThreadState *tstate, PyObject *exception, PyObject *value)
{
    PyObject *exc_value;
    PyObject *tb = NULL;

    if (exception != NULL &&
        !PyExceptionClass_Check(exception)) {
        _PyErr_Format(tstate, PyExc_SystemError,
                      "_PyErr_SetObject: "
                      "exception %R is not a BaseException subclass",
                      exception);
        return;
    }

    Py_XINCREF(value);
    exc_value = _PyErr_GetTopmostException(tstate)->exc_value;
    if (exc_value != NULL && exc_value != Py_None) {
        /* Implicit exception chaining */
        Py_INCREF(exc_value);
        if (value == NULL || !PyExceptionInstance_Check(value)) {
            /* We must normalize the value right now */
            PyObject *fixed_value;

            /* Issue #23571: functions must not be called with an
               exception set */
            _PyErr_Clear(tstate);

            fixed_value = _PyErr_CreateException(exception, value);
            Py_XDECREF(value);
            if (fixed_value == NULL) {
                Py_DECREF(exc_value);
                return;
            }

            value = fixed_value;
        }

        /* Avoid creating new reference cycles through the
           context chain, while taking care not to hang on
           pre-existing ones.
           This is O(chain length) but context chains are
           usually very short. Sensitive readers may try
           to inline the call to PyException_GetContext. */
        if (exc_value != value) {
            PyObject *o = exc_value, *context;
            PyObject *slow_o = o;  /* Floyd's cycle detection algo */
            int slow_update_toggle = 0;
            while ((context = PyException_GetContext(o))) {
                Py_DECREF(context);
                if (context == value) {
                    PyException_SetContext(o, NULL);
                    break;
                }
                o = context;
                if (o == slow_o) {
                    /* pre-existing cycle - all exceptions on the
                       path were visited and checked.  */
                    break;
                }
                if (slow_update_toggle) {
                    slow_o = PyException_GetContext(slow_o);
                    Py_DECREF(slow_o);
                }
                slow_update_toggle = !slow_update_toggle;
            }
            PyException_SetContext(value, exc_value);
        }
        else {
            Py_DECREF(exc_value);
        }
    }
    if (value != NULL && PyExceptionInstance_Check(value))
        tb = PyException_GetTraceback(value);
    Py_XINCREF(exception);
    _PyErr_Restore(tstate, exception, value, tb);
}

void
PyErr_SetObject(PyObject *exception, PyObject *value)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_SetObject(tstate, exception, value);
}

/* Set a key error with the specified argument, wrapping it in a
 * tuple automatically so that tuple keys are not unpacked as the
 * exception arguments. */
void
_PyErr_SetKeyError(PyObject *arg)
{
    PyThreadState *tstate = _PyThreadState_GET();
    PyObject *tup = PyTuple_Pack(1, arg);
    if (!tup) {
        /* caller will expect error to be set anyway */
        return;
    }
    _PyErr_SetObject(tstate, PyExc_KeyError, tup);
    Py_DECREF(tup);
}

void
_PyErr_SetNone(PyThreadState *tstate, PyObject *exception)
{
    _PyErr_SetObject(tstate, exception, (PyObject *)NULL);
}


void
PyErr_SetNone(PyObject *exception)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_SetNone(tstate, exception);
}


void
_PyErr_SetString(PyThreadState *tstate, PyObject *exception,
                 const char *string)
{
    PyObject *value = PyUnicode_FromString(string);
    _PyErr_SetObject(tstate, exception, value);
    Py_XDECREF(value);
}

void
PyErr_SetString(PyObject *exception, const char *string)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_SetString(tstate, exception, string);
}


PyObject* _Py_HOT_FUNCTION
PyErr_Occurred(void)
{
    /* The caller must hold the GIL. */
    assert(PyGILState_Check());

    PyThreadState *tstate = _PyThreadState_GET();
    return _PyErr_Occurred(tstate);
}


int
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
{
    if (err == NULL || exc == NULL) {
        /* maybe caused by "import exceptions" that failed early on */
        return 0;
    }
    if (PyTuple_Check(exc)) {
        Py_ssize_t i, n;
        n = PyTuple_Size(exc);
        for (i = 0; i < n; i++) {
            /* Test recursively */
             if (PyErr_GivenExceptionMatches(
                 err, PyTuple_GET_ITEM(exc, i)))
             {
                 return 1;
             }
        }
        return 0;
    }
    /* err might be an instance, so check its class. */
    if (PyExceptionInstance_Check(err))
        err = PyExceptionInstance_Class(err);

    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
        return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
    }

    return err == exc;
}


int
_PyErr_ExceptionMatches(PyThreadState *tstate, PyObject *exc)
{
    return PyErr_GivenExceptionMatches(_PyErr_Occurred(tstate), exc);
}


int
PyErr_ExceptionMatches(PyObject *exc)
{
    PyThreadState *tstate = _PyThreadState_GET();
    return _PyErr_ExceptionMatches(tstate, exc);
}


#ifndef Py_NORMALIZE_RECURSION_LIMIT
#define Py_NORMALIZE_RECURSION_LIMIT 32
#endif

/* Used in many places to normalize a raised exception, including in
   eval_code2(), do_raise(), and PyErr_Print()

   XXX: should PyErr_NormalizeException() also call
            PyException_SetTraceback() with the resulting value and tb?
*/
void
_PyErr_NormalizeException(PyThreadState *tstate, PyObject **exc,
                          PyObject **val, PyObject **tb)
{
    int recursion_depth = 0;
    tstate->recursion_headroom++;
    PyObject *type, *value, *initial_tb;

  restart:
    type = *exc;
    if (type == NULL) {
        /* There was no exception, so nothing to do. */
        tstate->recursion_headroom--;
        return;
    }

    value = *val;
    /* If PyErr_SetNone() was used, the value will have been actually
       set to NULL.
    */
    if (!value) {
        value = Py_None;
        Py_INCREF(value);
    }

    /* Normalize the exception so that if the type is a class, the
       value will be an instance.
    */
    if (PyExceptionClass_Check(type)) {
        PyObject *inclass = NULL;
        int is_subclass = 0;

        if (PyExceptionInstance_Check(value)) {
            inclass = PyExceptionInstance_Class(value);
            is_subclass = PyObject_IsSubclass(inclass, type);
            if (is_subclass < 0) {
                goto error;
            }
        }

        /* If the value was not an instance, or is not an instance
           whose class is (or is derived from) type, then use the
           value as an argument to instantiation of the type
           class.
        */
        if (!is_subclass) {
            PyObject *fixed_value = _PyErr_CreateException(type, value);
            if (fixed_value == NULL) {
                goto error;
            }
            Py_DECREF(value);
            value = fixed_value;
        }
        /* If the class of the instance doesn't exactly match the
           class of the type, believe the instance.
        */
        else if (inclass != type) {
            Py_INCREF(inclass);
            Py_DECREF(type);
            type = inclass;
        }
    }
    *exc = type;
    *val = value;
    tstate->recursion_headroom--;
    return;

  error:
    Py_DECREF(type);
    Py_DECREF(value);
    recursion_depth++;
    if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
        _PyErr_SetString(tstate, PyExc_RecursionError,
                         "maximum recursion depth exceeded "
                         "while normalizing an exception");
    }
    /* If the new exception doesn't set a traceback and the old
       exception had a traceback, use the old traceback for the
       new exception.  It's better than nothing.
    */
    initial_tb = *tb;
    _PyErr_Fetch(tstate, exc, val, tb);
    assert(*exc != NULL);
    if (initial_tb != NULL) {
        if (*tb == NULL)
            *tb = initial_tb;
        else
            Py_DECREF(initial_tb);
    }
    /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
       corresponding RecursionError could not be normalized, and the
       MemoryError raised when normalize this RecursionError could not be
       normalized. */
    if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
        if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
            Py_FatalError("Cannot recover from MemoryErrors "
                          "while normalizing exceptions.");
        }
        else {
            Py_FatalError("Cannot recover from the recursive normalization "
                          "of an exception.");
        }
    }
    goto restart;
}


void
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_NormalizeException(tstate, exc, val, tb);
}


void
_PyErr_Fetch(PyThreadState *tstate, PyObject **p_type, PyObject **p_value,
             PyObject **p_traceback)
{
    *p_type = tstate->curexc_type;
    *p_value = tstate->curexc_value;
    *p_traceback = tstate->curexc_traceback;

    tstate->curexc_type = NULL;
    tstate->curexc_value = NULL;
    tstate->curexc_traceback = NULL;
}


void
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_Fetch(tstate, p_type, p_value, p_traceback);
}


void
_PyErr_Clear(PyThreadState *tstate)
{
    _PyErr_Restore(tstate, NULL, NULL, NULL);
}


void
PyErr_Clear(void)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_Clear(tstate);
}


void
_PyErr_GetExcInfo(PyThreadState *tstate,
                  PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
{
    _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
    *p_type = exc_info->exc_type;
    *p_value = exc_info->exc_value;
    *p_traceback = exc_info->exc_traceback;

    Py_XINCREF(*p_type);
    Py_XINCREF(*p_value);
    Py_XINCREF(*p_traceback);
}


void
PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_GetExcInfo(tstate, p_type, p_value, p_traceback);
}

void
PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
{
    PyObject *oldtype, *oldvalue, *oldtraceback;
    PyThreadState *tstate = _PyThreadState_GET();

    oldtype = tstate->exc_info->exc_type;
    oldvalue = tstate->exc_info->exc_value;
    oldtraceback = tstate->exc_info->exc_traceback;

    tstate->exc_info->exc_type = p_type;
    tstate->exc_info->exc_value = p_value;
    tstate->exc_info->exc_traceback = p_traceback;

    Py_XDECREF(oldtype);
    Py_XDECREF(oldvalue);
    Py_XDECREF(oldtraceback);
}

/* Like PyErr_Restore(), but if an exception is already set,
   set the context associated with it.

   The caller is responsible for ensuring that this call won't create
   any cycles in the exception context chain. */
void
_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
{
    if (exc == NULL)
        return;

    PyThreadState *tstate = _PyThreadState_GET();

    if (!PyExceptionClass_Check(exc)) {
        _PyErr_Format(tstate, PyExc_SystemError,
                      "_PyErr_ChainExceptions: "
                      "exception %R is not a BaseException subclass",
                      exc);
        return;
    }

    if (_PyErr_Occurred(tstate)) {
        PyObject *exc2, *val2, *tb2;
        _PyErr_Fetch(tstate, &exc2, &val2, &tb2);
        _PyErr_NormalizeException(tstate, &exc, &val, &tb);
        if (tb != NULL) {
            PyException_SetTraceback(val, tb);
            Py_DECREF(tb);
        }
        Py_DECREF(exc);
        _PyErr_NormalizeException(tstate, &exc2, &val2, &tb2);
        PyException_SetContext(val2, val);
        _PyErr_Restore(tstate, exc2, val2, tb2);
    }
    else {
        _PyErr_Restore(tstate, exc, val, tb);
    }
}

/* Set the currently set exception's context to the given exception.

   If the provided exc_info is NULL, then the current Python thread state's
   exc_info will be used for the context instead.

   This function can only be called when _PyErr_Occurred() is true.
   Also, this function won't create any cycles in the exception context
   chain to the extent that _PyErr_SetObject ensures this. */
void
_PyErr_ChainStackItem(_PyErr_StackItem *exc_info)
{
    PyThreadState *tstate = _PyThreadState_GET();
    assert(_PyErr_Occurred(tstate));

    int exc_info_given;
    if (exc_info == NULL) {
        exc_info_given = 0;
        exc_info = tstate->exc_info;
    } else {
        exc_info_given = 1;
    }
    if (exc_info->exc_type == NULL || exc_info->exc_type == Py_None) {
        return;
    }

    _PyErr_StackItem *saved_exc_info;
    if (exc_info_given) {
        /* Temporarily set the thread state's exc_info since this is what
           _PyErr_SetObject uses for implicit exception chaining. */
        saved_exc_info = tstate->exc_info;
        tstate->exc_info = exc_info;
    }

    PyObject *exc, *val, *tb;
    _PyErr_Fetch(tstate, &exc, &val, &tb);

    PyObject *exc2, *val2, *tb2;
    exc2 = exc_info->exc_type;
    val2 = exc_info->exc_value;
    tb2 = exc_info->exc_traceback;
    _PyErr_NormalizeException(tstate, &exc2, &val2, &tb2);
    if (tb2 != NULL) {
        PyException_SetTraceback(val2, tb2);
    }

    /* _PyErr_SetObject sets the context from PyThreadState. */
    _PyErr_SetObject(tstate, exc, val);
    Py_DECREF(exc);  // since _PyErr_Occurred was true
    Py_XDECREF(val);
    Py_XDECREF(tb);

    if (exc_info_given) {
        tstate->exc_info = saved_exc_info;
    }
}

static PyObject *
_PyErr_FormatVFromCause(PyThreadState *tstate, PyObject *exception,
                        const char *format, va_list vargs)
{
    PyObject *exc, *val, *val2, *tb;

    assert(_PyErr_Occurred(tstate));
    _PyErr_Fetch(tstate, &exc, &val, &tb);
    _PyErr_NormalizeException(tstate, &exc, &val, &tb);
    if (tb != NULL) {
        PyException_SetTraceback(val, tb);
        Py_DECREF(tb);
    }
    Py_DECREF(exc);
    assert(!_PyErr_Occurred(tstate));

    _PyErr_FormatV(tstate, exception, format, vargs);

    _PyErr_Fetch(tstate, &exc, &val2, &tb);
    _PyErr_NormalizeException(tstate, &exc, &val2, &tb);
    Py_INCREF(val);
    PyException_SetCause(val2, val);
    PyException_SetContext(val2, val);
    _PyErr_Restore(tstate, exc, val2, tb);

    return NULL;
}

PyObject *
_PyErr_FormatFromCauseTstate(PyThreadState *tstate, PyObject *exception,
                             const char *format, ...)
{
    va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
    va_start(vargs, format);
#else
    va_start(vargs);
#endif
    _PyErr_FormatVFromCause(tstate, exception, format, vargs);
    va_end(vargs);
    return NULL;
}

PyObject *
_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
{
    PyThreadState *tstate = _PyThreadState_GET();
    va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
    va_start(vargs, format);
#else
    va_start(vargs);
#endif
    _PyErr_FormatVFromCause(tstate, exception, format, vargs);
    va_end(vargs);
    return NULL;
}

/* Convenience functions to set a type error exception and return 0 */

int
PyErr_BadArgument(void)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_SetString(tstate, PyExc_TypeError,
                     "bad argument type for built-in operation");
    return 0;
}

PyObject *
_PyErr_NoMemory(PyThreadState *tstate)
{
    if (Py_IS_TYPE(PyExc_MemoryError, NULL)) {
        /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
           initialized by _PyExc_Init() */
        Py_FatalError("Out of memory and PyExc_MemoryError is not "
                      "initialized yet");
    }
    _PyErr_SetNone(tstate, PyExc_MemoryError);
    return NULL;
}

PyObject *
PyErr_NoMemory(void)
{
    PyThreadState *tstate = _PyThreadState_GET();
    return _PyErr_NoMemory(tstate);
}

PyObject *
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
{
    return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
}

PyObject *
PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
{
    PyThreadState *tstate = _PyThreadState_GET();
    PyObject *message;
    PyObject *v, *args;
    int i = errno;
#ifdef MS_WINDOWS
    WCHAR *s_buf = NULL;
#endif /* Unix/Windows */

#ifdef EINTR
    if (i == EINTR && PyErr_CheckSignals())
        return NULL;
#endif

#ifndef MS_WINDOWS
    if (i != 0) {
        const char *s = strerror(i);
        message = PyUnicode_DecodeLocale(s, "surrogateescape");
    }
    else {
        /* Sometimes errno didn't get set */
        message = PyUnicode_FromString("Error");
    }
#else
    if (i == 0)
        message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
    else
    {
        /* Note that the Win32 errors do not lineup with the
           errno error.  So if the error is in the MSVC error
           table, we use it, otherwise we assume it really _is_
           a Win32 error code
        */
        if (i > 0 && i < _sys_nerr) {
            message = PyUnicode_FromString(_sys_errlist[i]);
        }
        else {
            int len = FormatMessageW(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,                   /* no message source */
                i,
                MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_DEFAULT),
                           /* Default language */
                (LPWSTR) &s_buf,
                0,                      /* size not used */
                NULL);                  /* no args */
            if (len==0) {
                /* Only ever seen this in out-of-mem
                   situations */
                s_buf = NULL;
                message = PyUnicode_FromFormat("Windows Error 0x%x", i);
            } else {
                /* remove trailing cr/lf and dots */
                while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
                    s_buf[--len] = L'\0';
                message = PyUnicode_FromWideChar(s_buf, len);
            }
        }
    }
#endif /* Unix/Windows */

    if (message == NULL)
    {
#ifdef MS_WINDOWS
        LocalFree(s_buf);
#endif
        return NULL;
    }

    if (filenameObject != NULL) {
        if (filenameObject2 != NULL)
            args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
        else
            args = Py_BuildValue("(iOO)", i, message, filenameObject);
    } else {
        assert(filenameObject2 == NULL);
        args = Py_BuildValue("(iO)", i, message);
    }
    Py_DECREF(message);

    if (args != NULL) {
        v = PyObject_Call(exc, args, NULL);
        Py_DECREF(args);
        if (v != NULL) {
            _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
            Py_DECREF(v);
        }
    }
#ifdef MS_WINDOWS
    LocalFree(s_buf);
#endif
    return NULL;
}

PyObject *
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
{
    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
    PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
    Py_XDECREF(name);
    return result;
}

PyObject *
PyErr_SetFromErrno(PyObject *exc)
{
    return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
}

#ifdef MS_WINDOWS
/* Windows specific error code handling */
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
    PyObject *exc,
    int ierr,
    PyObject *filenameObject)
{
    return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
        filenameObject, NULL);
}

PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
    PyObject *exc,
    int ierr,
    PyObject *filenameObject,
    PyObject *filenameObject2)
{
    PyThreadState *tstate = _PyThreadState_GET();
    int len;
    WCHAR *s_buf = NULL; /* Free via LocalFree */
    PyObject *message;
    PyObject *args, *v;

    DWORD err = (DWORD)ierr;
    if (err==0) {
        err = GetLastError();
    }

    len = FormatMessageW(
        /* Error API error */
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,           /* no message source */
        err,
        MAKELANGID(LANG_NEUTRAL,
        SUBLANG_DEFAULT), /* Default language */
        (LPWSTR) &s_buf,
        0,              /* size not used */
        NULL);          /* no args */
    if (len==0) {
        /* Only seen this in out of mem situations */
        message = PyUnicode_FromFormat("Windows Error 0x%x", err);
        s_buf = NULL;
    } else {
        /* remove trailing cr/lf and dots */
        while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
            s_buf[--len] = L'\0';
        message = PyUnicode_FromWideChar(s_buf, len);
    }

    if (message == NULL)
    {
        LocalFree(s_buf);
        return NULL;
    }

    if (filenameObject == NULL) {
        assert(filenameObject2 == NULL);
        filenameObject = filenameObject2 = Py_None;
    }
    else if (filenameObject2 == NULL)
        filenameObject2 = Py_None;
    /* This is the constructor signature for OSError.
       The POSIX translation will be figured out by the constructor. */
    args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
    Py_DECREF(message);

    if (args != NULL) {
        v = PyObject_Call(exc, args, NULL);
        Py_DECREF(args);
        if (v != NULL) {
            _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
            Py_DECREF(v);
        }
    }
    LocalFree(s_buf);
    return NULL;
}

PyObject *PyErr_SetExcFromWindowsErrWithFilename(
    PyObject *exc,
    int ierr,
    const char *filename)
{
    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
    PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
                                                                 ierr,
                                                                 name,
                                                                 NULL);
    Py_XDECREF(name);
    return ret;
}

PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
{
    return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
}

PyObject *PyErr_SetFromWindowsErr(int ierr)
{
    return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
                                                  ierr, NULL);
}

PyObject *PyErr_SetFromWindowsErrWithFilename(
    int ierr,
    const char *filename)
{
    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
    PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
                                                  PyExc_OSError,
                                                  ierr, name, NULL);
    Py_XDECREF(name);
    return result;
}

#endif /* MS_WINDOWS */

PyObject *
PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
    PyObject *name, PyObject *path)
{
    PyThreadState *tstate = _PyThreadState_GET();
    int issubclass;
    PyObject *kwargs, *error;

    issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
    if (issubclass < 0) {
        return NULL;
    }
    else if (!issubclass) {
        _PyErr_SetString(tstate, PyExc_TypeError,
                         "expected a subclass of ImportError");
        return NULL;
    }

    if (msg == NULL) {
        _PyErr_SetString(tstate, PyExc_TypeError,
                         "expected a message argument");
        return NULL;
    }

    if (name == NULL) {
        name = Py_None;
    }
    if (path == NULL) {
        path = Py_None;
    }

    kwargs = PyDict_New();
    if (kwargs == NULL) {
        return NULL;
    }
    if (PyDict_SetItemString(kwargs, "name", name) < 0) {
        goto done;
    }
    if (PyDict_SetItemString(kwargs, "path", path) < 0) {
        goto done;
    }

    error = PyObject_VectorcallDict(exception, &msg, 1, kwargs);
    if (error != NULL) {
        _PyErr_SetObject(tstate, (PyObject *)Py_TYPE(error), error);
        Py_DECREF(error);
    }

done:
    Py_DECREF(kwargs);
    return NULL;
}

PyObject *
PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
{
    return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
}

void
_PyErr_BadInternalCall(const char *filename, int lineno)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_Format(tstate, PyExc_SystemError,
                  "%s:%d: bad argument to internal function",
                  filename, lineno);
}

/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
   export the entry point for existing object code: */
#undef PyErr_BadInternalCall
void
PyErr_BadInternalCall(void)
{
    assert(0 && "bad argument to internal function");
    PyThreadState *tstate = _PyThreadState_GET();
    _PyErr_SetString(tstate, PyExc_SystemError,
                     "bad argument to internal function");
}
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)


static PyObject *
_PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
               const char *format, va_list vargs)
{
    PyObject* string;

    /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
       exception set, it calls arbitrary Python code like PyObject_Repr() */
    _PyErr_Clear(tstate);

    string = PyUnicode_FromFormatV(format, vargs);

    _PyErr_SetObject(tstate, exception, string);
    Py_XDECREF(string);
    return NULL;
}


PyObject *
PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
{
    PyThreadState *tstate = _PyThreadState_GET();
    return _PyErr_FormatV(tstate, exception, format, vargs);
}


PyObject *
_PyErr_Format(PyThreadState *tstate, PyObject *exception,
              const char *format, ...)
{
    va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
    va_start(vargs, format);
#else
    va_start(vargs);
#endif
    _PyErr_FormatV(tstate, exception, format, vargs);
    va_end(vargs);
    return NULL;
}


PyObject *
PyErr_Format(PyObject *exception, const char *format, ...)
{
    PyThreadState *tstate = _PyThreadState_GET();
    va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
    va_start(vargs, format);
#else
    va_start(vargs);
#endif
    _PyErr_FormatV(tstate, exception, format, vargs);
    va_end(vargs);
    return NULL;
}


PyObject *
PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
{
    PyThreadState *tstate = _PyThreadState_GET();
    PyObject *modulename = NULL;
    PyObject *mydict = NULL;
    PyObject *bases = NULL;
    PyObject *result = NULL;

    const char *dot = strrchr(name, '.');
    if (dot == NULL) {
        _PyErr_SetString(tstate, PyExc_SystemError,
                         "PyErr_NewException: name must be module.class");
        return NULL;
    }
    if (base == NULL) {
        base = PyExc_Exception;
    }
    if (dict == NULL) {
        dict = mydict = PyDict_New();
        if (dict == NULL)
            goto failure;
    }

    int r = _PyDict_ContainsId(dict, &PyId___module__);
    if (r < 0) {
        goto failure;
    }
    if (r == 0) {
        modulename = PyUnicode_FromStringAndSize(name,
                                             (Py_ssize_t)(dot-name));
        if (modulename == NULL)
            goto failure;
        if (_PyDict_SetItemId(dict, &PyId___module__, modulename) != 0)
            goto failure;
    }
    if (PyTuple_Check(base)) {
        bases = base;
        /* INCREF as we create a new ref in the else branch */
        Py_INCREF(bases);
    } else {
        bases = PyTuple_Pack(1, base);
        if (bases == NULL)
            goto failure;
    }
    /* Create a real class. */
    result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
                                   dot+1, bases, dict);
  failure:
    Py_XDECREF(bases);
    Py_XDECREF(mydict);
    Py_XDECREF(modulename);
    return result;
}


/* Create an exception with docstring */
PyObject *
PyErr_NewExceptionWithDoc(const char *name, const char *doc,
                          PyObject *base, PyObject *dict)
{
    int result;
    PyObject *ret = NULL;
    PyObject *mydict = NULL; /* points to the dict only if we create it */
    PyObject *docobj;

    if (dict == NULL) {
        dict = mydict = PyDict_New();
        if (dict == NULL) {
            return NULL;
        }
    }

    if (doc != NULL) {
        docobj = PyUnicode_FromString(doc);
        if (docobj == NULL)
            goto failure;
        result = PyDict_SetItemString(dict, "__doc__", docobj);
        Py_DECREF(docobj);
        if (result < 0)
            goto failure;
    }

    ret = PyErr_NewException(name, base, dict);
  failure:
    Py_XDECREF(mydict);
    return ret;
}


PyDoc_STRVAR(UnraisableHookArgs__doc__,
"UnraisableHookArgs\n\
\n\
Type used to pass arguments to sys.unraisablehook.");

static PyTypeObject UnraisableHookArgsType;

static PyStructSequence_Field UnraisableHookArgs_fields[] = {
    {"exc_type", "Exception type"},
    {"exc_value", "Exception value"},
    {"exc_traceback", "Exception traceback"},
    {"err_msg", "Error message"},
    {"object", "Object causing the exception"},
    {0}
};

static PyStructSequence_Desc UnraisableHookArgs_desc = {
    .name = "UnraisableHookArgs",
    .doc = UnraisableHookArgs__doc__,
    .fields = UnraisableHookArgs_fields,
    .n_in_sequence = 5
};


PyStatus
_PyErr_InitTypes(void)
{
    if (UnraisableHookArgsType.tp_name == NULL) {
        if (PyStructSequence_InitType2(&UnraisableHookArgsType,
                                       &UnraisableHookArgs_desc) < 0) {
            return _PyStatus_ERR("failed to initialize UnraisableHookArgs type");
        }
    }
    return _PyStatus_OK();
}


static PyObject *
make_unraisable_hook_args(PyThreadState *tstate, PyObject *exc_type,
                          PyObject *exc_value, PyObject *exc_tb,
                          PyObject *err_msg, PyObject *obj)
{
    PyObject *args = PyStructSequence_New(&UnraisableHookArgsType);
    if (args == NULL) {
        return NULL;
    }

    Py_ssize_t pos = 0;
#define ADD_ITEM(exc_type) \
        do { \
            if (exc_type == NULL) { \
                exc_type = Py_None; \
            } \
            Py_INCREF(exc_type); \
            PyStructSequence_SET_ITEM(args, pos++, exc_type); \
        } while (0)


    ADD_ITEM(exc_type);
    ADD_ITEM(exc_value);
    ADD_ITEM(exc_tb);
    ADD_ITEM(err_msg);
    ADD_ITEM(obj);
#undef ADD_ITEM

    if (_PyErr_Occurred(tstate)) {
        Py_DECREF(args);
        return NULL;
    }
    return args;
}



/* Default implementation of sys.unraisablehook.

   It can be called to log the exception of a custom sys.unraisablehook.

   Do nothing if sys.stderr attribute doesn't exist or is set to None. */
static int
write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type,
                          PyObject *exc_value, PyObject *exc_tb,
                          PyObject *err_msg, PyObject *obj, PyObject *file)
{
    if (obj != NULL && obj != Py_None) {
        if (err_msg != NULL && err_msg != Py_None) {
            if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
                return -1;
            }
            if (PyFile_WriteString(": ", file) < 0) {
                return -1;
            }
        }
        else {
            if (PyFile_WriteString("Exception ignored in: ", file) < 0) {
                return -1;
            }
        }

        if (PyFile_WriteObject(obj, file, 0) < 0) {
            _PyErr_Clear(tstate);
            if (PyFile_WriteString("<object repr() failed>", file) < 0) {
                return -1;
            }
        }
        if (PyFile_WriteString("\n", file) < 0) {
            return -1;
        }
    }
    else if (err_msg != NULL && err_msg != Py_None) {
        if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
            return -1;
        }
        if (PyFile_WriteString(":\n", file) < 0) {
            return -1;
        }
    }

    if (exc_tb != NULL && exc_tb != Py_None) {
        if (PyTraceBack_Print(exc_tb, file) < 0) {
            /* continue even if writing the traceback failed */
            _PyErr_Clear(tstate);
        }
    }

    if (exc_type == NULL || exc_type == Py_None) {
        return -1;
    }

    assert(PyExceptionClass_Check(exc_type));

    PyObject *modulename = _PyObject_GetAttrId(exc_type, &PyId___module__);
    if (modulename == NULL || !PyUnicode_Check(modulename)) {
        Py_XDECREF(modulename);
        _PyErr_Clear(tstate);
        if (PyFile_WriteString("<unknown>", file) < 0) {
            return -1;
        }
    }
    else {
        if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins) &&
            !_PyUnicode_EqualToASCIIId(modulename, &PyId___main__)) {
            if (PyFile_WriteObject(modulename, file, Py_PRINT_RAW) < 0) {
                Py_DECREF(modulename);
                return -1;
            }
            Py_DECREF(modulename);
            if (PyFile_WriteString(".", file) < 0) {
                return -1;
            }
        }
        else {
            Py_DECREF(modulename);
        }
    }

    PyObject *qualname = PyType_GetQualName((PyTypeObject *)exc_type);
    if (qualname == NULL || !PyUnicode_Check(qualname)) {
        Py_XDECREF(qualname);
        _PyErr_Clear(tstate);
        if (PyFile_WriteString("<unknown>", file) < 0) {
            return -1;
        }
    }
    else {
        if (PyFile_WriteObject(qualname, file, Py_PRINT_RAW) < 0) {
            Py_DECREF(qualname);
            return -1;
        }
        Py_DECREF(qualname);
    }

    if (exc_value && exc_value != Py_None) {
        if (PyFile_WriteString(": ", file) < 0) {
            return -1;
        }
        if (PyFile_WriteObject(exc_value, file, Py_PRINT_RAW) < 0) {
            _PyErr_Clear(tstate);
            if (PyFile_WriteString("<exception str() failed>", file) < 0) {
                return -1;
            }
        }
    }

    if (PyFile_WriteString("\n", file) < 0) {
        return -1;
    }

    /* Explicitly call file.flush() */
    PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
    if (!res) {
        return -1;
    }
    Py_DECREF(res);

    return 0;
}


static int
write_unraisable_exc(PyThreadState *tstate, PyObject *exc_type,
                     PyObject *exc_value, PyObject *exc_tb, PyObject *err_msg,
                     PyObject *obj)
{
    PyObject *file = _PySys_GetObjectId(&PyId_stderr);
    if (file == NULL || file == Py_None) {
        return 0;
    }

    /* Hold a strong reference to ensure that sys.stderr doesn't go away
       while we use it */
    Py_INCREF(file);
    int res = write_unraisable_exc_file(tstate, exc_type, exc_value, exc_tb,
                                        err_msg, obj, file);
    Py_DECREF(file);

    return res;
}


PyObject*
_PyErr_WriteUnraisableDefaultHook(PyObject *args)
{
    PyThreadState *tstate = _PyThreadState_GET();

    if (!Py_IS_TYPE(args, &UnraisableHookArgsType)) {
        _PyErr_SetString(tstate, PyExc_TypeError,
                         "sys.unraisablehook argument type "
                         "must be UnraisableHookArgs");
        return NULL;
    }

    /* Borrowed references */
    PyObject *exc_type = PyStructSequence_GET_ITEM(args, 0);
    PyObject *exc_value = PyStructSequence_GET_ITEM(args, 1);
    PyObject *exc_tb = PyStructSequence_GET_ITEM(args, 2);
    PyObject *err_msg = PyStructSequence_GET_ITEM(args, 3);
    PyObject *obj = PyStructSequence_GET_ITEM(args, 4);

    if (write_unraisable_exc(tstate, exc_type, exc_value, exc_tb, err_msg, obj) < 0) {
        return NULL;
    }
    Py_RETURN_NONE;
}


/* Call sys.unraisablehook().

   This function can be used when an exception has occurred but there is no way
   for Python to handle it. For example, when a destructor raises an exception
   or during garbage collection (gc.collect()).

   If err_msg_str is non-NULL, the error message is formatted as:
   "Exception ignored %s" % err_msg_str. Otherwise, use "Exception ignored in"
   error message.

   An exception must be set when calling this function. */
void
_PyErr_WriteUnraisableMsg(const char *err_msg_str, PyObject *obj)
{
    PyThreadState *tstate = _PyThreadState_GET();
    _Py_EnsureTstateNotNULL(tstate);

    PyObject *err_msg = NULL;
    PyObject *exc_type, *exc_value, *exc_tb;
    _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);

    assert(exc_type != NULL);

    if (exc_type == NULL) {
        /* sys.unraisablehook requires that at least exc_type is set */
        goto default_hook;
    }

    if (exc_tb == NULL) {
        PyFrameObject *frame = PyThreadState_GetFrame(tstate);
        if (frame != NULL) {
            exc_tb = _PyTraceBack_FromFrame(NULL, frame);
            if (exc_tb == NULL) {
                _PyErr_Clear(tstate);
            }
            Py_DECREF(frame);
        }
    }

    _PyErr_NormalizeException(tstate, &exc_type, &exc_value, &exc_tb);

    if (exc_tb != NULL && exc_tb != Py_None && PyTraceBack_Check(exc_tb)) {
        if (PyException_SetTraceback(exc_value, exc_tb) < 0) {
            _PyErr_Clear(tstate);
        }
    }

    if (err_msg_str != NULL) {
        err_msg = PyUnicode_FromFormat("Exception ignored %s", err_msg_str);
        if (err_msg == NULL) {
            PyErr_Clear();
        }
    }

    PyObject *hook_args = make_unraisable_hook_args(
        tstate, exc_type, exc_value, exc_tb, err_msg, obj);
    if (hook_args == NULL) {
        err_msg_str = ("Exception ignored on building "
                       "sys.unraisablehook arguments");
        goto error;
    }

    _Py_IDENTIFIER(unraisablehook);
    PyObject *hook = _PySys_GetObjectId(&PyId_unraisablehook);
    if (hook == NULL) {
        Py_DECREF(hook_args);
        goto default_hook;
    }

    if (_PySys_Audit(tstate, "sys.unraisablehook", "OO", hook, hook_args) < 0) {
        Py_DECREF(hook_args);
        err_msg_str = "Exception ignored in audit hook";
        obj = NULL;
        goto error;
    }

    if (hook == Py_None) {
        Py_DECREF(hook_args);
        goto default_hook;
    }

    PyObject *res = PyObject_CallOneArg(hook, hook_args);
    Py_DECREF(hook_args);
    if (res != NULL) {
        Py_DECREF(res);
        goto done;
    }

    /* sys.unraisablehook failed: log its error using default hook */
    obj = hook;
    err_msg_str = NULL;

error:
    /* err_msg_str and obj have been updated and we have a new exception */
    Py_XSETREF(err_msg, PyUnicode_FromString(err_msg_str ?
        err_msg_str : "Exception ignored in sys.unraisablehook"));
    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value);
    Py_XDECREF(exc_tb);
    _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);

default_hook:
    /* Call the default unraisable hook (ignore failure) */
    (void)write_unraisable_exc(tstate, exc_type, exc_value, exc_tb,
                               err_msg, obj);

done:
    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value);
    Py_XDECREF(exc_tb);
    Py_XDECREF(err_msg);
    _PyErr_Clear(tstate); /* Just in case */
}


void
PyErr_WriteUnraisable(PyObject *obj)
{
    _PyErr_WriteUnraisableMsg(NULL, obj);
}


void
PyErr_SyntaxLocation(const char *filename, int lineno)
{
    PyErr_SyntaxLocationEx(filename, lineno, -1);
}


/* Set file and line information for the current exception.
   If the exception is not a SyntaxError, also sets additional attributes
   to make printing of exceptions believe it is a syntax error. */

static void
PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset,
                             int end_lineno, int end_col_offset)
{
    PyObject *exc, *v, *tb, *tmp;
    _Py_IDENTIFIER(filename);
    _Py_IDENTIFIER(lineno);
    _Py_IDENTIFIER(end_lineno);
    _Py_IDENTIFIER(msg);
    _Py_IDENTIFIER(offset);
    _Py_IDENTIFIER(end_offset);
    _Py_IDENTIFIER(print_file_and_line);
    _Py_IDENTIFIER(text);
    PyThreadState *tstate = _PyThreadState_GET();

    /* add attributes for the line number and filename for the error */
    _PyErr_Fetch(tstate, &exc, &v, &tb);
    _PyErr_NormalizeException(tstate, &exc, &v, &tb);
    /* XXX check that it is, indeed, a syntax error. It might not
     * be, though. */
    tmp = PyLong_FromLong(lineno);
    if (tmp == NULL)
        _PyErr_Clear(tstate);
    else {
        if (_PyObject_SetAttrId(v, &PyId_lineno, tmp)) {
            _PyErr_Clear(tstate);
        }
        Py_DECREF(tmp);
    }
    tmp = NULL;
    if (col_offset >= 0) {
        tmp = PyLong_FromLong(col_offset);
        if (tmp == NULL) {
            _PyErr_Clear(tstate);
        }
    }
    if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None)) {
        _PyErr_Clear(tstate);
    }
    Py_XDECREF(tmp);

    tmp = NULL;
    if (end_lineno >= 0) {
        tmp = PyLong_FromLong(end_lineno);
        if (tmp == NULL) {
            _PyErr_Clear(tstate);
        }
    }
    if (_PyObject_SetAttrId(v, &PyId_end_lineno, tmp ? tmp : Py_None)) {
        _PyErr_Clear(tstate);
    }
    Py_XDECREF(tmp);

    tmp = NULL;
    if (end_col_offset >= 0) {
        tmp = PyLong_FromLong(end_col_offset);
        if (tmp == NULL) {
            _PyErr_Clear(tstate);
        }
    }
    if (_PyObject_SetAttrId(v, &PyId_end_offset, tmp ? tmp : Py_None)) {
        _PyErr_Clear(tstate);
    }
    Py_XDECREF(tmp);

    tmp = NULL;
    if (filename != NULL) {
        if (_PyObject_SetAttrId(v, &PyId_filename, filename)) {
            _PyErr_Clear(tstate);
        }

        tmp = PyErr_ProgramTextObject(filename, lineno);
        if (tmp) {
            if (_PyObject_SetAttrId(v, &PyId_text, tmp)) {
                _PyErr_Clear(tstate);
            }
            Py_DECREF(tmp);
        }
        else {
            _PyErr_Clear(tstate);
        }
    }
    if (exc != PyExc_SyntaxError) {
        if (_PyObject_LookupAttrId(v, &PyId_msg, &tmp) < 0) {
            _PyErr_Clear(tstate);
        }
        else if (tmp) {
            Py_DECREF(tmp);
        }
        else {
            tmp = PyObject_Str(v);
            if (tmp) {
                if (_PyObject_SetAttrId(v, &PyId_msg, tmp)) {
                    _PyErr_Clear(tstate);
                }
                Py_DECREF(tmp);
            }
            else {
                _PyErr_Clear(tstate);
            }
        }
        if (_PyObject_LookupAttrId(v, &PyId_print_file_and_line, &tmp) < 0) {
            _PyErr_Clear(tstate);
        }
        else if (tmp) {
            Py_DECREF(tmp);
        }
        else {
            if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
                                    Py_None)) {
                _PyErr_Clear(tstate);
            }
        }
    }
    _PyErr_Restore(tstate, exc, v, tb);
}

void
PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) {
    PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, lineno, -1);
}

void
PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset,
                                 int end_lineno, int end_col_offset) {
    PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, end_lineno, end_col_offset);
}

void
PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
{
    PyThreadState *tstate = _PyThreadState_GET();
    PyObject *fileobj;
    if (filename != NULL) {
        fileobj = PyUnicode_DecodeFSDefault(filename);
        if (fileobj == NULL) {
            _PyErr_Clear(tstate);
        }
    }
    else {
        fileobj = NULL;
    }
    PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
    Py_XDECREF(fileobj);
}

/* Attempt to load the line of text that the exception refers to.  If it
   fails, it will return NULL but will not set an exception.

   XXX The functionality of this function is quite similar to the
   functionality in tb_displayline() in traceback.c. */

static PyObject *
err_programtext(PyThreadState *tstate, FILE *fp, int lineno)
{
    int i;
    char linebuf[1000];
    if (fp == NULL) {
        return NULL;
    }

    for (i = 0; i < lineno; i++) {
        char *pLastChar = &linebuf[sizeof(linebuf) - 2];
        do {
            *pLastChar = '\0';
            if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
                                         fp, NULL) == NULL) {
                goto after_loop;
            }
            /* fgets read *something*; if it didn't get as
               far as pLastChar, it must have found a newline
               or hit the end of the file; if pLastChar is \n,
               it obviously found a newline; else we haven't
               yet seen a newline, so must continue */
        } while (*pLastChar != '\0' && *pLastChar != '\n');
    }

after_loop:
    fclose(fp);
    if (i == lineno) {
        PyObject *res;
        res = PyUnicode_FromString(linebuf);
        if (res == NULL)
            _PyErr_Clear(tstate);
        return res;
    }
    return NULL;
}

PyObject *
PyErr_ProgramText(const char *filename, int lineno)
{
    if (filename == NULL) {
        return NULL;
    }

    PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
    if (filename_obj == NULL) {
        PyErr_Clear();
        return NULL;
    }
    PyObject *res = PyErr_ProgramTextObject(filename_obj, lineno);
    Py_DECREF(filename_obj);
    return res;
}

PyObject *
PyErr_ProgramTextObject(PyObject *filename, int lineno)
{
    if (filename == NULL || lineno <= 0) {
        return NULL;
    }

    PyThreadState *tstate = _PyThreadState_GET();
    FILE *fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
    if (fp == NULL) {
        _PyErr_Clear(tstate);
        return NULL;
    }
    return err_programtext(tstate, fp, lineno);
}

#ifdef __cplusplus
}
#endif