已合并
fix: 加固安全敏感路径的错误处理 #103
fix: 加固安全敏感路径的错误处理 #103
已合并
yangqi创建于 20 天前
共 38 个文件变更+343-1354
@@ -28,10 +28,10 @@ public:
28 static RmLibObmmExecutor instance;28 static RmLibObmmExecutor instance;
29 return instance;29 return instance;
30 }30 }
31- RmLibObmmExecutor(const RmLibObmmExecutor &other) = default;31+ RmLibObmmExecutor(const RmLibObmmExecutor &other) = delete;
32- RmLibObmmExecutor(RmLibObmmExecutor &&other) = default;32+ RmLibObmmExecutor(RmLibObmmExecutor &&other) = delete;
33- RmLibObmmExecutor &operator=(const RmLibObmmExecutor &other) = default;33+ RmLibObmmExecutor &operator=(const RmLibObmmExecutor &other) = delete;
34- RmLibObmmExecutor &operator=(RmLibObmmExecutor &&other) noexcept = default;34+ RmLibObmmExecutor &operator=(RmLibObmmExecutor &&other) noexcept = delete;
35 35 
36 DAGGER_DEFINE_REF_COUNT_FUNCTIONS36 DAGGER_DEFINE_REF_COUNT_FUNCTIONS
37private:37private:
@@ -40,4 +40,4 @@ private:
40 RmLibObmmExecutor() = default;40 RmLibObmmExecutor() = default;
41};41};
42} // namespace ock::mxmd42} // namespace ock::mxmd
43-#endif // MEMORYFABRIC_RMLIBOBMMEXECUTOR_H43+#endif // MEMORYFABRIC_RMLIBOBMMEXECUTOR_H
@@ -253,9 +253,9 @@ uint32_t IpcProxy::Destroy()
253 return ret == UBSM_OK ? static_cast<uint32_t>(UBSM_OK) : static_cast<uint32_t>(MXM_ERR_MEMLIB);253 return ret == UBSM_OK ? static_cast<uint32_t>(UBSM_OK) : static_cast<uint32_t>(MXM_ERR_MEMLIB);
254}254}
255 255 
256-uint32_t IpcProxy::SyncCall(int opcode, MsgBase *request, MsgBase *response)256+uint32_t IpcProxy::SyncCall(int opcode, MsgBase &request, MsgBase &response)
257{257{
258- auto ret = MxmComIpcClientSend(opcode, request, response);258+ auto ret = MxmComIpcClientSend(opcode, &request, &response);
259 if (ret != 0) {259 if (ret != 0) {
260 return MXM_ERR_IPC_HCOM_INNER_SYNC_CALL;260 return MXM_ERR_IPC_HCOM_INNER_SYNC_CALL;
261 }261 }
@@ -48,7 +48,7 @@ public:
48 48 
49 static uint32_t Resume();49 static uint32_t Resume();
50 50 
51- uint32_t SyncCall(int opcode, MsgBase *request, MsgBase *response);51+ uint32_t SyncCall(int opcode, MsgBase &request, MsgBase &response);
52 52 
53 static uint32_t Destroy();53 static uint32_t Destroy();
54 54 
@@ -83,7 +83,7 @@ public:
83 uint32_t hr;83 uint32_t hr;
84 for (int i = 0; i < 3u; ++i) {84 for (int i = 0; i < 3u; ++i) {
85 TP_TRACE_BEGIN(TP_UBSM_IPC_CALL);85 TP_TRACE_BEGIN(TP_UBSM_IPC_CALL);
86- hr = SyncCall(opCode, &request, &response);86+ hr = SyncCall(opCode, request, response);
87 TP_TRACE_END(TP_UBSM_IPC_CALL, hr);87 TP_TRACE_END(TP_UBSM_IPC_CALL, hr);
88 if (hr != MXM_ERR_IPC_CRC_CHECK_ERROR && hr != MXM_ERR_IPC_SERIALIZE_DESERIALIZE_ERROR) {88 if (hr != MXM_ERR_IPC_CRC_CHECK_ERROR && hr != MXM_ERR_IPC_SERIALIZE_DESERIALIZE_ERROR) {
89 break;89 break;
@@ -104,10 +104,10 @@ public:
104 static IpcProxy instance;104 static IpcProxy instance;
105 return instance;105 return instance;
106 }106 }
107- IpcProxy(const IpcProxy &other) = default;107+ IpcProxy(const IpcProxy &other) = delete;
108- IpcProxy(IpcProxy &&other) = default;108+ IpcProxy(IpcProxy &&other) = delete;
109- IpcProxy &operator=(const IpcProxy &other) = default;109+ IpcProxy &operator=(const IpcProxy &other) = delete;
110- IpcProxy &operator=(IpcProxy &&other) noexcept = default;110+ IpcProxy &operator=(IpcProxy &&other) noexcept = delete;
111 111 
112 DAGGER_DEFINE_REF_COUNT_FUNCTIONS112 DAGGER_DEFINE_REF_COUNT_FUNCTIONS
113private:113private:
@@ -671,6 +671,10 @@ int32_t RackMemShm::UbsMemShmWriteLock(const std::string &name)
671 result = ShmMetaDataMgr::GetInstance().UpdateMetaData(name, meta);671 result = ShmMetaDataMgr::GetInstance().UpdateMetaData(name, meta);
672 if (BresultFail(result)) {672 if (BresultFail(result)) {
673 DBG_LOGERROR("Update shm meta by name failed, ret: " << result);673 DBG_LOGERROR("Update shm meta by name failed, ret: " << result);
674+ auto unlockRet = ShmIpcCommand::IpcShmemUnLock(name);
675+ if (BresultFail(unlockRet)) {
676+ DBG_LOGERROR("Rollback write lock failed, ret: " << unlockRet);
677+ }
674 return result;678 return result;
675 }679 }
676 DBG_LOGINFO("Ipc Shm WriteLock success, name=" << name);680 DBG_LOGINFO("Ipc Shm WriteLock success, name=" << name);
@@ -724,6 +728,10 @@ int32_t RackMemShm::UbsMemShmReadLock(const std::string &name)
724 result = ShmMetaDataMgr::GetInstance().UpdateMetaData(name, meta);728 result = ShmMetaDataMgr::GetInstance().UpdateMetaData(name, meta);
725 if (BresultFail(result)) {729 if (BresultFail(result)) {
726 DBG_LOGERROR("Update shm meta by name failed, ret: " << result);730 DBG_LOGERROR("Update shm meta by name failed, ret: " << result);
731+ auto unlockRet = ShmIpcCommand::IpcShmemUnLock(name);
732+ if (BresultFail(unlockRet)) {
733+ DBG_LOGERROR("Rollback read lock failed, ret: " << unlockRet);
734+ }
727 return result;735 return result;
728 }736 }
729 DBG_LOGINFO("Ipc Shm ReadLock success, name=" << name);737 DBG_LOGINFO("Ipc Shm ReadLock success, name=" << name);
@@ -862,4 +870,4 @@ int32_t RackMemShm::UbsMemQueryDlockStatus(bool &isReady)
862 return 0;870 return 0;
863}871}
864} // namespace ock::mxmd872} // namespace ock::mxmd
865-// ock873+// ock
@@ -148,9 +148,13 @@ uint32_t ShmIpcCommand::IpcCallShmLookRegionList(const std::string &baseNid, Shm
148 DBG_LOGINFO("Result of Ipc looking up regions list, number=" << shmRegions.num);148 DBG_LOGINFO("Result of Ipc looking up regions list, number=" << shmRegions.num);
149 list.num = shmRegions.num;149 list.num = shmRegions.num;
150 for (int i = 0; i < list.num; ++i) {150 for (int i = 0; i < list.num; ++i) {
151+ if (shmRegions.region[i].num < 0 || shmRegions.region[i].num > MAX_REGION_NODE_NUM) {
152+ DBG_LOGERROR("Invalid node count in region " << i << ": " << shmRegions.region[i].num);
153+ return MXM_ERR_CHECK_RESOURCE;
154+ }
151 list.region[i] = shmRegions.region[i];155 list.region[i] = shmRegions.region[i];
152 DBG_LOGINFO("Serial number=" << i << ", number=" << shmRegions.region[i].num);156 DBG_LOGINFO("Serial number=" << i << ", number=" << shmRegions.region[i].num);
153- for (int j = 0; j < shmRegions.num; ++j) {157+ for (int j = 0; j < shmRegions.region[i].num; ++j) {
154 DBG_LOGDEBUG("Node id=" << shmRegions.region[i].nodeId[j]158 DBG_LOGDEBUG("Node id=" << shmRegions.region[i].nodeId[j]
155 << ", host name=" << shmRegions.region[i].hostName[j]);159 << ", host name=" << shmRegions.region[i].hostName[j]);
156 }160 }
@@ -764,7 +768,7 @@ uint32_t ShmIpcCommand::IpcCallSuspendInner()
764 DBG_LOGERROR("Failed to allocate suspend IPC message.");768 DBG_LOGERROR("Failed to allocate suspend IPC message.");
765 return MXM_ERR_MALLOC_FAIL;769 return MXM_ERR_MALLOC_FAIL;
766 }770 }
767- auto ret = IpcProxy::GetInstance().SyncCall(IPC_SUSPEND_CLIENT, request.get(), response.get());771+ auto ret = IpcProxy::GetInstance().SyncCall(IPC_SUSPEND_CLIENT, *request, *response);
768 if (ret != UBSM_OK) {772 if (ret != UBSM_OK) {
769 DBG_LOGERROR("IpcCallSuspend failed, ret=" << ret);773 DBG_LOGERROR("IpcCallSuspend failed, ret=" << ret);
770 return ret;774 return ret;
@@ -789,7 +793,7 @@ uint32_t ShmIpcCommand::IpcCallResumeInner()
789 DBG_LOGERROR("Failed to allocate resume IPC message.");793 DBG_LOGERROR("Failed to allocate resume IPC message.");
790 return MXM_ERR_MALLOC_FAIL;794 return MXM_ERR_MALLOC_FAIL;
791 }795 }
792- auto ret = IpcProxy::GetInstance().SyncCall(IPC_RESUME_CLIENT, request.get(), response.get());796+ auto ret = IpcProxy::GetInstance().SyncCall(IPC_RESUME_CLIENT, *request, *response);
793 if (ret != UBSM_OK) {797 if (ret != UBSM_OK) {
794 DBG_LOGERROR("IpcCallResume failed, ret=" << ret);798 DBG_LOGERROR("IpcCallResume failed, ret=" << ret);
795 return ret;799 return ret;
@@ -11,6 +11,7 @@
11 */11 */
12 12 
13#include <sys/mman.h>13#include <sys/mman.h>
14+#include <new>
14#include "ubs_mem.h"15#include "ubs_mem.h"
15#include "RackMemShm.h"16#include "RackMemShm.h"
16#include "UbseMemExecutor.h"17#include "UbseMemExecutor.h"
@@ -36,9 +37,9 @@ static int find_region_desc(const char *region_name, SHMRegionDesc *region)
36 if (strcmp(region_name, "default") == 0) {37 if (strcmp(region_name, "default") == 0) {
37 std::string baseNid;38 std::string baseNid;
38 ShmRegionType type = ALL2ALL_SHARE;39 ShmRegionType type = ALL2ALL_SHARE;
39- SHMRegions *regions = static_cast<SHMRegions *>(malloc(sizeof(SHMRegions)));40+ SHMRegions *regions = new (std::nothrow) SHMRegions{};
40 if (regions == nullptr) {41 if (regions == nullptr) {
41- DBG_LOGERROR("SHMRegions malloc failed.");42+ DBG_LOGERROR("SHMRegions allocation failed.");
42 return MXM_ERR_MALLOC_FAIL;43 return MXM_ERR_MALLOC_FAIL;
43 }44 }
44 TP_TRACE_BEGIN(TP_UBSM_LOOKUP_REGION_DEFAULT_IPC_REQUEST);45 TP_TRACE_BEGIN(TP_UBSM_LOOKUP_REGION_DEFAULT_IPC_REQUEST);
@@ -46,17 +47,17 @@ static int find_region_desc(const char *region_name, SHMRegionDesc *region)
46 TP_TRACE_END(TP_UBSM_LOOKUP_REGION_DEFAULT_IPC_REQUEST, ret);47 TP_TRACE_END(TP_UBSM_LOOKUP_REGION_DEFAULT_IPC_REQUEST, ret);
47 if (ret != 0) {48 if (ret != 0) {
48 DBG_LOGERROR("Failed to lookup shared regions, ret=" << ret);49 DBG_LOGERROR("Failed to lookup shared regions, ret=" << ret);
49- free(regions);50+ ock::mxmd::SafeDelete(regions);
50 return ret;51 return ret;
51 }52 }
52 if (regions->num <= 0) {53 if (regions->num <= 0) {
53 DBG_LOGERROR("Failed to lookup shared Region, region number=" << ret);54 DBG_LOGERROR("Failed to lookup shared Region, region number=" << ret);
54- free(regions);55+ ock::mxmd::SafeDelete(regions);
55 return ret;56 return ret;
56 }57 }
57 58 
58 *region = regions->region[0];59 *region = regions->region[0];
59- free(regions);60+ ock::mxmd::SafeDelete(regions);
60 61 
61 DBG_LOGINFO("Get region successfully, name=" << region_name);62 DBG_LOGINFO("Get region successfully, name=" << region_name);
62 return UBSM_OK;63 return UBSM_OK;
@@ -75,30 +76,36 @@ static int find_region_desc(const char *region_name, SHMRegionDesc *region)
75 return UBSM_OK;76 return UBSM_OK;
76}77}
77 78 
78-static int translate_to_region_attributes(SHMRegionDesc *regionDesc, ubsmem_region_attributes_t *region_attr)79+static int translate_to_region_attributes(const SHMRegionDesc &regionDesc, ubsmem_region_attributes_t &regionAttr)
79{80{
80- region_attr->host_num = regionDesc->num;81+ if (regionDesc.num < 0 || regionDesc.num > MAX_REGION_NODE_NUM) {
82+ return MXM_ERR_REGION_PARAM_INVALID;
83+ }
84+ regionAttr.host_num = regionDesc.num;
81 85 
82- for (int i = 0; i < regionDesc->num; i++) {86+ for (int i = 0; i < regionDesc.num; i++) {
83- auto ret = strcpy_s(region_attr->hosts[i].host_name, MAX_HOST_NAME_DESC_LENGTH, regionDesc->hostName[i]);87+ auto ret = strcpy_s(regionAttr.hosts[i].host_name, MAX_HOST_NAME_DESC_LENGTH, regionDesc.hostName[i]);
84 if (ret != UBSM_OK) {88 if (ret != UBSM_OK) {
85 DBG_LOGERROR("host name copy error, ret=" << ret);89 DBG_LOGERROR("host name copy error, ret=" << ret);
86 return MXM_ERR_MEMORY;90 return MXM_ERR_MEMORY;
87 }91 }
88- region_attr->hosts[i].affinity = regionDesc->affinity[i];92+ regionAttr.hosts[i].affinity = regionDesc.affinity[i];
89- DBG_LOGINFO("Coping region name=" << region_attr->hosts[i].host_name93+ DBG_LOGINFO("Coping region name=" << regionAttr.hosts[i].host_name
90- << ", affinity=" << region_attr->hosts[i].affinity << " to list");94+ << ", affinity=" << regionAttr.hosts[i].affinity << " to list");
91 }95 }
92 96 
93 return UBSM_OK;97 return UBSM_OK;
94}98}
95 99 
96-static int translate_to_regions(SHMRegions *list, ubsmem_regions_t *regions)100+static int translate_to_regions(const SHMRegions &list, ubsmem_regions_t &regions)
97{101{
98- regions->num = list->num;102+ if (list.num < 0 || list.num > MAX_REGIONS_NUM) {
103+ return MXM_ERR_REGION_PARAM_INVALID;
104+ }
105+ regions.num = list.num;
99 106 
100- for (int i = 0; i < list->num; i++) {107+ for (int i = 0; i < list.num; i++) {
101- auto ret = translate_to_region_attributes(&list->region[i], &regions->region[i]);108+ auto ret = translate_to_region_attributes(list.region[i], regions.region[i]);
102 if (ret != UBSM_OK) {109 if (ret != UBSM_OK) {
103 DBG_LOGERROR("region attribute copy error, ret=" << ret);110 DBG_LOGERROR("region attribute copy error, ret=" << ret);
104 return ret;111 return ret;
@@ -117,7 +124,7 @@ static int translate_to_region_desc(const char *region_name, SHMRegionDesc *regi
117 return MXM_ERR_MEMORY;124 return MXM_ERR_MEMORY;
118 }125 }
119 region_desc->size = 0;126 region_desc->size = 0;
120- ret = translate_to_region_attributes(regionDesc, &region_desc->region_attr);127+ ret = translate_to_region_attributes(*regionDesc, region_desc->region_attr);
121 if (ret != UBSM_OK) {128 if (ret != UBSM_OK) {
122 DBG_LOGERROR("region attributes copy error, ret=" << ret);129 DBG_LOGERROR("region attributes copy error, ret=" << ret);
123 return ret;130 return ret;
@@ -125,58 +132,62 @@ static int translate_to_region_desc(const char *region_name, SHMRegionDesc *regi
125 return UBSM_OK;132 return UBSM_OK;
126}133}
127 134 
128-static bool contain_all_hosts_in_attr(SHMRegionDesc *regionDesc, const ubsmem_region_attributes_t *reg_attr)135+static bool contain_all_hosts_in_attr(SHMRegionDesc &regionDesc, const ubsmem_region_attributes_t &regAttr)
129{136{
137+ if (regionDesc.num < 0 || regionDesc.num > MAX_REGION_NODE_NUM || regAttr.host_num < 0 ||
138+ regAttr.host_num > MAX_REGION_NODE_NUM) {
139+ return false;
140+ }
130 bool flag[MAX_REGION_NODE_NUM] = {false};141 bool flag[MAX_REGION_NODE_NUM] = {false};
131 int i;142 int i;
132 int j;143 int j;
133 144 
134- for (i = 0; i < reg_attr->host_num; i++) {145+ for (i = 0; i < regAttr.host_num; i++) {
135- for (j = 0; j < regionDesc->num; j++) {146+ for (j = 0; j < regionDesc.num; j++) {
136 if (flag[j]) {147 if (flag[j]) {
137 continue;148 continue;
138 }149 }
139- DBG_LOGDEBUG("Host name=" << reg_attr->hosts[i].host_name);150+ DBG_LOGDEBUG("Host name=" << regAttr.hosts[i].host_name);
140- if (strcmp(reg_attr->hosts[i].host_name, regionDesc->hostName[j]) == 0) {151+ if (strcmp(regAttr.hosts[i].host_name, regionDesc.hostName[j]) == 0) {
141 flag[j] = true;152 flag[j] = true;
142- regionDesc->affinity[j] = reg_attr->hosts[i].affinity;153+ regionDesc.affinity[j] = regAttr.hosts[i].affinity;
143- DBG_LOGDEBUG("affinity[" << j << "]=" << regionDesc->affinity[j] << ", i=" << i);154+ DBG_LOGDEBUG("affinity[" << j << "]=" << regionDesc.affinity[j] << ", i=" << i);
144 break;155 break;
145 }156 }
146 }157 }
147- if (j == regionDesc->num) {158+ if (j == regionDesc.num) {
148- DBG_LOGERROR("Failed to find host name=" << reg_attr->hosts[i].host_name);159+ DBG_LOGERROR("Failed to find host name=" << regAttr.hosts[i].host_name);
149 return false;160 return false;
150 }161 }
151 }162 }
152 int k = 0;163 int k = 0;
153- for (j = 0; j < regionDesc->num; j++) {164+ for (j = 0; j < regionDesc.num; j++) {
154 if (!flag[j]) {165 if (!flag[j]) {
155 continue;166 continue;
156 }167 }
157 if (k != j) {168 if (k != j) {
158- auto ret = strcpy_s(regionDesc->nodeId[k], MEM_MAX_ID_LENGTH, regionDesc->nodeId[j]);169+ auto ret = strcpy_s(regionDesc.nodeId[k], MEM_MAX_ID_LENGTH, regionDesc.nodeId[j]);
159 if (ret != UBSM_OK) {170 if (ret != UBSM_OK) {
160 DBG_LOGERROR("Failed to copy node id, ret=" << ret);171 DBG_LOGERROR("Failed to copy node id, ret=" << ret);
161 return false;172 return false;
162 }173 }
163- ret = strcpy_s(regionDesc->hostName[k], MAX_HOST_NAME_DESC_LENGTH, regionDesc->hostName[j]);174+ ret = strcpy_s(regionDesc.hostName[k], MAX_HOST_NAME_DESC_LENGTH, regionDesc.hostName[j]);
164 if (ret != UBSM_OK) {175 if (ret != UBSM_OK) {
165 DBG_LOGERROR("Failed to copy host name, ret=" << ret);176 DBG_LOGERROR("Failed to copy host name, ret=" << ret);
166 return false;177 return false;
167 }178 }
168- regionDesc->affinity[k] = regionDesc->affinity[j];179+ regionDesc.affinity[k] = regionDesc.affinity[j];
169 }180 }
170 k++;181 k++;
171 }182 }
172- regionDesc->num = k;183+ regionDesc.num = k;
173 return true;184 return true;
174}185}
175 186 
176static int filter_all_hosts_in_attr(SHMRegions *list, const ubsmem_region_attributes_t *reg_attr, int &index)187static int filter_all_hosts_in_attr(SHMRegions *list, const ubsmem_region_attributes_t *reg_attr, int &index)
177{188{
178 for (int i = 0; i < list->num; i++) {189 for (int i = 0; i < list->num; i++) {
179- if (contain_all_hosts_in_attr(&list->region[i], reg_attr)) {190+ if (contain_all_hosts_in_attr(list->region[i], *reg_attr)) {
180 index = i;191 index = i;
181 return UBSM_OK;192 return UBSM_OK;
182 }193 }
@@ -305,16 +316,16 @@ uint32_t ubsmem_shmem_allocate_impl(const char *region_name, const char *name, s
305 DBG_LOGINFO("Allocating shared memory, region=" << region_name << ", name=" << name << ", size=" << size);316 DBG_LOGINFO("Allocating shared memory, region=" << region_name << ", name=" << name << ", size=" << size);
306 std::string regionName = region_name;317 std::string regionName = region_name;
307 std::string baseNid;318 std::string baseNid;
308- auto regions = static_cast<SHMRegionDesc *>(malloc(sizeof(SHMRegionDesc)));319+ auto regions = new (std::nothrow) SHMRegionDesc{};
309 if (regions == nullptr) {320 if (regions == nullptr) {
310- DBG_LOGERROR("SHMRegions malloc failed.");321+ DBG_LOGERROR("SHMRegionDesc allocation failed.");
311 return MXM_ERR_MALLOC_FAIL;322 return MXM_ERR_MALLOC_FAIL;
312 }323 }
313 324 
314 auto ret = find_region_desc(region_name, regions);325 auto ret = find_region_desc(region_name, regions);
315 if (ret != 0) {326 if (ret != 0) {
316 DBG_LOGERROR("RackMemShmLookupShareRegions failed, ret=" << ret);327 DBG_LOGERROR("RackMemShmLookupShareRegions failed, ret=" << ret);
317- free(regions);328+ ock::mxmd::SafeDelete(regions);
318 return ret;329 return ret;
319 }330 }
320 331 
@@ -323,11 +334,11 @@ uint32_t ubsmem_shmem_allocate_impl(const char *region_name, const char *name, s
323 TP_TRACE_END(TP_UBSM_SHM_CREATE_IPC_REQUEST, ret);334 TP_TRACE_END(TP_UBSM_SHM_CREATE_IPC_REQUEST, ret);
324 if (ret != 0) {335 if (ret != 0) {
325 DBG_LOGERROR("UbsMemShmCreate failed, ret=" << ret);336 DBG_LOGERROR("UbsMemShmCreate failed, ret=" << ret);
326- free(regions);337+ ock::mxmd::SafeDelete(regions);
327 return ret;338 return ret;
328 }339 }
329 340 
330- free(regions);341+ ock::mxmd::SafeDelete(regions);
331 DBG_LOGINFO("Allocating shared memory successfully, memory name=" << name);342 DBG_LOGINFO("Allocating shared memory successfully, memory name=" << name);
332 return UBSM_OK;343 return UBSM_OK;
333}344}
@@ -587,9 +598,9 @@ uint32_t ubsm_lookup_regions_ompl(ubsmem_regions_t *regions)
587 DBG_LOGINFO("Start to looking up regions");598 DBG_LOGINFO("Start to looking up regions");
588 std::string baseNid;599 std::string baseNid;
589 ShmRegionType type = ALL2ALL_SHARE;600 ShmRegionType type = ALL2ALL_SHARE;
590- SHMRegions *list = static_cast<SHMRegions *>(malloc(sizeof(SHMRegions)));601+ SHMRegions *list = new (std::nothrow) SHMRegions{};
591 if (list == nullptr) {602 if (list == nullptr) {
592- DBG_LOGERROR("Failed to malloc, error info=no memory.");603+ DBG_LOGERROR("Failed to allocate SHMRegions, error info=no memory.");
593 return MXM_ERR_MALLOC_FAIL;604 return MXM_ERR_MALLOC_FAIL;
594 }605 }
595 TP_TRACE_BEGIN(TP_UBSM_LOOKUP_REGIONS_IPC_REQUEST);606 TP_TRACE_BEGIN(TP_UBSM_LOOKUP_REGIONS_IPC_REQUEST);
@@ -597,17 +608,17 @@ uint32_t ubsm_lookup_regions_ompl(ubsmem_regions_t *regions)
597 TP_TRACE_END(TP_UBSM_LOOKUP_REGIONS_IPC_REQUEST, ret);608 TP_TRACE_END(TP_UBSM_LOOKUP_REGIONS_IPC_REQUEST, ret);
598 if (ret != UBSM_OK) {609 if (ret != UBSM_OK) {
599 DBG_LOGERROR("LookupResourceRegions fail, ret is: " << ret);610 DBG_LOGERROR("LookupResourceRegions fail, ret is: " << ret);
600- free(list);611+ ock::mxmd::SafeDelete(list);
601 return ret;612 return ret;
602 }613 }
603 614 
604- ret = translate_to_regions(list, regions);615+ ret = translate_to_regions(*list, *regions);
605 if (ret != UBSM_OK) {616 if (ret != UBSM_OK) {
606 DBG_LOGERROR("Translating regiosn to nodes list, ret=" << ret);617 DBG_LOGERROR("Translating regiosn to nodes list, ret=" << ret);
607- free(list);618+ ock::mxmd::SafeDelete(list);
608 return ret;619 return ret;
609 }620 }
610- free(list);621+ ock::mxmd::SafeDelete(list);
611 DBG_LOGINFO("Looking up regions successfully");622 DBG_LOGINFO("Looking up regions successfully");
612 return UBSM_OK;623 return UBSM_OK;
613}624}
@@ -635,7 +646,7 @@ uint32_t ubsmem_create_region_impl(const char *region_name, size_t size, const u
635 646 
636 std::string baseNid;647 std::string baseNid;
637 ShmRegionType type = ALL2ALL_SHARE;648 ShmRegionType type = ALL2ALL_SHARE;
638- SHMRegions *list = static_cast<SHMRegions *>(malloc(sizeof(SHMRegions)));649+ SHMRegions *list = new (std::nothrow) SHMRegions{};
639 if (list == nullptr) {650 if (list == nullptr) {
640 DBG_LOGERROR("Failed to SHMRegions, error info=no memory");651 DBG_LOGERROR("Failed to SHMRegions, error info=no memory");
641 return MXM_ERR_MALLOC_FAIL;652 return MXM_ERR_MALLOC_FAIL;
@@ -650,7 +661,7 @@ uint32_t ubsmem_create_region_impl(const char *region_name, size_t size, const u
650 TP_TRACE_END(TP_UBSM_LOOKUP_REGIONS_IPC_REQUEST, ret);661 TP_TRACE_END(TP_UBSM_LOOKUP_REGIONS_IPC_REQUEST, ret);
651 if (ret != UBSM_OK) {662 if (ret != UBSM_OK) {
652 DBG_LOGERROR("Failed to look up regions, ret=" << ret);663 DBG_LOGERROR("Failed to look up regions, ret=" << ret);
653- free(list);664+ ock::mxmd::SafeDelete(list);
654 return ret;665 return ret;
655 }666 }
656 667 
@@ -658,7 +669,7 @@ uint32_t ubsmem_create_region_impl(const char *region_name, size_t size, const u
658 ret = filter_all_hosts_in_attr(list, reg_attr, index);669 ret = filter_all_hosts_in_attr(list, reg_attr, index);
659 if (ret != UBSM_OK || index >= MAX_REGIONS_NUM) {670 if (ret != UBSM_OK || index >= MAX_REGIONS_NUM) {
660 DBG_LOGERROR("Failed to filter designated region, index=" << index << ", ret=" << ret);671 DBG_LOGERROR("Failed to filter designated region, index=" << index << ", ret=" << ret);
661- free(list);672+ ock::mxmd::SafeDelete(list);
662 return ret;673 return ret;
663 }674 }
664 675 
@@ -668,11 +679,11 @@ uint32_t ubsmem_create_region_impl(const char *region_name, size_t size, const u
668 TP_TRACE_END(TP_UBSM_CREATE_REGIONS_IPC_REQUEST, ret);679 TP_TRACE_END(TP_UBSM_CREATE_REGIONS_IPC_REQUEST, ret);
669 if (ret != UBSM_OK) {680 if (ret != UBSM_OK) {
670 DBG_LOGERROR("Failed to create resource region, ret=" << ret);681 DBG_LOGERROR("Failed to create resource region, ret=" << ret);
671- free(list);682+ ock::mxmd::SafeDelete(list);
672 return ret;683 return ret;
673 }684 }
674 685 
675- free(list);686+ ock::mxmd::SafeDelete(list);
676 687 
677 DBG_LOGINFO("Create region successfully, region name=" << region_name);688 DBG_LOGINFO("Create region successfully, region name=" << region_name);
678 return UBSM_OK;689 return UBSM_OK;
@@ -705,9 +716,9 @@ uint32_t ubsmem_lookup_region_impl(const char *region_name, ubsmem_region_desc_t
705 return MXM_ERR_MEMLIB;716 return MXM_ERR_MEMLIB;
706 }717 }
707 718 
708- SHMRegionDesc *region = static_cast<SHMRegionDesc *>(malloc(sizeof(SHMRegionDesc)));719+ SHMRegionDesc *region = new (std::nothrow) SHMRegionDesc{};
709 if (region == nullptr) {720 if (region == nullptr) {
710- DBG_LOGERROR("SHMRegion malloc failed.");721+ DBG_LOGERROR("SHMRegion allocation failed.");
711 return MXM_ERR_MALLOC_FAIL;722 return MXM_ERR_MALLOC_FAIL;
712 }723 }
713 724 
@@ -718,17 +729,17 @@ uint32_t ubsmem_lookup_region_impl(const char *region_name, ubsmem_region_desc_t
718 TP_TRACE_END(TP_UBSM_LOOKUP_REGION_IPC_REQUEST, ret);729 TP_TRACE_END(TP_UBSM_LOOKUP_REGION_IPC_REQUEST, ret);
719 if (ret != UBSM_OK) {730 if (ret != UBSM_OK) {
720 DBG_LOGERROR("Failed to look up resource region, ret=" << ret);731 DBG_LOGERROR("Failed to look up resource region, ret=" << ret);
721- free(region);732+ ock::mxmd::SafeDelete(region);
722 return ret;733 return ret;
723 }734 }
724 735 
725 ret = translate_to_region_desc(region_name, region, region_desc);736 ret = translate_to_region_desc(region_name, region, region_desc);
726 if (ret != UBSM_OK) {737 if (ret != UBSM_OK) {
727 DBG_LOGERROR("translate region info, ret=" << ret);738 DBG_LOGERROR("translate region info, ret=" << ret);
728- free(region);739+ ock::mxmd::SafeDelete(region);
729 return ret;740 return ret;
730 }741 }
731- free(region);742+ ock::mxmd::SafeDelete(region);
732 DBG_LOGINFO("Looking up region successfully, region name=" << region_name);743 DBG_LOGINFO("Looking up region successfully, region name=" << region_name);
733 return UBSM_OK;744 return UBSM_OK;
734}745}
@@ -1,475 +0,0 @@
1-/*
2- * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3- 
4- * ubs-mem is licensed under the Mulan PSL v2.
5- * You can use this software according to the terms and conditions of the Mulan PSL v2.
6- * You may obtain a copy of Mulan PSL v2 at:
7- * http://license.coscl.org.cn/MulanPSL2
8- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
9- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
10- * See the Mulan PSL v2 for more details.
11- */
12-#ifndef HDAGGER_DG_RING_BUFFER_QUEUE_H
13-#define HDAGGER_DG_RING_BUFFER_QUEUE_H
14- 
15-#include <semaphore.h>
16-#include <sstream>
17- 
18-#include "../lock/dg_lock.h"
19- 
20-namespace ock {
21-namespace dagger {
22-/*
23- * @brief A ring buffer, guarded by spin lock, allow flex capacity
24- */
25-template <typename T>
26-class RingBuffer {
27-public:
28- explicit RingBuffer(uint32_t capacity) : mCapacity(capacity) {}
29- 
30- RingBuffer() = delete;
31- 
32- ~RingBuffer()
33- {
34- UnInitialize();
35- }
36- 
37- /*
38- * @brief Set capacity, which should be called before initialize
39- *
40- * @param capacity [in] capacity number
41- */
42- inline void Capacity(uint32_t capacity)
43- {
44- if (mRingBuf == nullptr) {
45- mCapacity = capacity;
46- }
47- }
48- 
49- /*
50- * @brief Get capacity
51- *
52- * @return capacity
53- */
54- inline uint32_t Capacity() const
55- {
56- return mCapacity;
57- }
58- 
59- /*
60- * @brief Initialize ring buffer
61- *
62- * @return 0 if successful, -1 in two cases:
63- * a) capacity is not valid, i.e. 0
64- * b) failed to malloc bucket for the ring
65- */
66- inline int32_t Initialize()
67- {
68- if (mCapacity == 0) {
69- return -1;
70- }
71- 
72- mCount = 0;
73- mHead = 0;
74- mTail = 0;
75- 
76- if (mRingBuf != nullptr) {
77- return 0;
78- }
79- 
80- mRingBuf = new (std::nothrow) T[mCapacity];
81- if (mRingBuf == nullptr) {
82- return -1;
83- }
84- 
85- return 0;
86- }
87- 
88- /*
89- * @brief UnInitialize the ring buffer
90- */
91- inline void UnInitialize()
92- {
93- if (mRingBuf == nullptr) {
94- return;
95- }
96- 
97- delete[] mRingBuf;
98- mRingBuf = nullptr;
99- }
100- 
101- /*
102- * @brief Push back an item into ring buffer, must be initialized firstly
103- *
104- * @param item [in] item to push back
105- *
106- * @return true if successful, false if the ring buffer is full
107- */
108- inline bool PushBack(const T &item)
109- {
110- mLock.DoLock();
111- if (mCapacity <= mCount) {
112- mLock.UnLock();
113- return false;
114- }
115- 
116- mRingBuf[mTail] = item;
117- if (mTail != mCapacity - 1) {
118- ++mTail;
119- } else {
120- mTail = 0;
121- }
122- ++mCount;
123- mLock.UnLock();
124- return true;
125- }
126- 
127- /*
128- * @brief Push front an item into ring buffer, must be initialized firstly
129- *
130- * @param item [in] item to push front
131- *
132- * @return true if successful, false if the ring buffer is full
133- */
134- inline bool PushFront(const T &item)
135- {
136- mLock.DoLock();
137- if (mCapacity <= mCount) {
138- mLock.UnLock();
139- return false;
140- }
141- 
142- /* move to tail */
143- if (mHead == 0) {
144- mHead = mCapacity - 1;
145- } else {
146- mHead--;
147- }
148- 
149- mRingBuf[mHead] = item;
150- ++mCount;
151- 
152- mLock.UnLock();
153- return true;
154- }
155- 
156- /*
157- * @brief Pop an item from front of ring buffer, must be initialized firstly
158- *
159- * @param item [out] item popped in front
160- *
161- * @return true if successful, false if the ring buffer is empty
162- */
163- inline bool PopFront(T &item)
164- {
165- mLock.DoLock();
166- if (mCount == 0) {
167- mLock.UnLock();
168- return false;
169- }
170- 
171- item = mRingBuf[mHead];
172- if (mHead != mCapacity - 1) {
173- ++mHead;
174- } else {
175- mHead = 0;
176- }
177- --mCount;
178- mLock.UnLock();
179- return true;
180- }
181- 
182- /*
183- * @brief Pop N items from front of ring buffer, must be initialized firstly
184- * and caller must ensure items is not null
185- *
186- * @param items [out] item popped in front
187- * @param n [out] item count popped in front
188- *
189- * @return true if successful, false if the ring buffer doesn't have n items
190- */
191- inline bool PopFrontN(T *items, uint32_t n)
192- {
193- mLock.DoLock();
194- if (mCount < n) {
195- mLock.UnLock();
196- return false;
197- }
198- 
199- for (uint32_t i = 0; i < n; ++i) {
200- items[i] = mRingBuf[mHead];
201- if (mHead != mCapacity - 1) {
202- ++mHead;
203- } else {
204- mHead = 0;
205- }
206- }
207- 
208- mCount -= n;
209- 
210- mLock.UnLock();
211- return true;
212- }
213- 
214- /*
215- * @brief Pop N items from front of ring buffer, must be initialized firstly
216- * and caller must ensure items is not null
217- *
218- * @param items [out] item popped in front
219- * @param n [out] item count popped in front actually
220- *
221- * @return true if successful, false if the ring buffer is empty
222- */
223- inline bool PopFrontNFlex(T *items, uint32_t &n)
224- {
225- mLock.DoLock();
226- if (mCount == 0) {
227- mLock.UnLock();
228- return false;
229- }
230- 
231- n = mCount < n ? mCount : n;
232- 
233- for (uint32_t i = 0; i < n; ++i) {
234- items[i] = mRingBuf[mHead];
235- if (mHead != mCapacity - 1) {
236- ++mHead;
237- } else {
238- mHead = 0;
239- }
240- }
241- 
242- mCount -= n;
243- 
244- mLock.UnLock();
245- return true;
246- }
247- 
248- /*
249- * @brief Push front N items into ring buffer, must be initialized firstly
250- * and caller must ensure items is not null
251- *
252- * @param items [in] item to push front
253- * @param n [in] item count to push
254- *
255- * @return true if successful, false if the ring buffer doesn't have free bucket
256- */
257- inline bool PushFrontN(T *items, uint32_t n)
258- {
259- mLock.DoLock();
260- if (mCapacity < (mCount + n)) {
261- mLock.UnLock();
262- return false;
263- }
264- 
265- for (uint32_t i = 0; i < n; ++i) {
266- // move to tail
267- if (mHead == 0) {
268- mHead = mCapacity - 1;
269- } else {
270- mHead--;
271- }
272- 
273- mRingBuf[mHead] = items[i];
274- }
275- mCount += n;
276- 
277- mLock.UnLock();
278- return true;
279- }
280- 
281- /*
282- * @brief Push back N items into ring buffer, must be initialized firstly
283- * and caller must ensure items is not null
284- *
285- * @param items [in] item to push back
286- * @param n [in] item count to push
287- *
288- * @return true if successful, false if the ring buffer doesn't have free bucket
289- */
290- inline bool PushBackN(T *items, uint32_t n)
291- {
292- mLock.DoLock();
293- if (mCapacity < (mCount + n)) {
294- mLock.UnLock();
295- return false;
296- }
297- 
298- for (uint32_t i = 0; i < n; ++i) {
299- mRingBuf[mTail] = items[i];
300- if (mTail != mCapacity - 1) {
301- ++mTail;
302- } else {
303- mTail = 0;
304- }
305- }
306- mCount += n;
307- 
308- mLock.UnLock();
309- return true;
310- }
311- 
312- /*
313- * @brief Get size of ring buffer
314- *
315- * @return size of item in ring buffer
316- */
317- inline uint32_t Size()
318- {
319- mLock.DoLock();
320- auto temp = mCount;
321- mLock.UnLock();
322- return temp;
323- }
324- 
325- /*
326- * @brief Brief ring buffer info to string
327- */
328- inline std::string ToString()
329- {
330- std::ostringstream oss;
331- oss << "head " << mHead << ", tail " << mTail << ", capacity " << mCapacity << ", count " << mCount;
332- return oss.str();
333- }
334- 
335- RingBuffer(const RingBuffer &) = delete;
336- RingBuffer(RingBuffer &&) = delete;
337- RingBuffer &operator=(const RingBuffer &) = delete;
338- RingBuffer &operator=(RingBuffer &&) = delete;
339- 
340-private:
341- T *mRingBuf = nullptr;
342- SpinLock mLock;
343- uint32_t mCapacity = 0;
344- uint32_t mCount = 0;
345- uint32_t mHead = 0;
346- uint32_t mTail = 0;
347-};
348- 
349-/*
350- * @brief A blocking queue on top of ring buffer
351- */
352-template <typename T>
353-class RingBufferBlockingQueue {
354-public:
355- explicit RingBufferBlockingQueue(uint32_t capacity) : mRingBuffer(capacity) {}
356- 
357- ~RingBufferBlockingQueue()
358- {
359- UnInitialize();
360- }
361- 
362- /*
363- * @brief Initialize the queue
364- *
365- * @return 0 if successful, -1 if sem_init failed or inner ring buffer initialization failed
366- */
367- inline int Initialize()
368- {
369- if (sem_init(&mSem, 0, 0) != 0) {
370- return -1;
371- }
372- 
373- return mRingBuffer.Initialize();
374- }
375- 
376- /*
377- * @brief UnInitialized
378- */
379- inline void UnInitialize()
380- {
381- mRingBuffer.UnInitialize();
382- sem_destroy(&mSem);
383- }
384- 
385- /*
386- * @brief Enqueue an item into queue and notify to waiters
387- *
388- * @param item [in] item to be enqueued
389- *
390- * @return true if successful, false if queue is full
391- */
392- inline bool Enqueue(const T &item)
393- {
394- auto result = mRingBuffer.PushBack(item);
395- if (result) {
396- sem_post(&mSem);
397- }
398- return result;
399- }
400- 
401- /*
402- * @brief Enqueue an item into queue and notify to waiters
403- *
404- * @param item [in] item to be enqueued
405- *
406- * @return true if successful, false if queue is full
407- */
408- inline bool Enqueue(T &item)
409- {
410- auto result = mRingBuffer.PushBack(item);
411- if (result) {
412- sem_post(&mSem);
413- }
414- return result;
415- }
416- 
417- /*
418- * @brief Enqueue an item into queue in the front and notify to waiters
419- *
420- * @param item [in] item to be enqueued
421- *
422- * @return true if successful, false if queue is full
423- */
424- inline bool EnqueueFirst(T &item)
425- {
426- auto result = mRingBuffer.PushFront(item);
427- if (result) {
428- sem_post(&mSem);
429- }
430- return result;
431- }
432- 
433- /*
434- * @brief Enqueue an item into queue in the front and notify to waiters
435- *
436- * @param item [in] item to be enqueued
437- *
438- * @return true if successful, false if queue is full
439- */
440- inline bool EnqueueFirst(const T &item)
441- {
442- auto result = mRingBuffer.PushFront(item);
443- if (result) {
444- sem_post(&mSem);
445- }
446- return result;
447- }
448- 
449- /*
450- * @brief Dequeue an item from queue in the front, wait if no item
451- *
452- * @param item [in] item to be enqueued
453- *
454- * @return true if successful, false if queue is empty
455- */
456- inline bool Dequeue(T &item)
457- {
458- while (true) {
459- auto result = mRingBuffer.PopFront(item);
460- if (!result) {
461- sem_wait(&mSem);
462- } else {
463- return result;
464- }
465- }
466- }
467- 
468-private:
469- RingBuffer<T> mRingBuffer; /* ring buffer to data store */
470- sem_t mSem{}; /* semaphore to wait and notify */
471-};
472-} // namespace dagger
473-} // namespace ock
474- 
475-#endif // HDAGGER_DG_RING_BUFFER_QUEUE_H
@@ -1,320 +0,0 @@
1-/*
2- * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3- 
4- * ubs-mem is licensed under the Mulan PSL v2.
5- * You can use this software according to the terms and conditions of the Mulan PSL v2.
6- * You may obtain a copy of Mulan PSL v2 at:
7- * http://license.coscl.org.cn/MulanPSL2
8- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
9- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
10- * See the Mulan PSL v2 for more details.
11- */
12-#ifndef HDAGGER_DG_EXECUTION_SERVICE_H
13-#define HDAGGER_DG_EXECUTION_SERVICE_H
14-#include <unistd.h>
15-#include <atomic>
16-#include <functional>
17-#include <mutex>
18-#include <thread>
19-#include <vector>
20- 
21-#include "../container/dg_ring_buffer.h"
22-#include "../dg_common.h"
23-#include "../referable/dg_ref.h"
24-#include "log.h"
25- 
26-namespace ock {
27-namespace dagger {
28-enum RunnableType {
29- NORMAL = 0,
30- STOP = 1,
31-};
32- 
33-/*
34- * @brief Base class of runnable task
35- */
36-class Runnable {
37-public:
38- Runnable() : mTask{nullptr} {}
39- 
40- explicit Runnable(const std::function<void()> &task) : mTask{task} {}
41- virtual ~Runnable() = default;
42- 
43- virtual void Run()
44- {
45- if (mTask != nullptr) {
46- mTask();
47- }
48- }
49- 
50- DAGGER_DEFINE_REF_COUNT_FUNCTIONS
51-private:
52- inline void Type(RunnableType type)
53- {
54- mType = type;
55- }
56- 
57- inline RunnableType Type() const
58- {
59- return mType;
60- }
61- 
62-private:
63- RunnableType mType = RunnableType::NORMAL;
64- std::function<void()> mTask;
65- 
66- DAGGER_DEFINE_REF_COUNT_VARIABLE
67- 
68- friend class ExecutorService;
69-};
70-using RunnablePtr = Ref<Runnable>;
71- 
72-constexpr uint32_t ES_MAX_THR_NUM = 256;
73- 
74-class ExecutorService;
75-using ExecutorServicePtr = Ref<ExecutorService>;
76- 
77-/*
78- * @brief Execution service is fixed thread pool to task execution
79- */
80-class ExecutorService {
81-public:
82- /*
83- * @brief Create an execution service with fixed number of threads
84- *
85- * @param threadNum [in] number of threads
86- * @param queueCapacity [in] capacity of inner queue to store tasks
87- *
88- * @return executor ptr if successfully, otherwise return null
89- */
90- static ExecutorServicePtr Create(uint16_t threadNum, uint32_t queueCapacity = 10000)
91- {
92- if (threadNum > ES_MAX_THR_NUM || threadNum == 0) {
93- DBG_LOGERROR("The num of thread must 1-" << ES_MAX_THR_NUM);
94- return nullptr;
95- }
96- 
97- return new (std::nothrow) ExecutorService(threadNum, queueCapacity);
98- }
99- 
100-public:
101- ~ExecutorService()
102- {
103- if (!mStopped) {
104- Stop();
105- }
106- 
107- while (!mThreads.empty()) {
108- delete (mThreads.back());
109- mThreads.pop_back();
110- }
111- }
112- 
113- /*
114- * @brief Start the execution service, wait for all threads started
115- *
116- * @return true if successfully
117- */
118- bool Start();
119- 
120- /*
121- * @brief Stop the execution service, wait for all threads exited
122- */
123- void Stop();
124- 
125- /*
126- * @brief Enqueue a task to thread pool, need to ensure this has been started
127- *
128- * The ref count of runnable will be increased and will be decreased after executed
129- *
130- * @return true if enqueue successfully, otherwise the queue is full
131- */
132- inline bool Execute(const RunnablePtr &runnable)
133- {
134- auto tmp = runnable.Get();
135- if (DAGGER_UNLIKELY(tmp == nullptr)) {
136- return false;
137- }
138- 
139- tmp->IncreaseRef();
140- return mRunnableQueue.Enqueue(tmp);
141- }
142- 
143- /*
144- * @brief Enqueue a task to thread pool, need to ensure this has been started
145- *
146- * @param task a lambda expression or function no parameter no return value
147- *
148- * @return true if enqueue successfully, otherwise the queue is full
149- */
150- inline bool Execute(const std::function<void()> &task)
151- {
152- return Execute(MakeRef<Runnable>(task));
153- }
154- 
155- /*
156- * @brief Set the thread name prefix
157- *
158- * @param name [in] prefix name of execute service working thread
159- */
160- inline void SetThreadName(const std::string &name)
161- {
162- mThreadName = name;
163- }
164- 
165- /*
166- * @brief Bind the cpu for working threads
167- *
168- * @param idx [in] starting index cpu id to bind to working threads
169- */
170- inline void SetCpuSetStartIndex(int16_t idx)
171- {
172- mCpuSetStartIdx = idx;
173- }
174- 
175- DAGGER_DEFINE_REF_COUNT_FUNCTIONS
176- 
177-private:
178- ExecutorService(uint16_t threadNum, uint32_t queueCapacity)
179- : mRunnableQueue(queueCapacity),
180- mThreadNum(threadNum),
181- mThreads(0),
182- mStarted(false),
183- mStopped(false),
184- mStartedThreadNum(0)
185- {
186- }
187- 
188- void RunInThread(int16_t cpuId);
189- void DoRunnable(bool &flag);
190- 
191-private:
192- RingBufferBlockingQueue<Runnable *> mRunnableQueue;
193- uint16_t mThreadNum = 0;
194- int16_t mCpuSetStartIdx = -1;
195- std::vector<std::thread *> mThreads;
196- 
197- std::atomic<bool> mStarted;
198- std::atomic<bool> mStopped;
199- std::atomic<uint16_t> mStartedThreadNum;
200- 
201- std::string mThreadName;
202- 
203- DAGGER_DEFINE_REF_COUNT_VARIABLE
204-};
205- 
206-inline bool ExecutorService::Start()
207-{
208- if (mStarted) {
209- return true;
210- }
211- 
212- /* init ring buffer blocking queue */
213- auto result = mRunnableQueue.Initialize();
214- if (result != 0) {
215- DBG_LOGERROR("Failed to initialize queue, result " << result);
216- return false;
217- }
218- 
219- for (uint16_t i = 0; i < mThreadNum; i++) {
220- auto cpuId = mCpuSetStartIdx < 0 ? -1 : mCpuSetStartIdx + i;
221- auto *thr = new (std::nothrow) std::thread(&ExecutorService::RunInThread, this, cpuId);
222- if (thr == nullptr) {
223- DBG_LOGERROR("Failed to create executor thread " << i);
224- return false;
225- }
226- 
227- mThreads.push_back(thr);
228- }
229- 
230- while (mStartedThreadNum < mThreadNum) {
231- usleep(1);
232- }
233- 
234- mStarted = true;
235- return true;
236-}
237- 
238-inline void ExecutorService::Stop()
239-{
240- if (!mStarted || mStopped) {
241- return;
242- }
243- 
244- for (uint32_t i = 0; i < mThreads.size(); ++i) {
245- RunnablePtr stopTask = new (std::nothrow) Runnable();
246- if (stopTask == nullptr) {
247- DBG_LOGERROR("Failed to new stop task, probably out of memory");
248- break;
249- }
250- stopTask->Type(RunnableType::STOP);
251- 
252- Runnable *tmp = stopTask.Get();
253- tmp->IncreaseRef();
254- if (!mRunnableQueue.EnqueueFirst(tmp)) {
255- continue;
256- }
257- }
258- 
259- for (auto &thr : mThreads) {
260- if (thr != nullptr) {
261- thr->join();
262- }
263- }
264- 
265- mStopped = true;
266- mRunnableQueue.UnInitialize();
267-}
268- 
269-inline void ExecutorService::DoRunnable(bool &flag)
270-{
271- try {
272- Runnable *task = nullptr;
273- mRunnableQueue.Dequeue(task);
274- if (task != nullptr) {
275- RunnablePtr runnable = task;
276- task->DecreaseRef();
277- if (runnable->Type() == RunnableType::NORMAL) {
278- runnable->Run();
279- } else if (runnable->Type() == RunnableType::STOP) {
280- flag = false;
281- } else {
282- DBG_LOGERROR("Un-reachable path");
283- }
284- } else {
285- DBG_LOGERROR("Task is null");
286- }
287- } catch (std::runtime_error &ex) {
288- DBG_LOGERROR("Caught error " << ex.what() << " when execute a task, continue");
289- } catch (...) {
290- DBG_LOGERROR("Caught unknown error when execute a task, continue");
291- }
292-}
293- 
294-inline void ExecutorService::RunInThread(int16_t cpuId)
295-{
296- bool runFlag = true;
297- uint16_t threadIndex = mStartedThreadNum++;
298- 
299- auto threadName = mThreadName.empty() ? "executor" : mThreadName;
300- threadName += std::to_string(threadIndex);
301- if (cpuId != -1) {
302- cpu_set_t cpuSet;
303- CPU_ZERO(&cpuSet);
304- CPU_SET(cpuId, &cpuSet);
305- if (pthread_setaffinity_np(pthread_self(), sizeof(cpuSet), &cpuSet) != 0) {
306- DBG_LOGWARN("Failed to bind executor thread" << threadName << " << to cpu " << cpuId);
307- }
308- }
309- 
310- pthread_setname_np(pthread_self(), threadName.c_str());
311- DBG_LOGINFO("Thread is started for executor service <" << threadName << "> cpuId " << cpuId);
312- 
313- while (runFlag) {
314- DoRunnable(runFlag);
315- }
316- DBG_LOGINFO("Thread for executor service <" << threadName << "> cpuId " << cpuId << " exiting");
317-}
318-} // namespace dagger
319-} // namespace ock
320-#endif // HDAGGER_DG_EXECUTION_SERVICE_H
@@ -33,7 +33,6 @@
33#include "rack_mem_constants.h"33#include "rack_mem_constants.h"
34#include "referable/dg_ref.h"34#include "referable/dg_ref.h"
35#include "strings/dg_str_util.h"35#include "strings/dg_str_util.h"
36-#include "thread_pool/dg_execution_service.h"
37#include "time/dg_monotonic.h"36#include "time/dg_monotonic.h"
38#include "util/defines.h"37#include "util/defines.h"
39 38 
@@ -40,82 +40,6 @@ using namespace ock::common;
40 40 
41namespace ock::mxmd {41namespace ock::mxmd {
42 42 
43-class ThreadExecutorServiceHolder {
44-public:
45- static ThreadExecutorServiceHolder &GetInstance()
46- {
47- static ThreadExecutorServiceHolder gInstance;
48- return gInstance;
49- }
50- 
51- void StopAllThreadExecutorService()
52- {
53- std::unique_lock<std::recursive_mutex> uniqueLock(mLock);
54- if (mOneThreadExecutorService != nullptr) {
55- mOneThreadExecutorService->Stop();
56- mOneThreadExecutorService = nullptr;
57- }
58- if (mMoreThreadExecutorService != nullptr) {
59- mMoreThreadExecutorService->Stop();
60- mMoreThreadExecutorService = nullptr;
61- }
62- }
63- 
64- [[nodiscard]] ExecutorServicePtr GetOneThreadExecutorService()
65- {
66- std::unique_lock<std::recursive_mutex> uniqueLock(mLock);
67- if (mOneThreadExecutorService == nullptr) {
68- mOneThreadExecutorService = ExecutorService::Create(1);
69- }
70- return mOneThreadExecutorService;
71- }
72- 
73- [[nodiscard]] ExecutorServicePtr GetMoreThreadExecutorService()
74- {
75- std::unique_lock<std::recursive_mutex> uniqueLock(mLock);
76- if (mMoreThreadExecutorService == nullptr) {
77- mMoreThreadExecutorService = ExecutorService::Create(8u);
78- }
79- return mMoreThreadExecutorService;
80- }
81- 
82-private:
83- ThreadExecutorServiceHolder() = default;
84- std::recursive_mutex mLock{};
85- ExecutorServicePtr mOneThreadExecutorService{nullptr};
86- ExecutorServicePtr mMoreThreadExecutorService{nullptr};
87-};
88- 
89-inline ExecutorServicePtr GetOneThreadExecutorService()
90-{
91- auto ptr = ThreadExecutorServiceHolder::GetInstance().GetOneThreadExecutorService();
92- if (ptr == nullptr) {
93- DBG_LOGERROR("Failed to create executor service");
94- return nullptr;
95- }
96- ptr->SetThreadName("OneThreadExecutorService");
97- if (!ptr->Start()) {
98- DBG_LOGERROR("Failed to start executor service");
99- return nullptr;
100- }
101- return ptr;
102-}
103- 
104-inline ExecutorServicePtr GetMoreThreadExecutorService()
105-{
106- auto ptr = ThreadExecutorServiceHolder::GetInstance().GetMoreThreadExecutorService();
107- if (ptr == nullptr) {
108- DBG_LOGERROR("Failed to create executor service");
109- return nullptr;
110- }
111- ptr->SetThreadName("MoreThreadExecutorService");
112- if (!ptr->Start()) {
113- DBG_LOGERROR("Failed to start executor service");
114- return nullptr;
115- }
116- return ptr;
117-}
118- 
119class MemStrUtil {43class MemStrUtil {
120public:44public:
121 static std::vector<std::string> SplitTrim(const std::string &src, const std::string &sep);45 static std::vector<std::string> SplitTrim(const std::string &src, const std::string &sep);
@@ -345,6 +345,10 @@ private:
345 static void HandleRequest(MxmComMessageCtx &message)345 static void HandleRequest(MxmComMessageCtx &message)
346 {346 {
347 auto ucMsg = static_cast<MxmComMessage *>(static_cast<void *>(message.GetMessage()));347 auto ucMsg = static_cast<MxmComMessage *>(static_cast<void *>(message.GetMessage()));
348+ if (ucMsg == nullptr) {
349+ DBG_LOGERROR("Received request with null message.");
350+ return;
351+ }
348 uint16_t moduleCode = ucMsg->GetMessageHead().GetModuleCode();352 uint16_t moduleCode = ucMsg->GetMessageHead().GetModuleCode();
349 uint16_t opCode = ucMsg->GetMessageHead().GetOpCode();353 uint16_t opCode = ucMsg->GetMessageHead().GetOpCode();
350 uint32_t crc = ucMsg->GetMessageHead().GetCrc();354 uint32_t crc = ucMsg->GetMessageHead().GetCrc();
@@ -15,6 +15,8 @@
15#include "crc/dg_crc.h"15#include "crc/dg_crc.h"
16#include "strings/dg_str_util.h"16#include "strings/dg_str_util.h"
17 17 
18+#include <limits>
19+ 
18#include <log.h>20#include <log.h>
19 21 
20namespace ock::com {22namespace ock::com {
@@ -303,7 +305,8 @@ std::string MxmComChannelInfo::ConvertMxmComChannelInfoToString()
303{305{
304 std::string infoStr = "engine Name: " + engineName + "; ";306 std::string infoStr = "engine Name: " + engineName + "; ";
305 infoStr = infoStr + "channel type: " + std::to_string(static_cast<int>(channelType)) + "; ";307 infoStr = infoStr + "channel type: " + std::to_string(static_cast<int>(channelType)) + "; ";
306- infoStr = infoStr + "channel id: " + std::to_string(channel->GetId()) + "; ";308+ infoStr = infoStr +
309+ "channel id: " + (channel == nullptr ? std::string("invalid") : std::to_string(channel->GetId())) + "; ";
307 infoStr = infoStr + "cur node id: " + connectInfo.GetCurNodeId() + "; ";310 infoStr = infoStr + "cur node id: " + connectInfo.GetCurNodeId() + "; ";
308 infoStr = infoStr + "remote node id: " + connectInfo.GetRemoteNodeId() + "; ";311 infoStr = infoStr + "remote node id: " + connectInfo.GetRemoteNodeId() + "; ";
309 return infoStr;312 return infoStr;
@@ -517,6 +520,10 @@ const MxmComMessageHead &MxmComMessage::GetMessageHead() const
517 520 
518MxmComMessagePtr MxmComMessage::AllocMessage(uint32_t len)521MxmComMessagePtr MxmComMessage::AllocMessage(uint32_t len)
519{522{
523+ if (len > std::numeric_limits<uint32_t>::max() - sizeof(MxmComMessageHead)) {
524+ DBG_LOGERROR("Message length is too large: " << len);
525+ return nullptr;
526+ }
520 uint32_t sumLen = sizeof(MxmComMessageHead) + len;527 uint32_t sumLen = sizeof(MxmComMessageHead) + len;
521 auto msg = new (std::nothrow) uint8_t[sumLen];528 auto msg = new (std::nothrow) uint8_t[sumLen];
522 return msg;529 return msg;
@@ -135,7 +135,12 @@ void MxmComLinkManager::InsertChannel(MxmComChannelInfo &channelInfo)
135{135{
136 auto chType = channelInfo.GetChannelType();136 auto chType = channelInfo.GetChannelType();
137 if (chType == MxmChannelType::SINGLE_SIDE && channelInfo.IsServerSide()) {137 if (chType == MxmChannelType::SINGLE_SIDE && channelInfo.IsServerSide()) {
138- auto channelId = channelInfo.GetChannel()->GetId();138+ const auto &channel = channelInfo.GetChannel();
139+ if (channel == nullptr) {
140+ DBG_LOGERROR("Cannot insert a null channel.");
141+ return;
142+ }
143+ auto channelId = channel->GetId();
139 channelIdMap.emplace(channelId, channelInfo);144 channelIdMap.emplace(channelId, channelInfo);
140 DBG_LOGINFO("Insert channel id: " << channelId << ", cur node id" << channelInfo.GetConnectInfo().GetCurNodeId()145 DBG_LOGINFO("Insert channel id: " << channelId << ", cur node id" << channelInfo.GetConnectInfo().GetCurNodeId()
141 << ", remote node id" << channelInfo.GetConnectInfo().GetRemoteNodeId());146 << ", remote node id" << channelInfo.GetConnectInfo().GetRemoteNodeId());
@@ -491,7 +496,12 @@ HRESULT MxmComEngine::Start()
491 if (engineInfo.GetEngineType() != MxmEngineType::CLIENT && engineInfo.IsUds()) {496 if (engineInfo.GetEngineType() != MxmEngineType::CLIENT && engineInfo.IsUds()) {
492 // 设置uds文件权限497 // 设置uds文件权限
493 const std::string udsPath = GetUdsPath(engineInfo.GetUdsInfo().first);498 const std::string udsPath = GetUdsPath(engineInfo.GetUdsInfo().first);
494- if (chmod(udsPath.c_str(), engineInfo.GetUdsInfo().second) != 0) {499+ const mode_t udsMode = engineInfo.GetUdsInfo().second;
500+ if ((udsMode & ~0777U) != 0 || (udsMode & 0002U) != 0) {
501+ DBG_LOGERROR("Refuse unsafe uds file permission: " << udsMode);
502+ return HFAIL;
503+ }
504+ if (chmod(udsPath.c_str(), udsMode) != 0) {
495 DBG_LOGERROR("Failed to change uds file permission, " << strerror(errno));505 DBG_LOGERROR("Failed to change uds file permission, " << strerror(errno));
496 return HFAIL;506 return HFAIL;
497 }507 }
@@ -663,7 +673,6 @@ bool MxmComEngine::TlsPrivateKeyCallback(const std::string &name, std::string &p
663 UBSHcomTLSEraseKeypass &erase)673 UBSHcomTLSEraseKeypass &erase)
664{674{
665 path = UbsCommonConfig::GetInstance().GetKeyPath();675 path = UbsCommonConfig::GetInstance().GetKeyPath();
666- DBG_LOGINFO("key.path=" << path);
667 std::pair<char *, int> pwPair;676 std::pair<char *, int> pwPair;
668 auto ret = UbsCryptorHandler::GetInstance().Decrypt(0, UbsCommonConfig::GetInstance().GetKeypassPath(), pwPair);677 auto ret = UbsCryptorHandler::GetInstance().Decrypt(0, UbsCommonConfig::GetInstance().GetKeypassPath(), pwPair);
669 if (ret != 0) {678 if (ret != 0) {
@@ -1024,6 +1033,10 @@ HRESULT CreateChannel(bool isUds, const std::string &engineName, const std::pair
1024 1033 
1025HRESULT CreateCallBack(const MxmComCallback &usrCb, Callback *&done)1034HRESULT CreateCallBack(const MxmComCallback &usrCb, Callback *&done)
1026{1035{
1036+ if (usrCb.cb == nullptr) {
1037+ DBG_LOGERROR("User callback is nullptr.");
1038+ return MXM_COM_ERROR_NEW_NET_CALLBACK_FAIL;
1039+ }
1027 done = UBSHcomNewCallback(1040 done = UBSHcomNewCallback(
1028 [usrCb](UBSHcomServiceContext &context) {1041 [usrCb](UBSHcomServiceContext &context) {
1029 if (context.Result() != 0) {1042 if (context.Result() != 0) {
@@ -1174,7 +1187,7 @@ void MxmCommunication::MxmComMsgReply(MxmComMessageCtx &message, const MxmComDat
1174 UBSHcomRequest reqMsg{(data.data), data.len, 0};1187 UBSHcomRequest reqMsg{(data.data), data.len, 0};
1175 UBSHcomReplyContext replyCtx(rspCtx, 0);1188 UBSHcomReplyContext replyCtx(rspCtx, 0);
1176 1189 
1177- Callback *done;1190+ Callback *done = nullptr;
1178 if (CreateCallBack(usrCb, done) != HOK) {1191 if (CreateCallBack(usrCb, done) != HOK) {
1179 return;1192 return;
1180 }1193 }
@@ -12,12 +12,20 @@
12 12 
13#include "mxm_ipc_client.h"13#include "mxm_ipc_client.h"
14 14 
15+#include <exception>
16+ 
15namespace ock::com::ipc {17namespace ock::com::ipc {
16 18 
17static void IPCClientHandlerWork(void (*handler)(MxmComMessageCtx &messageCtx), MxmComMessageCtx &messageCtx)19static void IPCClientHandlerWork(void (*handler)(MxmComMessageCtx &messageCtx), MxmComMessageCtx &messageCtx)
18{20{
19- if (handler != nullptr) {21+ try {
20- handler(messageCtx);22+ if (handler != nullptr) {
23+ handler(messageCtx);
24+ }
25+ } catch (const std::exception &e) {
26+ DBG_LOGERROR("IPC handler threw an exception: " << e.what());
27+ } catch (...) {
28+ DBG_LOGERROR("IPC handler threw an unknown exception.");
21 }29 }
22 messageCtx.FreeMessage();30 messageCtx.FreeMessage();
23}31}
@@ -18,13 +18,17 @@
18#include "ubsm_com_constants.h"18#include "ubsm_com_constants.h"
19#include "util/defines.h"19#include "util/defines.h"
20 20 
21+#include <mutex>
22+ 
21namespace ock::com::ipc {23namespace ock::com::ipc {
22 24 
23MxmIpcServer *g_mxmIpcServer{nullptr};25MxmIpcServer *g_mxmIpcServer{nullptr};
24std::atomic<int> g_ipcServerCount{0};26std::atomic<int> g_ipcServerCount{0};
27+std::mutex g_mxmIpcServerMutex;
25 28 
26HRESULT RegIpcService(MxmComBaseMessageHandlerPtr &handlerPtr)29HRESULT RegIpcService(MxmComBaseMessageHandlerPtr &handlerPtr)
27{30{
31+ std::lock_guard<std::mutex> guard(g_mxmIpcServerMutex);
28 if (g_mxmIpcServer != nullptr) {32 if (g_mxmIpcServer != nullptr) {
29 return g_mxmIpcServer->RegMessageHandler(handlerPtr);33 return g_mxmIpcServer->RegMessageHandler(handlerPtr);
30 }34 }
@@ -37,7 +41,9 @@ HRESULT RegIpcService(MxmComBaseMessageHandlerPtr &handlerPtr)
37 */41 */
38int MxmComStartIpcServer()42int MxmComStartIpcServer()
39{43{
40- if (g_ipcServerCount.load() > 0 && g_mxmIpcServer != nullptr) {44+ std::lock_guard<std::mutex> guard(g_mxmIpcServerMutex);
45+ if (g_mxmIpcServer != nullptr) {
46+ g_ipcServerCount.fetch_add(1);
41 return HOK;47 return HOK;
42 }48 }
43 std::string udsPathPrefix = MXM_IPC_UDS_PATH_PREFIX_DEFAULT;49 std::string udsPathPrefix = MXM_IPC_UDS_PATH_PREFIX_DEFAULT;
@@ -72,16 +78,21 @@ int MxmComStartIpcServer()
72 */78 */
73void MxmComStopIpcServer()79void MxmComStopIpcServer()
74{80{
75- if (g_mxmIpcServer != nullptr) {81+ std::lock_guard<std::mutex> guard(g_mxmIpcServerMutex);
82+ if (g_mxmIpcServer != nullptr && g_ipcServerCount.fetch_sub(1) == 1) {
76 g_mxmIpcServer->Stop();83 g_mxmIpcServer->Stop();
77 delete g_mxmIpcServer;84 delete g_mxmIpcServer;
78 g_mxmIpcServer = nullptr;85 g_mxmIpcServer = nullptr;
79- g_ipcServerCount.fetch_sub(1);
80 }86 }
81}87}
82 88 
83void MXMSetLinkEventHandler(const MXMLinkEventHandler &handler)89void MXMSetLinkEventHandler(const MXMLinkEventHandler &handler)
84{90{
91+ std::lock_guard<std::mutex> guard(g_mxmIpcServerMutex);
92+ if (g_mxmIpcServer == nullptr) {
93+ DBG_LOGERROR("IPC server is not started.");
94+ return;
95+ }
85 g_mxmIpcServer->AddLinkNotifyFunc([handler](const std::vector<MxmLinkInfo> &linkInfoList) -> void {96 g_mxmIpcServer->AddLinkNotifyFunc([handler](const std::vector<MxmLinkInfo> &linkInfoList) -> void {
86 for (MxmLinkInfo info : linkInfoList) {97 for (MxmLinkInfo info : linkInfoList) {
87 if (info.GetState() == MxmLinkState::LINK_DOWN) {98 if (info.GetState() == MxmLinkState::LINK_DOWN) {
@@ -112,4 +123,4 @@ uint32_t MxmRegIpcService(const MxmComEndpoint &endpoint, const MxmComIpcService
112 DBG_LOGINFO("Register moduleId: " << moduleCode << ",serviceId is " << opCode << " ret is " << ret);123 DBG_LOGINFO("Register moduleId: " << moduleCode << ",serviceId is " << opCode << " ret is " << ret);
113 return ret;124 return ret;
114}125}
115-} // namespace ock::com::ipc126+} // namespace ock::com::ipc
@@ -13,12 +13,20 @@
13#include "ubs_certify_handler.h"13#include "ubs_certify_handler.h"
14#include "ubs_common_config.h"14#include "ubs_common_config.h"
15 15 
16+#include <exception>
17+ 
16namespace ock::com::rpc {18namespace ock::com::rpc {
17 19 
18static void RPCServerHandlerWork(void (*handler)(MxmComMessageCtx &messageCtx), MxmComMessageCtx &messageCtx)20static void RPCServerHandlerWork(void (*handler)(MxmComMessageCtx &messageCtx), MxmComMessageCtx &messageCtx)
19{21{
20- if (handler != nullptr) {22+ try {
21- handler(messageCtx);23+ if (handler != nullptr) {
24+ handler(messageCtx);
25+ }
26+ } catch (const std::exception &e) {
27+ DBG_LOGERROR("RPC handler threw an exception: " << e.what());
28+ } catch (...) {
29+ DBG_LOGERROR("RPC handler threw an unknown exception.");
22 }30 }
23 messageCtx.FreeMessage();31 messageCtx.FreeMessage();
24}32}
@@ -257,15 +257,21 @@ void DLockExecutor::DestroyDLockDlopenLib()
257 257 
258int DLockExecutor::ClientInitWrapper(int *clientId, const char *serverIp)258int DLockExecutor::ClientInitWrapper(int *clientId, const char *serverIp)
259{259{
260+ if (GetInstance().DLockClientInitFunc == nullptr) {
261+ return dlock::DLOCK_FAIL;
262+ }
260 return GetInstance().DLockClientInitFunc(clientId, serverIp);263 return GetInstance().DLockClientInitFunc(clientId, serverIp);
261}264}
262 265 
263int DLockExecutor::ClientReinitWrapper(int clientId, const char *serverIp)266int DLockExecutor::ClientReinitWrapper(int clientId, const char *serverIp)
264{267{
268+ if (GetInstance().DLockClientReinitFunc == nullptr) {
269+ return dlock::DLOCK_FAIL;
270+ }
265 return GetInstance().DLockClientReinitFunc(clientId, serverIp);271 return GetInstance().DLockClientReinitFunc(clientId, serverIp);
266}272}
267 273 
268int DLockExecutor::ServerStartWrapper(const struct dlock::server_cfg &cfg, int &serverId)274int DLockExecutor::ServerStartWrapper(const struct dlock::server_cfg &cfg, int &serverId)
269{275{
270 return GetInstance().DLockServerStartFunc(cfg, serverId);276 return GetInstance().DLockServerStartFunc(cfg, serverId);
271-}277+}
@@ -12,6 +12,7 @@
12#include "ubsm_lock.h"12#include "ubsm_lock.h"
13#include <arpa/inet.h>13#include <arpa/inet.h>
14#include <securec.h>14#include <securec.h>
15+#include <limits>
15#include <string>16#include <string>
16#include "dlock_context.h"17#include "dlock_context.h"
17#include "dlock_types.h"18#include "dlock_types.h"
@@ -48,6 +49,8 @@ int32_t UbsmLock::Init()
48 ret = InitTlsConfig(sslConfig);49 ret = InitTlsConfig(sslConfig);
49 if (ret != MXM_OK) {50 if (ret != MXM_OK) {
50 DBG_LOGERROR("Failed to init tls config of ubsm lock, ret: " << ret);51 DBG_LOGERROR("Failed to init tls config of ubsm lock, ret: " << ret);
52+ DeinitTlsConfig();
53+ DLockExecutor::GetInstance().DestroyDLockDlopenLib();
51 return ret;54 return ret;
52 }55 }
53 56 
@@ -155,6 +158,9 @@ int32_t UbsmLock::DlockServerInit(struct dlock::ssl_cfg ssl)
155 if (ret == dlock::DLOCK_SERVER_NO_RESOURCE) {158 if (ret == dlock::DLOCK_SERVER_NO_RESOURCE) {
156 DBG_LOGERROR("ServerStartWrapper dlock server no resource");159 DBG_LOGERROR("ServerStartWrapper dlock server no resource");
157 }160 }
161+ if (DLockExecutor::GetInstance().DLockSeverLibDeInitFunc != nullptr) {
162+ DLockExecutor::GetInstance().DLockSeverLibDeInitFunc();
163+ }
158 return MXM_ERR_DLOCK_INNER;164 return MXM_ERR_DLOCK_INNER;
159 }165 }
160 DBG_LOGINFO("Server started successfully on " << cfg.serverIp << ":" << cfg.serverPort);166 DBG_LOGINFO("Server started successfully on " << cfg.serverIp << ":" << cfg.serverPort);
@@ -635,6 +641,10 @@ int32_t UbsmLock::HandleUnlock(const std::string &name, const LockUdsInfo &udsIn
635 641 
636int32_t UbsmLock::UnlockWithDesc(const std::string &name, ClientDesc *clientDesc, const LockUdsInfo &udsInfo)642int32_t UbsmLock::UnlockWithDesc(const std::string &name, ClientDesc *clientDesc, const LockUdsInfo &udsInfo)
637{643{
644+ if (clientDesc == nullptr) {
645+ DBG_LOGERROR("Client descriptor is nullptr.");
646+ return MXM_ERR_NULLPTR;
647+ }
638 auto clientId = clientDesc->GetClientId();648 auto clientId = clientDesc->GetClientId();
639 auto lockIdPair = clientDesc->GetLockId(name);649 auto lockIdPair = clientDesc->GetLockId(name);
640 if (!lockIdPair.first) {650 if (!lockIdPair.first) {
@@ -721,6 +731,7 @@ int32_t UbsmLock::Reinit()
721 if (ret != MXM_OK) {731 if (ret != MXM_OK) {
722 DBG_LOGINFO("Failed to init tls config of ubsmlock, ret: " << ret);732 DBG_LOGINFO("Failed to init tls config of ubsmlock, ret: " << ret);
723 DeinitTlsConfig();733 DeinitTlsConfig();
734+ DLockExecutor::GetInstance().DestroyDLockDlopenLib();
724 return ret;735 return ret;
725 }736 }
726 737 
@@ -770,8 +781,12 @@ int32_t UbsmLock::DlockServerReinit(const std::string &serverIp, struct dlock::s
770 DBG_LOGINFO("Starting server reinit. Server IP: " << serverIp781 DBG_LOGINFO("Starting server reinit. Server IP: " << serverIp
771 << ", Recovery clients: " << ctx.GetConfig().recoveryClientNum);782 << ", Recovery clients: " << ctx.GetConfig().recoveryClientNum);
772 dlock::server_cfg conf = {};783 dlock::server_cfg conf = {};
773- dlock::primary_cfg primCfg = GetPrimCfg(serverIp, ctx);784+ dlock::primary_cfg primCfg = {};
774- auto retCode = GetServerCfg(ssl, primCfg, conf);785+ auto retCode = GetPrimCfg(serverIp, ctx, primCfg);
786+ if (retCode != MXM_OK) {
787+ return retCode;
788+ }
789+ retCode = GetServerCfg(ssl, primCfg, conf);
775 if (retCode != MXM_OK) {790 if (retCode != MXM_OK) {
776 DBG_LOGERROR("Get server config failed, ret: " << retCode);791 DBG_LOGERROR("Get server config failed, ret: " << retCode);
777 return retCode;792 return retCode;
@@ -779,6 +794,7 @@ int32_t UbsmLock::DlockServerReinit(const std::string &serverIp, struct dlock::s
779 794 
780 DBG_LOGINFO("Server bind core " << primCfg.cmd_cpuset << ", sleep" << conf.sleep_mode_enable);795 DBG_LOGINFO("Server bind core " << primCfg.cmd_cpuset << ", sleep" << conf.sleep_mode_enable);
781 796 
797+ bool initializedServerLib = false;
782 if (ctx.IsNeedServerDeinit()) {798 if (ctx.IsNeedServerDeinit()) {
783 DBG_LOGINFO("Attempting to stop server with serverId=" << ctx.GetConfig().serverId);799 DBG_LOGINFO("Attempting to stop server with serverId=" << ctx.GetConfig().serverId);
784 auto ret = DLockExecutor::GetInstance().DLockServerStopFunc(ctx.GetConfig().serverId);800 auto ret = DLockExecutor::GetInstance().DLockServerStopFunc(ctx.GetConfig().serverId);
@@ -795,6 +811,7 @@ int32_t UbsmLock::DlockServerReinit(const std::string &serverIp, struct dlock::s
795 return MXM_ERR_DLOCK_INNER;811 return MXM_ERR_DLOCK_INNER;
796 }812 }
797 DBG_LOGINFO("Server library initialized successfully");813 DBG_LOGINFO("Server library initialized successfully");
814+ initializedServerLib = true;
798 ctx.SetServerDeinitFlag(true);815 ctx.SetServerDeinitFlag(true);
799 }816 }
800 auto ret = DLockExecutor::ServerStartWrapper(conf, ctx.GetConfig().serverId);817 auto ret = DLockExecutor::ServerStartWrapper(conf, ctx.GetConfig().serverId);
@@ -803,6 +820,12 @@ int32_t UbsmLock::DlockServerReinit(const std::string &serverIp, struct dlock::s
803 DBG_LOGERROR("Failed to start server, dlock server has no resource");820 DBG_LOGERROR("Failed to start server, dlock server has no resource");
804 }821 }
805 DBG_LOGERROR("Failed to start server, retCode: " << ret);822 DBG_LOGERROR("Failed to start server, retCode: " << ret);
823+ if (initializedServerLib) {
824+ if (DLockExecutor::GetInstance().DLockSeverLibDeInitFunc != nullptr) {
825+ DLockExecutor::GetInstance().DLockSeverLibDeInitFunc();
826+ }
827+ ctx.SetServerDeinitFlag(false);
828+ }
806 return MXM_ERR_DLOCK_INNER;829 return MXM_ERR_DLOCK_INNER;
807 }830 }
808 DBG_LOGINFO("Server started successfully, serverId=" << ctx.GetConfig().serverId);831 DBG_LOGINFO("Server started successfully, serverId=" << ctx.GetConfig().serverId);
@@ -828,17 +851,22 @@ int32_t UbsmLock::GetServerCfg(const dlock::ssl_cfg &ssl, const dlock::primary_c
828 return MXM_OK;851 return MXM_OK;
829}852}
830 853 
831-dlock::primary_cfg UbsmLock::GetPrimCfg(const std::string &serverIp, DLockContext &ctx)854+int32_t UbsmLock::GetPrimCfg(const std::string &serverIp, DLockContext &ctx, dlock::primary_cfg &primCfg)
832{855{
833- struct dlock::primary_cfg primCfg = {0};856+ const auto recoveryClientNum = ctx.GetConfig().recoveryClientNum;
857+ const auto dlockClientNum = ctx.GetConfig().dlockClientNum;
858+ if (dlockClientNum != 0 && recoveryClientNum > std::numeric_limits<unsigned int>::max() / dlockClientNum) {
859+ DBG_LOGERROR("Recovery client count overflow.");
860+ return MXM_ERR_PARAM_INVALID;
861+ }
834 primCfg.num_of_replica = 0;862 primCfg.num_of_replica = 0;
835- primCfg.recovery_client_num = ctx.GetConfig().recoveryClientNum * ctx.GetConfig().dlockClientNum;863+ primCfg.recovery_client_num = recoveryClientNum * dlockClientNum;
836 primCfg.cmd_cpuset = const_cast<char *>(ctx.GetConfig().cmdCpuSet.c_str());864 primCfg.cmd_cpuset = const_cast<char *>(ctx.GetConfig().cmdCpuSet.c_str());
837 primCfg.ctrl_cpuset = nullptr;865 primCfg.ctrl_cpuset = nullptr;
838 primCfg.server_ip_str = const_cast<char *>(serverIp.c_str());866 primCfg.server_ip_str = const_cast<char *>(serverIp.c_str());
839 primCfg.server_port = ctx.GetConfig().serverPort;867 primCfg.server_port = ctx.GetConfig().serverPort;
840 primCfg.replica_enable = false;868 primCfg.replica_enable = false;
841- return primCfg;869+ return MXM_OK;
842}870}
843 871 
844void UbsmLock::DoClientReInitStagesClientReInit(int32_t &ret, bool &skipUpdate, int32_t clientId, REINIT_STAGES &stages)872void UbsmLock::DoClientReInitStagesClientReInit(int32_t &ret, bool &skipUpdate, int32_t clientId, REINIT_STAGES &stages)
@@ -987,8 +1015,8 @@ void GetPrivateKeyPwd(char **keyPwd, int *keyPwdLen)
987 DBG_LOGERROR("Invalid input parameters (keyPwd or keyPwdLen is nullptr).");1015 DBG_LOGERROR("Invalid input parameters (keyPwd or keyPwdLen is nullptr).");
988 return;1016 return;
989 }1017 }
990- auto path = UbsCommonConfig::GetInstance().GetLockKeyPath();1018+ *keyPwd = nullptr;
991- DBG_LOGINFO("key.path=" << path);1019+ *keyPwdLen = 0;
992 std::pair<char *, int> pwPair;1020 std::pair<char *, int> pwPair;
993 auto ret = UbsCryptorHandler::GetInstance().Decrypt(0, UbsCommonConfig::GetInstance().GetLockKeypassPath(), pwPair);1021 auto ret = UbsCryptorHandler::GetInstance().Decrypt(0, UbsCommonConfig::GetInstance().GetLockKeypassPath(), pwPair);
994 if (ret != 0) {1022 if (ret != 0) {
@@ -1094,10 +1122,6 @@ int32_t UbsmLock::InitTlsConfig(struct dlock::ssl_cfg &conf)
1094 tlsConfig.erase_prkey_cb = &ErasePrivateKey;1122 tlsConfig.erase_prkey_cb = &ErasePrivateKey;
1095 tlsConfig.ssl_enable = true;1123 tlsConfig.ssl_enable = true;
1096 conf = tlsConfig;1124 conf = tlsConfig;
1097- DBG_LOGINFO("Tls config ca_path: " << conf.ca_path);
1098- DBG_LOGDEBUG("Tls config crl_path: " << conf.crl_path);
1099- DBG_LOGDEBUG("Tls config cert_path: " << conf.cert_path);
1100- DBG_LOGDEBUG("Tls config prkey_path: " << conf.prkey_path);
1101 return MXM_OK;1125 return MXM_OK;
1102}1126}
1103 1127 
@@ -102,7 +102,7 @@ private:
102 int32_t ClientReInitStagesClientReInit(int32_t clientId, const char *serverIp, uint32_t &retryCount);102 int32_t ClientReInitStagesClientReInit(int32_t clientId, const char *serverIp, uint32_t &retryCount);
103 int32_t ClientReInitStagesUpdateLocks(int32_t clientId, int32_t &updateRetryTimes, REINIT_STAGES &stages);103 int32_t ClientReInitStagesUpdateLocks(int32_t clientId, int32_t &updateRetryTimes, REINIT_STAGES &stages);
104 int32_t ClientReInitStagesClientReInitDone(int32_t clientId, REINIT_STAGES &stages);104 int32_t ClientReInitStagesClientReInitDone(int32_t clientId, REINIT_STAGES &stages);
105- dlock::primary_cfg GetPrimCfg(const std::string &serverIp, DLockContext &ctx);105+ int32_t GetPrimCfg(const std::string &serverIp, DLockContext &ctx, dlock::primary_cfg &primCfg);
106 int32_t GetServerCfg(const dlock::ssl_cfg &ssl, const dlock::primary_cfg &primCfg, dlock::server_cfg &conf);106 int32_t GetServerCfg(const dlock::ssl_cfg &ssl, const dlock::primary_cfg &primCfg, dlock::server_cfg &conf);
107 int32_t InitTlsConfig(struct dlock::ssl_cfg &conf);107 int32_t InitTlsConfig(struct dlock::ssl_cfg &conf);
108 int32_t InitializeTlsPaths();108 int32_t InitializeTlsPaths();
@@ -113,4 +113,4 @@ private:
113 113 
114} // namespace dlock_utils114} // namespace dlock_utils
115} // namespace ock115} // namespace ock
116-#endif // UBSM_DLOCK_LOCK_H116+#endif // UBSM_DLOCK_LOCK_H
@@ -139,7 +139,8 @@ inline bool FileUtil::MakeDirRecursive(const std::string &path, uint32_t mode)
139 return true;139 return true;
140 }140 }
141 141 
142- auto chPath = const_cast<char *>(path.c_str());142+ std::string mutablePath(path);
143+ auto chPath = mutablePath.data();
143 auto p = strchr(chPath + 1, '/');144 auto p = strchr(chPath + 1, '/');
144 for (; p != nullptr; (p = strchr(p + 1, '/'))) {145 for (; p != nullptr; (p = strchr(p + 1, '/'))) {
145 *p = '\0';146 *p = '\0';
@@ -185,6 +185,7 @@ bool UbsmemLoggerFilesink::OpenFile(const std::string &fileName)
185 fs::permissions(filePath, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read);185 fs::permissions(filePath, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read);
186 } catch (const std::exception &e) {186 } catch (const std::exception &e) {
187 std::cerr << "Error: " << e.what() << std::endl;187 std::cerr << "Error: " << e.what() << std::endl;
188+ fileMap_[fileName].logFile.close();
188 return false;189 return false;
189 }190 }
190 return true;191 return true;
@@ -299,4 +300,4 @@ void UbsmemLoggerFilesink::ManageFileRotation(const std::string &fileName)
299 // 将新文件的索引设置为最大300 // 将新文件的索引设置为最大
300 fileMap_[fileName].fileIndex = fileMap_[fileName].maxFileCount;301 fileMap_[fileName].fileIndex = fileMap_[fileName].maxFileCount;
301}302}
302-} // namespace ubsmem::log303+} // namespace ubsmem::log
@@ -125,7 +125,7 @@ void UbsmemLoggerManager::Push(UbsmemLoggerEntry &&loggerEntry)
125 oss << "[UBS_SDK " << loggerEntry.GetFile() << ":" << loggerEntry.GetLine() << "] ";125 oss << "[UBS_SDK " << loggerEntry.GetFile() << ":" << loggerEntry.GetLine() << "] ";
126 loggerEntry.DecodePayload(oss);126 loggerEntry.DecodePayload(oss);
127 externLogCallback_(static_cast<int>(loggerEntry.GetLogLevel()), oss.str().c_str());127 externLogCallback_(static_cast<int>(loggerEntry.GetLogLevel()), oss.str().c_str());
128- } else {128+ } else if (writer_ != nullptr) {
129 writer_->Write(loggerEntry);129 writer_->Write(loggerEntry);
130 }130 }
131 if (syslogOpen_) {131 if (syslogOpen_) {
@@ -247,4 +247,4 @@ UbsmemLogLevel UbsmemLoggerManager::StringToLogLevel(const std::string &level)
247 }247 }
248 return UbsmemLogLevel::INFO;248 return UbsmemLogLevel::INFO;
249}249}
250-} // namespace ubsmem::log250+} // namespace ubsmem::log
@@ -85,17 +85,14 @@ static void RollBackBorrowNewMemory(const std::string &name, bool isNuma)
85 auto ret = MLSManager::GetInstance().UpdateMemRecordState(name, RecordState::PRE_DEL);85 auto ret = MLSManager::GetInstance().UpdateMemRecordState(name, RecordState::PRE_DEL);
86 if (ret != 0) {86 if (ret != 0) {
87 DBG_LOGERROR("UpdateMemRecordState failed. name=" << name);87 DBG_LOGERROR("UpdateMemRecordState failed. name=" << name);
88- return;
89 }88 }
90 ret = mxm::UbseMemAdapter::LeaseFree(name, isNuma);89 ret = mxm::UbseMemAdapter::LeaseFree(name, isNuma);
91 if (ret != 0 && ret != MXM_ERR_LEASE_NOT_EXIST) {90 if (ret != 0 && ret != MXM_ERR_LEASE_NOT_EXIST) {
92 DBG_LOGERROR("LeaseFree failed. name=" << name);91 DBG_LOGERROR("LeaseFree failed. name=" << name);
93- return;
94 }92 }
95 ret = MLSManager::GetInstance().DeleteUsedMem(name);93 ret = MLSManager::GetInstance().DeleteUsedMem(name);
96 if (ret != 0) {94 if (ret != 0) {
97 DBG_LOGERROR("LeaseFree failed. name=" << name);95 DBG_LOGERROR("LeaseFree failed. name=" << name);
98- return;
99 }96 }
100}97}
101 98 
@@ -544,4 +541,4 @@ int MxmServerMsgHandle::AppCheckMemoryLease(const MsgBase *req, MsgBase *rsp, co
544 response->errCode_ = MXM_OK;541 response->errCode_ = MXM_OK;
545 return MXM_OK;542 return MXM_OK;
546}543}
547-} // namespace ock::lease::service544+} // namespace ock::lease::service
@@ -149,9 +149,9 @@ private:
149 if (end == modules.cbegin()) {149 if (end == modules.cbegin()) {
150 return;150 return;
151 }151 }
152- auto next = end;
153 auto pos = end;152 auto pos = end;
154- for (--pos; next != modules.cbegin(); --next, --pos) {153+ while (pos != modules.cbegin()) {
154+ --pos;
155 if (pos->exit != nullptr) {155 if (pos->exit != nullptr) {
156 pos->exit();156 pos->exit();
157 }157 }
@@ -163,9 +163,9 @@ private:
163 if (end == modules.cbegin()) {163 if (end == modules.cbegin()) {
164 return;164 return;
165 }165 }
166- auto next = end;
167 auto pos = end;166 auto pos = end;
168- for (--pos; next != modules.cbegin(); --next, --pos) {167+ while (pos != modules.cbegin()) {
168+ --pos;
169 if (pos->shutdown != nullptr) {169 if (pos->shutdown != nullptr) {
170 pos->shutdown();170 pos->shutdown();
171 }171 }
@@ -24,6 +24,7 @@ void *Create()
24 auto *leaseService = new (std::nothrow) ock::lease::service::MemLeaseService();24 auto *leaseService = new (std::nothrow) ock::lease::service::MemLeaseService();
25 if (leaseService == nullptr) {25 if (leaseService == nullptr) {
26 ShmDestroy(g_shmService);26 ShmDestroy(g_shmService);
27+ g_shmService = nullptr;
27 return nullptr;28 return nullptr;
28 }29 }
29 return leaseService;30 return leaseService;
@@ -108,4 +109,4 @@ void Destroy(void *service)
108 }109 }
109 auto real = static_cast<ock::common::Service *>(service);110 auto real = static_cast<ock::common::Service *>(service);
110 delete real;111 delete real;
111-}112+}
@@ -146,9 +146,9 @@ protected:
146private:146private:
147 void RollbackInit(const std::vector<ModuleDesc>::const_iterator &end) noexcept147 void RollbackInit(const std::vector<ModuleDesc>::const_iterator &end) noexcept
148 {148 {
149- auto next = end;
150 auto pos = end;149 auto pos = end;
151- for (--pos; next != modules.cbegin(); --next, --pos) {150+ while (pos != modules.cbegin()) {
151+ --pos;
152 if (pos->exit != nullptr) {152 if (pos->exit != nullptr) {
153 pos->exit();153 pos->exit();
154 }154 }
@@ -157,9 +157,9 @@ private:
157 157 
158 void RollbackStart(const std::vector<ModuleDesc>::const_iterator &end) noexcept158 void RollbackStart(const std::vector<ModuleDesc>::const_iterator &end) noexcept
159 {159 {
160- auto next = end;
161 auto pos = end;160 auto pos = end;
162- for (--pos; next != modules.cbegin(); --next, --pos) {161+ while (pos != modules.cbegin()) {
162+ --pos;
163 if (pos->shutdown != nullptr) {163 if (pos->shutdown != nullptr) {
164 pos->shutdown();164 pos->shutdown();
165 }165 }
@@ -81,16 +81,20 @@ int LoadFd(const std::string &name, int &fd) noexcept
81 return -1;81 return -1;
82 }82 }
83 83 
84+ bool found = false;
84 for (int i = 0; i < n; ++i) {85 for (int i = 0; i < n; ++i) {
85 int cur = SD_LISTEN_FDS_START + i;86 int cur = SD_LISTEN_FDS_START + i;
86 if (name == restores[i]) {87 if (name == restores[i]) {
87 fd = cur;88 fd = cur;
88- free(restores);89+ found = true;
89- return 0;
90 }90 }
91+ free(restores[i]);
91 }92 }
92 93 
93 free(restores);94 free(restores);
95+ if (found) {
96+ return 0;
97+ }
94 DBG_LOGINFO("sd_listen_fds_with_names get fd count: " << n << ", not matches " << name);98 DBG_LOGINFO("sd_listen_fds_with_names get fd count: " << n << ", not matches " << name);
95 return -1;99 return -1;
96}100}
@@ -10,34 +10,46 @@
10 * See the Mulan PSL v2 for more details.10 * See the Mulan PSL v2 for more details.
11 */11 */
12#include <fcntl.h>12#include <fcntl.h>
13+#include <sys/stat.h>
13#include <unistd.h>14#include <unistd.h>
14#include "ock_daemon.h"15#include "ock_daemon.h"
15#include "syslog.h"16#include "syslog.h"
16 17 
17using namespace ock::daemon;18using namespace ock::daemon;
18 19 
20+namespace {
21+constexpr const char *UBSMD_LOCK_FILE = "/run/matrix/ubsmd.lock";
22+int g_lockFd = -1;
23+} // namespace
24+ 
19bool CheckIsRunning()25bool CheckIsRunning()
20{26{
21- std::string filePath = "/tmp/matrix_mem_daemon";27+ g_lockFd = open(UBSMD_LOCK_FILE, O_WRONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600);
22- std::string fileName = filePath + ".lock";28+ if (g_lockFd < 0) {
23- int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, 0600);29+ std::cerr << "Open file " << UBSMD_LOCK_FILE << " failed, error message is " << strerror(errno) << "."
24- if (fd < 0) {
25- std::cerr << "Open file " << fileName.c_str() << " failed, error message is " << strerror(errno) << "."
26 << std::endl;30 << std::endl;
27 return true;31 return true;
28 }32 }
33+ struct stat lockStat {};
34+ if (fstat(g_lockFd, &lockStat) != 0 || !S_ISREG(lockStat.st_mode) || lockStat.st_uid != getuid() ||
35+ lockStat.st_nlink != 1) {
36+ std::cerr << "Invalid ubsmd lock file." << std::endl;
37+ close(g_lockFd);
38+ g_lockFd = -1;
39+ return true;
40+ }
29 flock lock{};41 flock lock{};
30 lock.l_type = F_WRLCK;42 lock.l_type = F_WRLCK;
31 lock.l_start = 0;43 lock.l_start = 0;
32 lock.l_whence = SEEK_SET;44 lock.l_whence = SEEK_SET;
33 lock.l_len = 0;45 lock.l_len = 0;
34- auto ret = fcntl(fd, F_SETLK, &lock);46+ auto ret = fcntl(g_lockFd, F_SETLK, &lock);
35 if (ret < 0) {47 if (ret < 0) {
36 std::cerr << "Fail to start ubsmd, process lock file is locked." << std::endl;48 std::cerr << "Fail to start ubsmd, process lock file is locked." << std::endl;
37- close(fd);49+ close(g_lockFd);
50+ g_lockFd = -1;
38 return true;51 return true;
39 }52 }
40- close(fd);
41 return false;53 return false;
42}54}
43 55 
@@ -85,4 +97,4 @@ int main(int argc, char *argv[])
85 daemon.Set(nullptr);97 daemon.Set(nullptr);
86 ock::daemon::OckDaemon::PrintStartTime(start, "STOP");98 ock::daemon::OckDaemon::PrintStartTime(start, "STOP");
87 return CLEAN_EXIT_CODE;99 return CLEAN_EXIT_CODE;
88-}100+}
@@ -495,7 +495,7 @@ int32_t OckDaemon::InitLockTlsConfig()
495 ock::ubsm::UbsCommonConfig::GetInstance().SetLockKeyPath(keyPath);495 ock::ubsm::UbsCommonConfig::GetInstance().SetLockKeyPath(keyPath);
496 ock::ubsm::UbsCommonConfig::GetInstance().SetLockKeypassPath(keypassPath);496 ock::ubsm::UbsCommonConfig::GetInstance().SetLockKeypassPath(keypassPath);
497 497 
498- DBG_LOGINFO("InitLockTlsConfig finished, ca path: " << ock::ubsm::UbsCommonConfig::GetInstance().GetLockCaPath());498+ DBG_LOGINFO("InitLockTlsConfig finished.");
499 return HOK;499 return HOK;
500}500}
501 501 
@@ -536,7 +536,7 @@ int32_t OckDaemon::InitRpcTlsConfig()
536 ock::ubsm::UbsCommonConfig::GetInstance().SetCertPath(certPath);536 ock::ubsm::UbsCommonConfig::GetInstance().SetCertPath(certPath);
537 ock::ubsm::UbsCommonConfig::GetInstance().SetKeyPath(keyPath);537 ock::ubsm::UbsCommonConfig::GetInstance().SetKeyPath(keyPath);
538 ock::ubsm::UbsCommonConfig::GetInstance().SetKeypassPath(keypassPath);538 ock::ubsm::UbsCommonConfig::GetInstance().SetKeypassPath(keypassPath);
539- DBG_LOGDEBUG("InitTlsConfig finished, ca path: " << ock::ubsm::UbsCommonConfig::GetInstance().GetCaPath());539+ DBG_LOGDEBUG("InitTlsConfig finished.");
540 return HOK;540 return HOK;
541}541}
542 542 
@@ -758,6 +758,7 @@ HRESULT OckDaemon::RegisterSignalHandler()
758{758{
759 struct sigaction saUsr {};759 struct sigaction saUsr {};
760 saUsr.sa_handler = &OckDaemon::HandleSignal;760 saUsr.sa_handler = &OckDaemon::HandleSignal;
761+ sigemptyset(&saUsr.sa_mask);
761 if (sigaction(SIGTERM, &saUsr, nullptr) < 0) {762 if (sigaction(SIGTERM, &saUsr, nullptr) < 0) {
762 DBG_LOGERROR("Register signal SIGTERM failed. errno(" << errno << "). ");763 DBG_LOGERROR("Register signal SIGTERM failed. errno(" << errno << "). ");
763 return HFAIL;764 return HFAIL;
@@ -765,6 +766,7 @@ HRESULT OckDaemon::RegisterSignalHandler()
765 766 
766 struct sigaction saUsr1 {};767 struct sigaction saUsr1 {};
767 saUsr1.sa_handler = &OckDaemon::HandleSigpipe;768 saUsr1.sa_handler = &OckDaemon::HandleSigpipe;
769+ sigemptyset(&saUsr1.sa_mask);
768 if (sigaction(SIGPIPE, &saUsr1, nullptr) < 0) {770 if (sigaction(SIGPIPE, &saUsr1, nullptr) < 0) {
769 DBG_LOGERROR("Register signal SIGTERM failed. errno(" << errno << "). ");771 DBG_LOGERROR("Register signal SIGTERM failed. errno(" << errno << "). ");
770 return HFAIL;772 return HFAIL;
@@ -211,7 +211,11 @@ char *DefaultDecrypt(const char *encrypted_data, size_t encrypted_len, size_t *p
211 if (encrypted_len == 0) {211 if (encrypted_len == 0) {
212 return nullptr;212 return nullptr;
213 }213 }
214- char *result = new char[encrypted_len];214+ char *result = new (std::nothrow) char[encrypted_len];
215+ if (result == nullptr) {
216+ DBG_LOGERROR("Failed to allocate decrypt result.");
217+ return nullptr;
218+ }
215 auto ret = memcpy_s(result, encrypted_len, encrypted_data, encrypted_len);219 auto ret = memcpy_s(result, encrypted_len, encrypted_data, encrypted_len);
216 if (ret != 0) {220 if (ret != 0) {
217 DBG_LOGERROR("memcpy_s failed, ret:" << ret);221 DBG_LOGERROR("memcpy_s failed, ret:" << ret);
@@ -10,6 +10,7 @@
10 * See the Mulan PSL v2 for more details.10 * See the Mulan PSL v2 for more details.
11 */11 */
12#include "record_id_pool_allocator.h"12#include "record_id_pool_allocator.h"
13+#include <array>
13#include "log.h"14#include "log.h"
14 15 
15namespace ock {16namespace ock {
@@ -135,15 +136,37 @@ int RecordIdPoolAllocator::FillAllocated(uint32_t headIndex, std::vector<uint64_
135 }136 }
136 137 
137 auto currentIndex = headIndex;138 auto currentIndex = headIndex;
139+ uint32_t traversed = 0;
140+ std::array<bool, RECORD_MEM_ID_POOL_LINE_COUNT> visited{};
141+ visited[currentIndex] = true;
138 while (idHead.u.tail == 0U) {142 while (idHead.u.tail == 0U) {
143+ if (++traversed >= RECORD_MEM_ID_POOL_LINE_COUNT || idHead.u.nextIndex >= RECORD_MEM_ID_POOL_LINE_COUNT) {
144+ DBG_LOGERROR("Corrupted memory id chain from head index(" << headIndex << ")");
145+ ids.clear();
146+ return -1;
147+ }
148+ if (visited[idHead.u.nextIndex]) {
149+ DBG_LOGERROR("Cycle detected in memory id chain from head index(" << headIndex << ")");
150+ ids.clear();
151+ return -1;
152+ }
139 for (auto i = 1U; i < RECORD_MEM_ID_POOL_LINE_SIZE; i++) {153 for (auto i = 1U; i < RECORD_MEM_ID_POOL_LINE_SIZE; i++) {
140 ids.emplace_back(memIdRecordPool_->memIds[currentIndex][i]);154 ids.emplace_back(memIdRecordPool_->memIds[currentIndex][i]);
141 }155 }
142 156 
143 currentIndex = idHead.u.nextIndex;157 currentIndex = idHead.u.nextIndex;
158+ visited[currentIndex] = true;
144 idHead.id = memIdRecordPool_->memIds[currentIndex][0];159 idHead.id = memIdRecordPool_->memIds[currentIndex][0];
160+ if (idHead.u.used == 0U) {
161+ ids.clear();
162+ return -1;
163+ }
145 }164 }
146 165 
166+ if (idHead.u.nextIndex >= RECORD_MEM_ID_POOL_LINE_SIZE) {
167+ ids.clear();
168+ return -1;
169+ }
147 for (auto i = 0U; i < idHead.u.nextIndex && i < RECORD_MEM_ID_POOL_LINE_SIZE; i++) {170 for (auto i = 0U; i < idHead.u.nextIndex && i < RECORD_MEM_ID_POOL_LINE_SIZE; i++) {
148 ids.emplace_back(memIdRecordPool_->memIds[currentIndex][i + 1]);171 ids.emplace_back(memIdRecordPool_->memIds[currentIndex][i + 1]);
149 }172 }
@@ -178,15 +201,32 @@ int RecordIdPoolAllocator::Release(uint32_t headIndex) noexcept
178 201 
179 std::vector<uint32_t> releasedIndexes;202 std::vector<uint32_t> releasedIndexes;
180 auto currentIndex = headIndex;203 auto currentIndex = headIndex;
204+ uint32_t traversed = 0;
205+ std::array<bool, RECORD_MEM_ID_POOL_LINE_COUNT> visited{};
206+ visited[currentIndex] = true;
181 while (idHead.u.tail == 0U) {207 while (idHead.u.tail == 0U) {
182- memIdRecordPool_->memIds[currentIndex][0] = 0UL;
183 releasedIndexes.emplace_back(currentIndex);208 releasedIndexes.emplace_back(currentIndex);
209+ if (++traversed >= RECORD_MEM_ID_POOL_LINE_COUNT || idHead.u.nextIndex >= RECORD_MEM_ID_POOL_LINE_COUNT) {
210+ DBG_LOGERROR("Corrupted memory id chain from head index(" << headIndex << ")");
211+ return -1;
212+ }
213+ if (visited[idHead.u.nextIndex]) {
214+ DBG_LOGERROR("Cycle detected in memory id chain from head index(" << headIndex << ")");
215+ return -1;
216+ }
184 currentIndex = idHead.u.nextIndex;217 currentIndex = idHead.u.nextIndex;
218+ visited[currentIndex] = true;
185 idHead.id = memIdRecordPool_->memIds[currentIndex][0];219 idHead.id = memIdRecordPool_->memIds[currentIndex][0];
220+ if (idHead.u.used == 0U) {
221+ return -1;
222+ }
186 }223 }
187- memIdRecordPool_->memIds[currentIndex][0] = 0UL;
188 releasedIndexes.emplace_back(currentIndex);224 releasedIndexes.emplace_back(currentIndex);
189 225 
226+ for (auto index : releasedIndexes) {
227+ memIdRecordPool_->memIds[index][0] = 0UL;
228+ }
229+ 
190 std::unique_lock<std::mutex> uniqueLock{indexMutex_};230 std::unique_lock<std::mutex> uniqueLock{indexMutex_};
191 idleIdIndexes_.insert(idleIdIndexes_.end(), releasedIndexes.begin(), releasedIndexes.end());231 idleIdIndexes_.insert(idleIdIndexes_.end(), releasedIndexes.begin(), releasedIndexes.end());
192 uniqueLock.unlock();232 uniqueLock.unlock();
@@ -195,4 +235,4 @@ int RecordIdPoolAllocator::Release(uint32_t headIndex) noexcept
195 return 0;235 return 0;
196}236}
197} // namespace ubsm237} // namespace ubsm
198-} // namespace ock238+} // namespace ock
@@ -229,11 +229,11 @@ int InitOpensslDl()
229 return 0;229 return 0;
230 }230 }
231#ifdef DEBUG_MEM_UT231#ifdef DEBUG_MEM_UT
232- g_cryptoHandle = dlopen(ARCH_LIB_DIR "/libcrypto.so", RTLD_NOW);232+ g_cryptoHandle = dlopen(ARCH_LIB_DIR "/libcrypto.so", RTLD_NOW | RTLD_LOCAL);
233- g_sslHandle = dlopen(ARCH_LIB_DIR "/libssl.so", RTLD_NOW);233+ g_sslHandle = dlopen(ARCH_LIB_DIR "/libssl.so", RTLD_NOW | RTLD_LOCAL);
234#else234#else
235- g_cryptoHandle = dlopen(ARCH_LIB_DIR "/libcrypto.so.3", RTLD_NOW);235+ g_cryptoHandle = dlopen(ARCH_LIB_DIR "/libcrypto.so.3", RTLD_NOW | RTLD_LOCAL);
236- g_sslHandle = dlopen(ARCH_LIB_DIR "/libssl.so.3", RTLD_NOW);236+ g_sslHandle = dlopen(ARCH_LIB_DIR "/libssl.so.3", RTLD_NOW | RTLD_LOCAL);
237#endif237#endif
238 if (g_cryptoHandle == nullptr || g_sslHandle == nullptr) {238 if (g_cryptoHandle == nullptr || g_sslHandle == nullptr) {
239 DBG_LOGERROR("Failed to load OpenSSL: " << dlerror());239 DBG_LOGERROR("Failed to load OpenSSL: " << dlerror());
@@ -412,4 +412,4 @@ int VerifyCertificate(const char *caPath, const char *certPath, const char *crlP
412 }412 }
413 DBG_LOGINFO("Certificate is valid");413 DBG_LOGINFO("Certificate is valid");
414 return 0;414 return 0;
415-}415+}
@@ -369,7 +369,9 @@ void UbseMemAdapter::Destroy()
369 * 关闭dlopen句柄,清除函数指针,清除初始化状态369 * 关闭dlopen句柄,清除函数指针,清除初始化状态
370 */370 */
371 std::lock_guard<std::mutex> guard(gMutex);371 std::lock_guard<std::mutex> guard(gMutex);
372- pUbseClientFinalize();372+ if (pUbseClientFinalize != nullptr) {
373+ pUbseClientFinalize();
374+ }
373 ResetLibUbseDl();375 ResetLibUbseDl();
374 initialized_ = false;376 initialized_ = false;
375}377}
@@ -684,8 +686,8 @@ int32_t UbseMemAdapter::PopulateHostNameMap(SHMRegions &regions)
684 DBG_LOGERROR("Ubsm is not initialized.");686 DBG_LOGERROR("Ubsm is not initialized.");
685 return MXM_ERR_UBSE_INNER;687 return MXM_ERR_UBSE_INNER;
686 }688 }
687- ubs_topo_node_t *nodeList;689+ ubs_topo_node_t *nodeList = nullptr;
688- uint32_t nodeCnt;690+ uint32_t nodeCnt = 0;
689 TP_TRACE_BEGIN(TP_UBSM_GET_NODE_LIST);691 TP_TRACE_BEGIN(TP_UBSM_GET_NODE_LIST);
690 auto ret = pUbseNodeList(&nodeList, &nodeCnt);692 auto ret = pUbseNodeList(&nodeList, &nodeCnt);
691 TP_TRACE_END(TP_UBSM_GET_NODE_LIST, ret);693 TP_TRACE_END(TP_UBSM_GET_NODE_LIST, ret);
@@ -697,6 +699,7 @@ int32_t UbseMemAdapter::PopulateHostNameMap(SHMRegions &regions)
697 699 
698 if (nodeList == nullptr || nodeCnt == 0 || (nodeCnt > UBS_MEM_MAX_SLOT_NUM)) {700 if (nodeList == nullptr || nodeCnt == 0 || (nodeCnt > UBS_MEM_MAX_SLOT_NUM)) {
699 DBG_LOGERROR("pUbseNodeList failed, ret=" << ret << ", nodeCnt=" << nodeCnt);701 DBG_LOGERROR("pUbseNodeList failed, ret=" << ret << ", nodeCnt=" << nodeCnt);
702+ free(nodeList);
700 return MXM_ERR_UBSE_INNER;703 return MXM_ERR_UBSE_INNER;
701 }704 }
702 705 
@@ -720,8 +723,14 @@ int32_t UbseMemAdapter::PopulateHostNameMap(SHMRegions &regions)
720 return MXM_ERR_UBSE_INNER;723 return MXM_ERR_UBSE_INNER;
721 }724 }
722 725 
726+ if (regions.num < 0 || regions.num > MAX_REGIONS_NUM) {
727+ return MXM_ERR_REGION_PARAM_INVALID;
728+ }
723 for (int i = 0; i < regions.num; ++i) {729 for (int i = 0; i < regions.num; ++i) {
724 SHMRegionDesc &region = regions.region[i];730 SHMRegionDesc &region = regions.region[i];
731+ if (region.num < 0 || region.num > MEM_TOPOLOGY_MAX_HOSTS) {
732+ return MXM_ERR_REGION_PARAM_INVALID;
733+ }
725 for (int j = 0; j < region.num; ++j) {734 for (int j = 0; j < region.num; ++j) {
726 DBG_LOGINFO("region nodeId[" << j << "]=" << region.nodeId[j]);735 DBG_LOGINFO("region nodeId[" << j << "]=" << region.nodeId[j]);
727 uint32_t nodeId{1u};736 uint32_t nodeId{1u};
@@ -958,8 +967,8 @@ int UbseMemAdapter::LookUpClusterStatistic(ubsmemClusterInfo &clusterInfo)
958 DBG_LOGERROR("Ubsm is not initialized.");967 DBG_LOGERROR("Ubsm is not initialized.");
959 return MXM_ERR_UBSE_INNER;968 return MXM_ERR_UBSE_INNER;
960 }969 }
961- ubs_topo_node_t *nodeList;970+ ubs_topo_node_t *nodeList = nullptr;
962- uint32_t nodeCnt;971+ uint32_t nodeCnt = 0;
963 DBG_LOGINFO("LookUpClusterStatistic start.");972 DBG_LOGINFO("LookUpClusterStatistic start.");
964 auto ret = pUbseNodeList(&nodeList, &nodeCnt);973 auto ret = pUbseNodeList(&nodeList, &nodeCnt);
965 if (ret != UBS_SUCCESS) {974 if (ret != UBS_SUCCESS) {
@@ -968,17 +977,21 @@ int UbseMemAdapter::LookUpClusterStatistic(ubsmemClusterInfo &clusterInfo)
968 }977 }
969 if (nodeList == nullptr || nodeCnt == 0 || (nodeCnt > UBS_MEM_MAX_SLOT_NUM)) {978 if (nodeList == nullptr || nodeCnt == 0 || (nodeCnt > UBS_MEM_MAX_SLOT_NUM)) {
970 DBG_LOGERROR("pUbseNodeList failed, ret=" << ret << ", nodeCnt=" << nodeCnt);979 DBG_LOGERROR("pUbseNodeList failed, ret=" << ret << ", nodeCnt=" << nodeCnt);
980+ free(nodeList);
971 return MXM_ERR_UBSE_INNER;981 return MXM_ERR_UBSE_INNER;
972 }982 }
973 983 
974- ubs_mem_numastat_t *numaMems;984+ ubs_mem_numastat_t *numaMems = nullptr;
975- uint32_t numaMemCnt;985+ uint32_t numaMemCnt = 0;
976 clusterInfo.host_num = 0;986 clusterInfo.host_num = 0;
977 for (int i = 0; i < nodeCnt; ++i) {987 for (int i = 0; i < nodeCnt; ++i) {
978 DBG_LOGINFO("Query nodeId=" << std::to_string(nodeList[i].slot_id) << ", nodeCnt=" << nodeCnt);988 DBG_LOGINFO("Query nodeId=" << std::to_string(nodeList[i].slot_id) << ", nodeCnt=" << nodeCnt);
989+ numaMems = nullptr;
990+ numaMemCnt = 0;
979 ret = pUbseNumaStatGet(nodeList[i].slot_id, &numaMems, &numaMemCnt);991 ret = pUbseNumaStatGet(nodeList[i].slot_id, &numaMems, &numaMemCnt);
980 if (ret != UBS_SUCCESS || numaMems == nullptr || numaMemCnt == 0 || numaMemCnt > UBS_TOPO_NUMA_NUM) {992 if (ret != UBS_SUCCESS || numaMems == nullptr || numaMemCnt == 0 || numaMemCnt > UBS_TOPO_NUMA_NUM) {
981 DBG_LOGERROR("pUbseNumaStatGet failed, ret: " << ret);993 DBG_LOGERROR("pUbseNumaStatGet failed, ret: " << ret);
994+ free(numaMems);
982 continue;995 continue;
983 }996 }
984 997 
@@ -1270,8 +1283,8 @@ int UbseMemAdapter::GetSlotIdFromHostName(const std::string &hostName, uint32_t
1270 DBG_LOGERROR("Host name is empty");1283 DBG_LOGERROR("Host name is empty");
1271 return MXM_ERR_PARAM_INVALID;1284 return MXM_ERR_PARAM_INVALID;
1272 }1285 }
1273- ubs_topo_node_t *nodeList;1286+ ubs_topo_node_t *nodeList = nullptr;
1274- uint32_t nodeCnt;1287+ uint32_t nodeCnt = 0;
1275 TP_TRACE_BEGIN(TP_UBSM_GET_NODE_LIST);1288 TP_TRACE_BEGIN(TP_UBSM_GET_NODE_LIST);
1276 ret = pUbseNodeList(&nodeList, &nodeCnt);1289 ret = pUbseNodeList(&nodeList, &nodeCnt);
1277 TP_TRACE_END(TP_UBSM_GET_NODE_LIST, ret);1290 TP_TRACE_END(TP_UBSM_GET_NODE_LIST, ret);
@@ -1283,6 +1296,7 @@ int UbseMemAdapter::GetSlotIdFromHostName(const std::string &hostName, uint32_t
1283 1296 
1284 if (nodeList == nullptr || nodeCnt == 0 || (nodeCnt > UBS_MEM_MAX_SLOT_NUM)) {1297 if (nodeList == nullptr || nodeCnt == 0 || (nodeCnt > UBS_MEM_MAX_SLOT_NUM)) {
1285 DBG_LOGERROR("pUbseNodeList return invalid, ret=" << ret << ", nodeCnt=" << nodeCnt);1298 DBG_LOGERROR("pUbseNodeList return invalid, ret=" << ret << ", nodeCnt=" << nodeCnt);
1299+ free(nodeList);
1286 return MXM_ERR_UBSE_INNER;1300 return MXM_ERR_UBSE_INNER;
1287 }1301 }
1288 1302 
@@ -2014,4 +2028,4 @@ int UbseMemAdapter::EnsureGetLocalNodeId(uint32_t &nid)
2014 return HOK;2028 return HOK;
2015}2029}
2016} // namespace mxm2030} // namespace mxm
2017-} // namespace ock2031+} // namespace ock
@@ -1,162 +0,0 @@
1-/*
2- * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
3- */
4-#include <dlfcn.h>
5-#include <gtest/gtest.h>
6-#include <mockcpp/mockcpp.hpp>
7- 
8-#include "common/hdagger/thread_pool/dg_execution_service.h"
9- 
10-using testing::Test;
11- 
12-namespace UT {
13-using namespace ock::dagger;
14- 
15-class DgExecutionServiceTestSuite : public Test {
16-public:
17- DgExecutionServiceTestSuite();
18- void SetUp() override;
19- void TearDown() override;
20- 
21-protected:
22- static ExecutorServicePtr executorService;
23-};
24- 
25-class Task : public Runnable {
26-public:
27- void Run() override
28- {
29- std::cout << "task is executed" << std::endl;
30- }
31-};
32- 
33-ExecutorServicePtr DgExecutionServiceTestSuite::executorService;
34- 
35-DgExecutionServiceTestSuite::DgExecutionServiceTestSuite() = default;
36- 
37-void DgExecutionServiceTestSuite::SetUp()
38-{
39- executorService = ExecutorService::Create(1, 128);
40- ASSERT_TRUE(executorService.Get() != nullptr);
41- 
42- executorService->SetThreadName("tt");
43- ASSERT_TRUE(executorService->Start());
44-}
45- 
46-void DgExecutionServiceTestSuite::TearDown()
47-{
48- executorService->Stop();
49-}
50- 
51-TEST_F(DgExecutionServiceTestSuite, TestExecutionService)
52-{
53- auto t = new (std::nothrow) Task();
54- ASSERT_TRUE(executorService->Execute(t));
55- 
56- sleep(1);
57-}
58- 
59-TEST_F(DgExecutionServiceTestSuite, TestLambdaExpression)
60-{
61- struct timespec ts {};
62- sem_t waitSem{};
63- 
64- auto ret = clock_gettime(CLOCK_REALTIME, &ts);
65- ASSERT_EQ(0, ret) << "get system time failed: " << errno << ": " << strerror(errno);
66- 
67- ret = sem_init(&waitSem, 0, 0);
68- ASSERT_EQ(0, ret) << "initialize sem failed: " << errno << ": " << strerror(errno);
69- 
70- auto task = [&waitSem]() {
71- sem_post(&waitSem);
72- };
73- auto success = executorService->Execute(task);
74- ASSERT_TRUE(success);
75- 
76- ts.tv_sec += 5;
77- ret = sem_timedwait(&waitSem, &ts);
78- ASSERT_EQ(0, ret) << "wait sem failed: " << errno << ": " << strerror(errno);
79- 
80- sem_destroy(&waitSem);
81-}
82- 
83-TEST_F(DgExecutionServiceTestSuite, Execute_NullptrTask)
84-{
85- Runnable *t = nullptr;
86- auto success = executorService->Execute(t);
87- EXPECT_FALSE(success);
88-}
89- 
90-TEST_F(DgExecutionServiceTestSuite, Create_WithInvalidThreadNum)
91-{
92- auto s1 = ExecutorService::Create(-1);
93- auto s2 = ExecutorService::Create(0);
94- auto s3 = ExecutorService::Create(300);
95- EXPECT_EQ(nullptr, s1.Get());
96- EXPECT_EQ(nullptr, s2.Get());
97- EXPECT_EQ(nullptr, s3.Get());
98-}
99- 
100-TEST_F(DgExecutionServiceTestSuite, Start_Twice)
101-{
102- ASSERT_TRUE(executorService->Start());
103- ASSERT_TRUE(executorService->Start());
104-}
105- 
106-TEST_F(DgExecutionServiceTestSuite, Stop_Twice)
107-{
108- executorService->Stop();
109- executorService->Stop();
110- SUCCEED();
111-}
112- 
113-TEST_F(DgExecutionServiceTestSuite, Runnable_RunWithNullTask)
114-{
115- Runnable r;
116- r.Run();
117- SUCCEED();
118-}
119- 
120-TEST_F(DgExecutionServiceTestSuite, DoRunnable_RuntimeError)
121-{
122- bool flag = true;
123- auto r = MakeRef<Runnable>([]() { throw std::runtime_error("test"); });
124- executorService->Execute(r);
125- sleep(1);
126-}
127- 
128-TEST_F(DgExecutionServiceTestSuite, DoRunnable_UnknownException)
129-{
130- auto r = MakeRef<Runnable>([]() { throw 42; });
131- executorService->Execute(r);
132- sleep(1);
133-}
134- 
135-TEST(DgExecutionServiceStandalone, Create_WithZeroQueueCapacity)
136-{
137- auto svc = ExecutorService::Create(1, 0);
138- ASSERT_TRUE(svc.Get() != nullptr);
139-}
140- 
141-TEST(DgExecutionServiceStandalone, DestructorWithoutStop)
142-{
143- auto svc = ExecutorService::Create(1, 10);
144-}
145- 
146-TEST(DgExecutionServiceStandalone, Stop_NewRunnableNull)
147-{
148- auto svc = ExecutorService::Create(1, 10);
149- svc->Start();
150- svc->Stop();
151-}
152- 
153-TEST(DgExecutionServiceStandalone, RunInThread_WithEmptyNameAndCpuBind)
154-{
155- auto svc = ExecutorService::Create(1, 10);
156- svc->SetCpuSetStartIndex(0);
157- svc->SetThreadName("");
158- ASSERT_TRUE(svc->Start());
159- svc->Stop();
160-}
161- 
162-} // namespace UT
@@ -1,158 +0,0 @@
1-/*
2- * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
3- */
4-#include <dlfcn.h>
5-#include <gtest/gtest.h>
6-#include <mockcpp/mockcpp.hpp>
7- 
8-#include "common/hdagger/container/dg_ring_buffer.h"
9- 
10-using testing::Test;
11- 
12-namespace UT {
13-using namespace ock::dagger;
14- 
15-class DgRingBufferTestSuite : public Test {
16-protected:
17- void SetUp() override {}
18- 
19- void TearDown() override
20- {
21- mockcpp::GlobalMockObject::verify();
22- mockcpp::GlobalMockObject::reset();
23- }
24-};
25- 
26-TEST_F(DgRingBufferTestSuite, TestRingBufferInit)
27-{
28- RingBuffer<uint32_t> rb(0);
29- ASSERT_NE(rb.Initialize(), 0);
30- rb.Capacity(10);
31- ASSERT_EQ(rb.Initialize(), 0);
32- ASSERT_EQ(rb.Capacity(), 10);
33- 
34- RingBuffer<uint32_t> rb1(100);
35- ASSERT_EQ(rb1.Initialize(), 0);
36- 
37- rb1.Capacity(10);
38- ASSERT_NE(rb1.Capacity(), 10);
39- ASSERT_EQ(rb1.Capacity(), 100);
40-}
41- 
42-TEST_F(DgRingBufferTestSuite, TestRingBufferExecuteFront)
43-{
44- RingBuffer<uint32_t> rb(2);
45- ASSERT_EQ(rb.Initialize(), 0);
46- ASSERT_EQ(rb.Size(), 0);
47- 
48- /* test PushFront */
49- ASSERT_EQ(rb.PushFront(0), true);
50- ASSERT_EQ(rb.Size(), 1);
51- ASSERT_EQ(rb.PushFront(1), true);
52- ASSERT_EQ(rb.Size(), 2);
53- ASSERT_EQ(rb.PushFront(2), false);
54- ASSERT_EQ(rb.Size(), 2);
55- 
56- /* test PopFront */
57- uint32_t item = 0;
58- ASSERT_EQ(rb.PopFront(item), true);
59- ASSERT_EQ(item, 1);
60- ASSERT_EQ(rb.Size(), 1);
61- 
62- ASSERT_EQ(rb.PopFront(item), true);
63- ASSERT_EQ(item, 0);
64- ASSERT_EQ(rb.Size(), 0);
65- 
66- ASSERT_EQ(rb.PopFront(item), false);
67- 
68- /* test PushFrontN */
69- uint32_t items[3] = {0, 1, 2};
70- ASSERT_EQ(rb.PushFrontN(items, 3), false);
71- ASSERT_EQ(rb.PushFrontN(items, 2), true);
72- ASSERT_EQ(rb.Size(), 2);
73- 
74- ASSERT_EQ(rb.PopFront(item), true);
75- ASSERT_EQ(item, 1);
76- ASSERT_EQ(rb.Size(), 1);
77- 
78- ASSERT_EQ(rb.PopFront(item), true);
79- ASSERT_EQ(item, 0);
80- ASSERT_EQ(rb.Size(), 0);
81- 
82- ASSERT_EQ(rb.PopFront(item), false);
83- 
84- /* test PopFrontN */
85- uint32_t items1[3] = {0, 1, 2};
86- ASSERT_EQ(rb.PushFrontN(items, 2), true);
87- ASSERT_EQ(rb.PopFrontN(items1, 3), false);
88- ASSERT_EQ(rb.PopFrontN(items1, 2), true);
89- ASSERT_EQ(rb.Size(), 0);
90- ASSERT_EQ(items1[0], 1);
91- ASSERT_EQ(items1[1], 0);
92- 
93- /* test PopFrontNFlex */
94- uint32_t n = 3;
95- ASSERT_EQ(rb.PushFrontN(items, 2), true);
96- ASSERT_EQ(rb.PopFrontNFlex(items1, n), true);
97- ASSERT_EQ(rb.Size(), 0);
98- ASSERT_EQ(n, 2);
99-}
100- 
101-TEST_F(DgRingBufferTestSuite, TestRingBufferExecuteBack)
102-{
103- RingBuffer<uint32_t> rb(2);
104- ASSERT_EQ(rb.Initialize(), 0);
105- ASSERT_EQ(rb.Size(), 0);
106- 
107- /* test PushBack */
108- ASSERT_EQ(rb.PushBack(0), true);
109- ASSERT_EQ(rb.Size(), 1);
110- ASSERT_EQ(rb.PushBack(1), true);
111- ASSERT_EQ(rb.Size(), 2);
112- ASSERT_EQ(rb.PushBack(2), false);
113- ASSERT_EQ(rb.Size(), 2);
114- 
115- uint32_t item = 0;
116- ASSERT_EQ(rb.PopFront(item), true);
117- ASSERT_EQ(rb.PopFront(item), true);
118- ASSERT_EQ(rb.Size(), 0);
119- 
120- /* test PushBackN */
121- uint32_t items[3] = {0, 1, 2};
122- uint32_t items1[3] = {0, 1, 2};
123- ASSERT_EQ(rb.PushBackN(items, 2), true);
124- ASSERT_EQ(rb.Size(), 2);
125- ASSERT_EQ(rb.PushBackN(items, 2), false);
126- ASSERT_EQ(rb.Size(), 2);
127- ASSERT_EQ(rb.PopFrontN(items1, 3), false);
128- ASSERT_EQ(rb.PopFrontN(items1, 2), true);
129- ASSERT_EQ(rb.Size(), 0);
130- ASSERT_EQ(items1[0], 0);
131- ASSERT_EQ(items1[1], 1);
132-}
133- 
134-TEST_F(DgRingBufferTestSuite, TestRingBufferQueue)
135-{
136- uint32_t item1 = 1;
137- const uint32_t item2 = 2;
138- uint32_t item3 = 3;
139- const uint32_t item4 = 4;
140- 
141- RingBufferBlockingQueue<uint32_t> queue(16);
142- ASSERT_EQ(queue.Initialize(), 0);
143- ASSERT_EQ(queue.Enqueue(item1), true);
144- ASSERT_EQ(queue.Enqueue(item2), true);
145- ASSERT_EQ(queue.EnqueueFirst(item3), true);
146- ASSERT_EQ(queue.EnqueueFirst(item4), true);
147- 
148- uint32_t out = 0;
149- ASSERT_EQ(queue.Dequeue(out), true);
150- ASSERT_EQ(out, 4);
151- ASSERT_EQ(queue.Dequeue(out), true);
152- ASSERT_EQ(out, 3);
153- ASSERT_EQ(queue.Dequeue(out), true);
154- ASSERT_EQ(out, 1);
155- ASSERT_EQ(queue.Dequeue(out), true);
156- ASSERT_EQ(out, 2);
157-}
158-} // namespace UT
@@ -24,20 +24,6 @@ protected:
24 }24 }
25};25};
26 26 
27-class Task : public Runnable {
28-public:
29- void Run() override
30- {
31- std::cout << "task is executed" << std::endl;
32- }
33-};
34- 
35-TEST_F(RackMemFunctionsTestSuite, TestGetThreadExecutorService)
36-{
37- ASSERT_NE(GetOneThreadExecutorService(), nullptr);
38- ASSERT_NE(GetMoreThreadExecutorService(), nullptr);
39-}
40- 
41TEST_F(RackMemFunctionsTestSuite, TestMemStrUtil)27TEST_F(RackMemFunctionsTestSuite, TestMemStrUtil)
42{28{
43 uint64_t value = 0;29 uint64_t value = 0;
@@ -3,6 +3,7 @@
3 */3 */
4#include "mxm_com.h"4#include "mxm_com.h"
5#include <sys/socket.h>5#include <sys/socket.h>
6+#include <limits>
6#ifdef DEBUG_MEM_UT7#ifdef DEBUG_MEM_UT
7#define private public8#define private public
8#define protected public9#define protected public
@@ -133,6 +134,7 @@ TEST_F(MxmComTestSuite, TestMxmComBaseInterface4)
133 EXPECT_EQ(type, MxmChannelType::NORMAL);134 EXPECT_EQ(type, MxmChannelType::NORMAL);
134 auto name = info.GetEngineName();135 auto name = info.GetEngineName();
135 EXPECT_EQ(name, "engineName");136 EXPECT_EQ(name, "engineName");
137+ EXPECT_NE(info.ConvertMxmComChannelInfoToString().find("channel id: invalid"), std::string::npos);
136}138}
137 139 
138TEST_F(MxmComTestSuite, TestMxmComBaseInterface5)140TEST_F(MxmComTestSuite, TestMxmComBaseInterface5)
@@ -156,7 +158,8 @@ TEST_F(MxmComTestSuite, TestMxmComBaseInterface5)
156 158 
157 UBSHcomServiceContext context{};159 UBSHcomServiceContext context{};
158 MxmUdsIdInfo udsIdInfo{};160 MxmUdsIdInfo udsIdInfo{};
161+ EXPECT_EQ(MxmComMessage::AllocMessage(std::numeric_limits<uint32_t>::max()), nullptr);
159 delete[] messagePtr;162 delete[] messagePtr;
160 ctx.FreeMessage();163 ctx.FreeMessage();
161}164}
162-} // namespace UT165+} // namespace UT
@@ -413,4 +413,16 @@ TEST_F(RecordStoreTest, TestFillAllocated_FailWhenHeadIndexInvalid)
413 ret = poolAllocator_.FillAllocated(7777U, TEST_LEASE_RECORD.second.memIds);413 ret = poolAllocator_.FillAllocated(7777U, TEST_LEASE_RECORD.second.memIds);
414 EXPECT_EQ(ret, -1);414 EXPECT_EQ(ret, -1);
415}415}
416+ 
417+TEST_F(RecordStoreTest, TestCorruptedIdChainDoesNotLoopForever)
418+{
419+ constexpr uint64_t USED_AND_HEAD_WITH_SELF_LOOP = 3U;
420+ ptr->memIds[0][0] = USED_AND_HEAD_WITH_SELF_LOOP;
421+ std::vector<uint64_t> ids;
422+ EXPECT_EQ(poolAllocator_.FillAllocated(0, ids), -1);
423+ EXPECT_TRUE(ids.empty());
424+ EXPECT_EQ(poolAllocator_.Release(0), -1);
425+ EXPECT_EQ(ptr->memIds[0][0], USED_AND_HEAD_WITH_SELF_LOOP);
426+ ptr->memIds[0][0] = 0;
427+}
416} // namespace UT428} // namespace UT