diff --git a/cmake/environmentchecks.cmake b/cmake/environmentchecks.cmake index d153eccab..ca975804d 100644 --- a/cmake/environmentchecks.cmake +++ b/cmake/environmentchecks.cmake @@ -95,11 +95,11 @@ else () set(_ORIGINAL_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) - set(CMAKE_REQUIRED_FLAGS -fprofile-instr-generate) - check_cxx_compiler_flag("-fprofile-instr-generate -fcoverage-mapping" LLVM_COVERAGE_COMPILER_FLAGS_OK) + set(CMAKE_REQUIRED_FLAGS "-fprofile-instr-generate -fprofile-update=atomic") + check_cxx_compiler_flag("-fprofile-instr-generate -fcoverage-mapping -fprofile-update=atomic" LLVM_ATOMIC_COVERAGE_COMPILER_FLAGS_OK) - set(CMAKE_REQUIRED_FLAGS "-fprofile-arcs -ftest-coverage") - check_cxx_compiler_flag("-fprofile-arcs -ftest-coverage" GCC_COVERAGE_COMPILER_FLAGS_OK) + set(CMAKE_REQUIRED_FLAGS "-fprofile-arcs -ftest-coverage -fprofile-update=atomic") + check_cxx_compiler_flag("-fprofile-arcs -ftest-coverage -fprofile-update=atomic" GCC_ATOMIC_COVERAGE_COMPILER_FLAGS_OK) set(CMAKE_REQUIRED_FLAGS ${_ORIGINAL_CMAKE_REQUIRED_FLAGS}) @@ -114,12 +114,12 @@ else () CLANG_TIDY_EXE CLANG_FORMAT_EXE FIND_EXE - GCC_COVERAGE_COMPILER_FLAGS_OK + GCC_ATOMIC_COVERAGE_COMPILER_FLAGS_OK GCOV_EXE GIT_EXE INSTALL_NAME_TOOL_EXE + LLVM_ATOMIC_COVERAGE_COMPILER_FLAGS_OK LLVM_COV_EXE - LLVM_COVERAGE_COMPILER_FLAGS_OK LLVM_PROFDATA_EXE SWIG_EXECUTABLE VALGRIND_EXE @@ -162,7 +162,7 @@ if(CLANG_TIDY_EXE) set(CLANG_TIDY_AVAILABLE TRUE CACHE INTERNAL "Executable required to perform static analysis is available.") endif() -if(FIND_EXE AND GCOV_EXE AND Python_Interpreter_FOUND AND GCC_COVERAGE_COMPILER_FLAGS_OK) +if(FIND_EXE AND GCOV_EXE AND Python_Interpreter_FOUND AND GCC_ATOMIC_COVERAGE_COMPILER_FLAGS_OK) set(COVERAGE_TESTING_AVAILABLE TRUE CACHE INTERNAL "Executables required to run the coverage testing are available.") endif() @@ -178,7 +178,7 @@ if(VALGRIND_EXE AND Python_Interpreter_FOUND) set(VALGRIND_TESTING_AVAILABLE TRUE CACHE INTERNAL "Executable required to run valgrind testing is available.") endif() -if(LLVM_PROFDATA_EXE AND LLVM_COV_EXE AND FIND_EXE AND LLVM_COVERAGE_COMPILER_FLAGS_OK) +if(LLVM_PROFDATA_EXE AND LLVM_COV_EXE AND FIND_EXE AND LLVM_ATOMIC_COVERAGE_COMPILER_FLAGS_OK) set(LLVM_COVERAGE_TESTING_AVAILABLE TRUE CACHE INTERNAL "Executables required to run the llvm coverage testing are available.") endif() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 488d2a773..a9cb0065a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -281,8 +281,9 @@ function(append_target_property _TARGET _PROPERTY _VALUE) endfunction() if(LIBCELLML_COVERAGE) - append_target_property(cellml COMPILE_FLAGS "-fprofile-arcs -ftest-coverage") - append_target_property(cellml LINK_FLAGS "-fprofile-arcs -ftest-coverage") + # Note: we use atomic profile updates for threaded tests coverage counting. + append_target_property(cellml COMPILE_FLAGS "-fprofile-arcs -ftest-coverage -fprofile-update=atomic") + append_target_property(cellml LINK_FLAGS "-fprofile-arcs -ftest-coverage -fprofile-update=atomic") # Share some paths with interested parties (tests) set(GCOV_ANALYSIS_PATH "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cellml.dir" PARENT_SCOPE) @@ -299,8 +300,8 @@ if(LIBCELLML_COVERAGE) endif() if(LIBCELLML_LLVM_COVERAGE) - append_target_property(cellml COMPILE_FLAGS "-fprofile-instr-generate -fcoverage-mapping") - append_target_property(cellml LINK_FLAGS "-fprofile-instr-generate") + append_target_property(cellml COMPILE_FLAGS "-fprofile-instr-generate -fcoverage-mapping -fprofile-update=atomic") + append_target_property(cellml LINK_FLAGS "-fprofile-instr-generate -fprofile-update=atomic") endif() install(TARGETS cellml EXPORT libcellml-targets diff --git a/src/xmldoc.cpp b/src/xmldoc.cpp index bee79fad9..f7dfa834f 100644 --- a/src/xmldoc.cpp +++ b/src/xmldoc.cpp @@ -52,6 +52,24 @@ void structuredErrorCallback(void *userData, XML_ERROR_CALLBACK_ARGUMENT_TYPE er doc->addXmlError(errorString); } +/** + * @brief Initialise libxml2. + * + * Initialise libxml2 exactly once, no matter how many threads call this function and when. Before libxml2 2.14, + * xmlInitParser() checks whether libxml2 is already initialised without any synchronisation, which is a data race + * when it gets called from different threads at the same time. + */ +void initialiseLibxml2() +{ + static const bool initialised = []() { + xmlInitParser(); + + return true; + }(); + + (void)initialised; +} + /** * @brief The XmlDoc::XmlDocImpl struct. * @@ -81,7 +99,7 @@ XmlDoc::~XmlDoc() void XmlDoc::parse(const std::string &input, bool keepBlanks) { - xmlInitParser(); + initialiseLibxml2(); int options = keepBlanks ? 0 : XML_PARSE_NOBLANKS; xmlParserCtxtPtr context = xmlNewParserCtxt(); context->_private = reinterpret_cast(this); @@ -89,7 +107,6 @@ void XmlDoc::parse(const std::string &input, bool keepBlanks) mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast(input.c_str()), "/", nullptr, options); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); - xmlCleanupParser(); } std::string decompressMathMLDTD() @@ -105,30 +122,62 @@ std::string decompressMathMLDTD() return std::string(mathmlDTD.begin(), mathmlDTD.end()); } -void XmlDoc::parseMathML(const std::string &input) +/** + * @brief The parsed MathML DTD. + * + * Parsing the MathML DTD is expensive (it is about 390 KB long), so we parse it only once rather than every time that + * we validate some MathML. However, libxml2 builds (and caches) the content model of an element declaration the first + * time that it validates an element against it, i.e. validating against a DTD modifies it, so we have one parsed MathML + * DTD per thread. + * + * Note: a thread's parsed MathML DTD is only freed when that thread exits, not when it has finished validating some + * MathML. A parsed MathML DTD takes about 4 MB of memory, so an application that validates MathML from a large + * pool of long-lived threads will hold about 4 MB per thread for as long as the pool exists. If this ever becomes + * a problem, we could, for instance, keep a fixed number of parsed MathML DTDs and lend each of them to one + * thread at a time. + */ +class MathmlDtd { - // Decompress the MathML DTD. - int sizeMathmlDTDUncompressed = MATHML_DTD_LEN; +public: + MathmlDtd() + { + auto mathmlDTD = decompressMathMLDTD(); + xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(mathmlDTD.c_str(), static_cast(mathmlDTD.size()), XML_CHAR_ENCODING_ASCII); + + mDtd = xmlIOParseDTD(nullptr, buf, XML_CHAR_ENCODING_ASCII); + } - static std::string mathMLDTD; + ~MathmlDtd() + { + xmlFreeDtd(mDtd); + } + + MathmlDtd(const MathmlDtd &) = delete; + MathmlDtd &operator=(const MathmlDtd &) = delete; - if (mathMLDTD.empty()) { - mathMLDTD = decompressMathMLDTD(); + xmlDtdPtr dtd() const + { + return mDtd; } - xmlInitParser(); +private: + xmlDtdPtr mDtd = nullptr; +}; + +void XmlDoc::parseMathML(const std::string &input) +{ + initialiseLibxml2(); + + thread_local MathmlDtd mathmlDtd; + xmlParserCtxtPtr context = xmlNewParserCtxt(); context->_private = reinterpret_cast(this); xmlSetStructuredErrorFunc(context, structuredErrorCallback); mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast(input.c_str()), "/", nullptr, 0); - xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(reinterpret_cast(mathMLDTD.c_str()), sizeMathmlDTDUncompressed, XML_CHAR_ENCODING_ASCII); - xmlDtdPtr dtd = xmlIOParseDTD(nullptr, buf, XML_CHAR_ENCODING_ASCII); - xmlValidateDtd(&(context->vctxt), mPimpl->mXmlDocPtr, dtd); + xmlValidateDtd(&(context->vctxt), mPimpl->mXmlDocPtr, mathmlDtd.dtd()); - xmlFreeDtd(dtd); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); - xmlCleanupParser(); } std::string XmlDoc::prettyPrint() const diff --git a/tests/parser/libxml_user.cpp b/tests/parser/libxml_user.cpp index ba84240c4..40e7c9fcb 100644 --- a/tests/parser/libxml_user.cpp +++ b/tests/parser/libxml_user.cpp @@ -53,7 +53,6 @@ TEST(Parser, parseValidXmlDirectlyUsingLibxml) EXPECT_NE(nullptr, doc); xmlFreeDoc(doc); xmlSetStructuredErrorFunc(nullptr, nullptr); - xmlCleanupParser(); } TEST(Parser, parseInvalidXmlDirectlyUsingLibxml) @@ -74,7 +73,6 @@ TEST(Parser, parseInvalidXmlDirectlyUsingLibxml) xmlDocPtr doc = xmlCtxtReadDoc(context, reinterpret_cast(e.c_str()), "/", nullptr, 0); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); - xmlCleanupParser(); EXPECT_EQ(nullptr, doc); } diff --git a/tests/validator/validator.cpp b/tests/validator/validator.cpp index 243d9a289..6b15bab06 100644 --- a/tests/validator/validator.cpp +++ b/tests/validator/validator.cpp @@ -18,6 +18,9 @@ limitations under the License. #include +#include +#include + #include "test_utils.h" /* @@ -4431,3 +4434,64 @@ TEST(Validator, invalidMathMLElementsChildrenOrSiblings) EXPECT_EQ_ISSUES(expectedIssues, validator); } + +TEST(Validator, validateMathmlConcurrently) +{ + // Validate a model that yields some W3C MathML DTD errors from several threads at the same time. Each thread uses + // (and, upon exiting, frees) its own parsed MathML DTD, so each thread should get the same issues as the main + // thread, which validates the model once all the other threads have exited. + + static const size_t THREAD_COUNT = 8; + static const size_t VALIDATION_COUNT = 5; + + auto validate = [](const std::string &modelContents) { + auto parser = libcellml::Parser::create(); + auto model = parser->parseModel(modelContents); + auto validator = libcellml::Validator::create(); + + validator->validateModel(model); + + std::vector issues; + + for (size_t i = 0; i < validator->issueCount(); ++i) { + issues.push_back(validator->issue(i)->description()); + } + + return issues; + }; + + auto modelContents = fileContents("invalidmathmlelementschildrenorsiblings.cellml"); + std::vector>> issues(THREAD_COUNT, std::vector>(VALIDATION_COUNT)); + std::vector threads; + std::atomic readyThreadCount(0); + + for (size_t i = 0; i < THREAD_COUNT; ++i) { + threads.emplace_back([&, i]() { + // Wait for all the threads to be ready, so that they all validate the model at the same time. + + ++readyThreadCount; + + while (readyThreadCount < THREAD_COUNT) { + std::this_thread::yield(); + } + + for (size_t j = 0; j < VALIDATION_COUNT; ++j) { + issues[i][j] = validate(modelContents); + } + }); + } + + for (auto &thread : threads) { + thread.join(); + } + + auto expectedIssues = validate(modelContents); + + EXPECT_FALSE(expectedIssues.empty()); + + for (size_t i = 0; i < THREAD_COUNT; ++i) { + for (size_t j = 0; j < VALIDATION_COUNT; ++j) { + EXPECT_EQ(expectedIssues, issues[i][j]); + } + } +}