From 232b51b3655d8a27764e2eb4a376f1a3014ac289 Mon Sep 17 00:00:00 2001 From: Tristan Stenner Date: Thu, 26 Nov 2020 11:01:13 +0100 Subject: [PATCH] Use per-thread error storage (thanks to @chkothe) --- src/common.cpp | 2 +- src/common.h | 2 +- testing/test_ext_streaminfo.cpp | 19 ++++++++++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/common.cpp b/src/common.cpp index 67aa6ac82..f6385a280 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -11,7 +11,7 @@ #include #endif -char last_error[512]; +thread_local char last_error[512] = {0}; extern "C" { diff --git a/src/common.h b/src/common.h index 34fe8689b..4fc2ae11c 100644 --- a/src/common.h +++ b/src/common.h @@ -31,7 +31,7 @@ extern "C" { "Please do not compile this with a lslboost version older than 1.45 because the library would otherwise not be protocol-compatible with builds using other versions." #endif -extern char last_error[512]; +extern thread_local char last_error[512]; // the highest supported protocol version // * 100 is the original version, supported by library versions 1.00+ diff --git a/testing/test_ext_streaminfo.cpp b/testing/test_ext_streaminfo.cpp index 29e1fd0db..1319f64ba 100644 --- a/testing/test_ext_streaminfo.cpp +++ b/testing/test_ext_streaminfo.cpp @@ -1,10 +1,27 @@ #include "catch.hpp" #include +#include namespace { TEST_CASE("streaminfo", "[streaminfo][basic]") { CHECK_THROWS(lsl::stream_info("", "emptyname")); - CHECK(std::string("The name of a stream must be non-empty.") == lsl_last_error()); + REQUIRE(std::string("The name of a stream must be non-empty.") == lsl_last_error()); +} + +TEST_CASE("multithreaded lsl_last_error", "[threading][basic]") { + CHECK_THROWS(lsl::stream_info("", "emptyname")); + std::thread([](){ + CHECK_THROWS(lsl::stream_info("hasname","type", -1)); + REQUIRE(std::string("The channel_count of a stream must be nonnegative.") == lsl_last_error()); + }).join(); + REQUIRE(std::string("The name of a stream must be non-empty.") == lsl_last_error()); +} + +/// Ensure that an overly long error message won't overflow the buffer +TEST_CASE("lsl_last_error size", "[basic]") { + std::string invalidquery(512, '\''); + CHECK_THROWS(lsl::resolve_stream(invalidquery, 1, 0.1)); + REQUIRE(lsl_last_error()[512] == 0); } } // namespace