]> Cypherpunks repositories - keks.git/commitdiff
Do not leave opened file after mmap
authorSergey Matveev <stargrave@stargrave.org>
Wed, 24 Sep 2025 09:23:47 +0000 (12:23 +0300)
committerSergey Matveev <stargrave@stargrave.org>
Wed, 24 Sep 2025 09:23:47 +0000 (12:23 +0300)
c/cmd/lib/mmap.c

index 9f533799830bd81b962ce5b0bf510a185a7f26a689d6e4c621e901945a976363..78079266b60d2a6fbe44f5166e24693170cd7ab149328edd396248df0c81a4d3 100644 (file)
@@ -6,6 +6,7 @@
 #include <string.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
+#include <unistd.h>
 
 #include "mmap.h"
 
@@ -14,11 +15,13 @@ Mmap(unsigned char **buf, size_t *len, const char *path)
 {
     int fd = open(path, O_RDONLY | O_CLOEXEC); // NOLINT(hicpp-signed-bitwise)
     if (fd == -1) {
+        fprintf(stderr, "open: %s\n", strerror(errno));
         return false;
     }
     struct stat sb;
     memset(&sb, 0, sizeof(struct stat));
     if (fstat(fd, &sb) != 0) {
+        fprintf(stderr, "fstat: %s\n", strerror(errno));
         return false;
     }
     (*len) = (size_t)sb.st_size;
@@ -26,7 +29,7 @@ Mmap(unsigned char **buf, size_t *len, const char *path)
     (*buf) = mmap(NULL, *len, PROT_READ, MAP_SHARED, fd, 0);
     if ((*buf) == MAP_FAILED) { // NOLINT(performance-no-int-to-ptr)
         fprintf(stderr, "mmap: %s\n", strerror(errno));
-        return false;
     }
-    return true;
+    close(fd);
+    return (*buf) != MAP_FAILED; // NOLINT(performance-no-int-to-ptr)
 }