From e81e720e7e57353f17e7dc09353d58f162bfbb7e Mon Sep 17 00:00:00 2001
From: Dmitri Naumov <github@naumov.de>
Date: Thu, 25 Aug 2022 11:52:27 +0200
Subject: [PATCH] [BL] Disable FPE for libxml2 calls

Internally in libxml2 there is some magic working with
NaN's and triggers a FPE where it is not relevant.
---
 BaseLib/PrjProcessing.cpp | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/BaseLib/PrjProcessing.cpp b/BaseLib/PrjProcessing.cpp
index 4372e40d07a..e92b60c187a 100644
--- a/BaseLib/PrjProcessing.cpp
+++ b/BaseLib/PrjProcessing.cpp
@@ -10,6 +10,12 @@
 
 #include "PrjProcessing.h"
 
+#ifndef _WIN32
+#ifndef __APPLE__
+#include <cfenv>
+#endif  // __APPLE__
+#endif  // _WIN32
+
 #include <libxml/parser.h>
 #include <libxml/tree.h>
 #include <xml_patch.h>
@@ -109,6 +115,19 @@ void traverseIncludes(xmlDoc* doc, xmlNode* node,
 void replaceIncludes(std::stringstream& prj_stream,
                      std::filesystem::path const& prj_dir)
 {
+    // Store floating-point exception handling. Parsing the XML triggers
+    // floating point exceptions. Because we are not debugging libxml2 (or other
+    // libraries) at this point, the possibly set exceptions are temporary
+    // disabled and restored before end of the function.
+#ifndef _WIN32
+#ifndef __APPLE__
+    fenv_t fe_env;
+    fegetenv(&fe_env);
+    fesetenv(FE_DFL_ENV);  // Set default environment effectively disabling
+                           // exceptions.
+#endif                     //_WIN32
+#endif                     //__APPLE__
+
     auto doc =
         xmlParseMemory(prj_stream.str().c_str(), prj_stream.str().size());
     if (doc == nullptr)
@@ -127,6 +146,13 @@ void replaceIncludes(std::stringstream& prj_stream,
 
     xmlFree(xmlbuff);
     xmlFreeDoc(doc);
+
+    // Restore floating-point exception handling.
+#ifndef _WIN32
+#ifndef __APPLE__
+    fesetenv(&fe_env);
+#endif  //_WIN32
+#endif  //__APPLE__
 }
 
 // Applies a patch file to the prj content in prj_stream.
-- 
GitLab