Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions cmake/environmentchecks.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand All @@ -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
Expand Down Expand Up @@ -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()

Expand All @@ -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()

Expand Down
9 changes: 5 additions & 4 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
77 changes: 63 additions & 14 deletions src/xmldoc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -81,15 +99,14 @@ 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<void *>(this);
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, options);
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();
}

std::string decompressMathMLDTD()
Expand All @@ -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.
Comment thread
hsorby marked this conversation as resolved.
Resolved
*
* 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<int>(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;
Comment thread
agarny marked this conversation as resolved.
Resolved

xmlParserCtxtPtr context = xmlNewParserCtxt();
context->_private = reinterpret_cast<void *>(this);
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0);
xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(reinterpret_cast<const char *>(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
Expand Down
2 changes: 0 additions & 2 deletions tests/parser/libxml_user.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ TEST(Parser, parseValidXmlDirectlyUsingLibxml)
EXPECT_NE(nullptr, doc);
xmlFreeDoc(doc);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();
}

TEST(Parser, parseInvalidXmlDirectlyUsingLibxml)
Expand All @@ -74,7 +73,6 @@ TEST(Parser, parseInvalidXmlDirectlyUsingLibxml)
xmlDocPtr doc = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(e.c_str()), "/", nullptr, 0);
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();

EXPECT_EQ(nullptr, doc);
}
64 changes: 64 additions & 0 deletions tests/validator/validator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ limitations under the License.

#include <libcellml>

#include <atomic>
#include <thread>

#include "test_utils.h"

/*
Expand Down Expand Up @@ -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<std::string> 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<std::vector<std::vector<std::string>>> issues(THREAD_COUNT, std::vector<std::vector<std::string>>(VALIDATION_COUNT));
std::vector<std::thread> threads;
std::atomic<size_t> 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]);
}
}
}
Loading