]> git.proxmox.com Git - ceph.git/blob - ceph/src/pmdk/src/core/util_posix.c
import ceph 16.2.7
[ceph.git] / ceph / src / pmdk / src / core / util_posix.c
1 // SPDX-License-Identifier: BSD-3-Clause
2 /* Copyright 2015-2020, Intel Corporation */
3
4 /*
5 * util_posix.c -- Abstraction layer for misc utilities (Posix implementation)
6 */
7
8 #include <string.h>
9 #include <limits.h>
10 #include <stdlib.h>
11 #include <sys/stat.h>
12 #include <errno.h>
13 #include "os.h"
14 #include "out.h"
15 #include "util.h"
16
17 /* pass through for Posix */
18 void
19 util_strerror(int errnum, char *buff, size_t bufflen)
20 {
21 strerror_r(errnum, buff, bufflen);
22 }
23
24 /*
25 * util_strwinerror -- should never be called on posix OS - abort()
26 */
27 void
28 util_strwinerror(unsigned long err, char *buff, size_t bufflen)
29 {
30 abort();
31 }
32
33 /*
34 * util_part_realpath -- get canonicalized absolute pathname
35 *
36 * As paths used in a poolset file have to be absolute (checked when parsing
37 * a poolset file), here we only have to resolve symlinks.
38 */
39 char *
40 util_part_realpath(const char *path)
41 {
42 return realpath(path, NULL);
43 }
44
45 /*
46 * util_compare_file_inodes -- compare device and inodes of two files;
47 * this resolves hard links
48 */
49 int
50 util_compare_file_inodes(const char *path1, const char *path2)
51 {
52 struct stat sb1, sb2;
53 if (os_stat(path1, &sb1)) {
54 if (errno != ENOENT) {
55 ERR("!stat failed for %s", path1);
56 return -1;
57 }
58 LOG(1, "stat failed for %s", path1);
59 errno = 0;
60 return strcmp(path1, path2) != 0;
61 }
62
63 if (os_stat(path2, &sb2)) {
64 if (errno != ENOENT) {
65 ERR("!stat failed for %s", path2);
66 return -1;
67 }
68 LOG(1, "stat failed for %s", path2);
69 errno = 0;
70 return strcmp(path1, path2) != 0;
71 }
72
73 return sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino;
74 }
75
76 /*
77 * util_aligned_malloc -- allocate aligned memory
78 */
79 void *
80 util_aligned_malloc(size_t alignment, size_t size)
81 {
82 void *retval = NULL;
83
84 errno = posix_memalign(&retval, alignment, size);
85
86 return retval;
87 }
88
89 /*
90 * util_aligned_free -- free allocated memory in util_aligned_malloc
91 */
92 void
93 util_aligned_free(void *ptr)
94 {
95 free(ptr);
96 }
97
98 /*
99 * util_getexecname -- return name of current executable
100 */
101 char *
102 util_getexecname(char *path, size_t pathlen)
103 {
104 ASSERT(pathlen != 0);
105 ssize_t cc;
106
107 #ifdef __FreeBSD__
108 #include <sys/types.h>
109 #include <sys/sysctl.h>
110
111 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
112
113 cc = (sysctl(mib, 4, path, &pathlen, NULL, 0) == -1) ?
114 -1 : (ssize_t)pathlen;
115 #else
116 cc = readlink("/proc/self/exe", path, pathlen);
117 #endif
118 if (cc == -1) {
119 strncpy(path, "unknown", pathlen);
120 path[pathlen - 1] = '\0';
121 } else {
122 path[cc] = '\0';
123 }
124
125 return path;
126 }