]> git.sesse.net Git - cubemap/blobdiff - util.cpp
Tweak the MutexLock implementation slightly, so as to confuse Coverity less.
[cubemap] / util.cpp
index 8159e3821ccb1071efa8801ae8a63b90b65d2db4..25a8da4a1e8893ca2407615d418aeab7fffe81d5 100644 (file)
--- a/util.cpp
+++ b/util.cpp
@@ -2,6 +2,7 @@
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <sys/stat.h>
 #include <unistd.h>
 
 #include "log.h"
@@ -12,7 +13,9 @@ using namespace std;
 int make_tempfile(const std::string &contents)
 {
        char filename[] = "/tmp/cubemap.XXXXXX";
+       mode_t old_umask = umask(077);
        int fd = mkstemp(filename);
+       umask(old_umask);
        if (fd == -1) {
                log_perror("mkstemp");
                return -1;
@@ -29,7 +32,7 @@ int make_tempfile(const std::string &contents)
                ssize_t ret = write(fd, ptr, to_write);
                if (ret == -1) {
                        log_perror("write");
-                       close(fd);
+                       safe_close(fd);
                        return -1;
                }
 
@@ -40,24 +43,28 @@ int make_tempfile(const std::string &contents)
        return fd;
 }
 
+bool read_tempfile_and_close(int fd, std::string *contents)
+{
+       bool ok = read_tempfile(fd, contents);
+       safe_close(fd);  // Implicitly deletes the file.
+       return ok;
+}
+
 bool read_tempfile(int fd, std::string *contents)
 {
-       bool ok = true;
        ssize_t ret, has_read;
 
        off_t len = lseek(fd, 0, SEEK_END);
        if (len == -1) {
                log_perror("lseek");
-               ok = false;
-               goto done;
+               return false;
        }
 
        contents->resize(len);
 
        if (lseek(fd, 0, SEEK_SET) == -1) {
                log_perror("lseek");
-               ok = false;
-               goto done;
+               return false;
        }
 
        has_read = 0;
@@ -65,26 +72,28 @@ bool read_tempfile(int fd, std::string *contents)
                ret = read(fd, &((*contents)[has_read]), len - has_read);
                if (ret == -1) {
                        log_perror("read");
-                       ok = false;
-                       goto done;
+                       return false;
                }
                if (ret == 0) {
                        log(ERROR, "Unexpected EOF!");
-                       ok = false;
-                       goto done;
+                       return false;
                }
                has_read += ret;
        }
 
-done:
+       return true;
+}
+
+int safe_close(int fd)
+{
+       int ret;
        do {
-               ret = close(fd);  // Implicitly deletes the files.
+               ret = close(fd);
        } while (ret == -1 && errno == EINTR);
-       
+
        if (ret == -1) {
-               log_perror("close");
-               // Can still continue.
+               log_perror("close()");
        }
 
-       return ok;
+       return ret;
 }