From 251b025e95ecff001b53fa914049793019c3d1e1 Mon Sep 17 00:00:00 2001
From: Grigoris Pavlakis <grigpavl@ece.auth.gr>
Date: Sun, 31 Mar 2019 17:26:26 +0300
Subject: [PATCH] Fix bug in include() and update its test

---
 src/Services/FunctionManagementService.cpp  | 10 ++++----
 test/Services/FunctionManagementService.cpp | 26 ++++++++++++---------
 2 files changed, 20 insertions(+), 16 deletions(-)

diff --git a/src/Services/FunctionManagementService.cpp b/src/Services/FunctionManagementService.cpp
index 7ad300f6..8dcc6027 100644
--- a/src/Services/FunctionManagementService.cpp
+++ b/src/Services/FunctionManagementService.cpp
@@ -42,11 +42,11 @@ void FunctionManagementService::call(Message& msg) {
 void FunctionManagementService::include(String<FUNC_NAME_LENGTH> funcName, void(*ptr)
 	(String<MAX_ARG_LENGTH>)) {
 
-	if (funcPtrIndex.full()) {
+	if (not funcPtrIndex.full()) {  // CAUTION: etl::map won't check by itself if it's full
+		// before attempting to insert a key-value pair, causing segmentation faults. Check first!
+		funcName.append(FUNC_NAME_LENGTH - funcName.length(), '\0');
+		funcPtrIndex.insert(std::make_pair(funcName, ptr));
+	} else {
 		ErrorHandler::reportInternalError(ErrorHandler::InternalErrorType::FunctionMapFull);
-		return;
 	}
-
-	funcName.append(FUNC_NAME_LENGTH - funcName.length(), '\0');
-	funcPtrIndex.insert(std::make_pair(funcName, ptr));
 }
diff --git a/test/Services/FunctionManagementService.cpp b/test/Services/FunctionManagementService.cpp
index 5b2310b7..1cd99bf5 100644
--- a/test/Services/FunctionManagementService.cpp
+++ b/test/Services/FunctionManagementService.cpp
@@ -35,14 +35,18 @@ TEST_CASE("ST[08] - Call Tests") {
 	}
 }
 
-// WARNING! include() is malfunctioning - do not merge!
-
-//TEST_CASE("ST[08] - Insert Tests") {
-//
-//	SECTION("Insertion to full pointer map") {
-//		// make sure the pointer map is full to the brim
-//		ServiceTests::reset();
-//		std::string name = "test";  // FOR TESTING ONLY!
-//
-//	}
-//}
+
+TEST_CASE("ST[08] - Insert Tests") {
+
+	SECTION("Insertion to full pointer map") {
+		// make sure the pointer map is full to the brim
+		ServiceTests::reset();
+		std::string name = "test";  // FOR TESTING ONLY!
+
+		for (int i = 0; i < FUNC_MAP_SIZE + 1; i++) {
+			name += std::to_string(i); // different names to fill up the map
+			fms.include(String<FUNC_NAME_LENGTH>(name.c_str()), &test);
+		}
+		CHECK(ServiceTests::thrownError(ErrorHandler::InternalErrorType::FunctionMapFull));
+	}
+}
-- 
GitLab