Make changing of shm file mode thread safe 24/157124/4
authorPiotr Sawicki <p.sawicki2@partner.samsung.com>
Mon, 23 Oct 2017 07:04:14 +0000 (09:04 +0200)
committerTomasz Swierczek <t.swierczek@samsung.com>
Tue, 24 Oct 2017 09:12:34 +0000 (09:12 +0000)
Change-Id: Id7b07a203878fdf16414c3b3fae281918671d345

TEECLib/src/teec_api.c

index a84aac7..0860520 100644 (file)
@@ -41,6 +41,7 @@
 
 #define SHM_MAX_ID                             INT32_MAX
 #define SHM_NAME_TEMPLATE              "/teec_shm%d"
+#define SHM_FILE_MODE                  0660
 /*-----------------------------------------------------------------------------
  *  Globals
  *-----------------------------------------------------------------------------*/
@@ -98,23 +99,27 @@ static int32_t allocateSharedMemory(TEEC_SharedMemory *shm) {
        int fd_shm = -1;
        int res;
 
-       mode_t origMask = umask(0);
-
        do {
                res = snprintf(shm_name, sizeof(shm_name), SHM_NAME_TEMPLATE, memKey);
                if (res == sizeof(shm_name)) {
-                       umask(origMask);
                        LOGE(TEEC_LIB, "the shm object name is too long");
                        return TEEC_ERROR_GENERIC;
                }
 
-               fd_shm = shm_open(shm_name, O_RDWR | O_CREAT | O_EXCL, 0660);
+               fd_shm = shm_open(shm_name, O_RDWR | O_CREAT | O_EXCL, SHM_FILE_MODE);
                if (fd_shm >= 0) {
+                       res = fchmod(fd_shm, SHM_FILE_MODE);
+                       if (res == -1) {
+                               close(fd_shm);
+                               shm_unlink(shm_name);
+                               LOGE(TEEC_LIB, "Cannot change permission of the %s shared memory file, error: %s",
+                                    shm_name, strerror(errno));
+                               return TEEC_ERROR_GENERIC;
+                       }
                        break;
                }
 
                if (errno != EEXIST) {
-                       umask(origMask);
                        LOGE(TEEC_LIB, "Cannot create shared memory object, error: %s", strerror(errno));
                        return TEEC_ERROR_GENERIC;
                }
@@ -122,8 +127,6 @@ static int32_t allocateSharedMemory(TEEC_SharedMemory *shm) {
                memKey++;
        } while (memKey < SHM_MAX_ID);
 
-       umask(origMask);
-
        if (memKey == SHM_MAX_ID) {
                LOGE(TEEC_LIB, "Cannot find free shared memory slot");
                return TEEC_ERROR_GENERIC;