2 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 Raphaël Beamonte <raphael.beamonte@gmail.com>
4 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
6 * SPDX-License-Identifier: GPL-2.0-only
10 #include "common/macros.h"
18 #include <sys/types.h>
26 #include <common/common.h>
27 #include <common/readwrite.h>
28 #include <common/runas.h>
29 #include <common/compat/getenv.h>
30 #include <common/compat/string.h>
31 #include <common/compat/dirent.h>
32 #include <common/compat/directory-handle.h>
33 #include <common/dynamic-buffer.h>
34 #include <common/string-utils/format.h>
35 #include <lttng/constant.h>
41 #define PROC_MEMINFO_PATH "/proc/meminfo"
42 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
43 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
45 /* The length of the longest field of `/proc/meminfo`. */
46 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
48 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
49 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
51 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
54 #define FALLBACK_USER_BUFLEN 16384
55 #define FALLBACK_GROUP_BUFLEN 16384
58 * Return a partial realpath(3) of the path even if the full path does not
59 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
60 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
61 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
62 * point directory does not exist.
63 * In case resolved_path is NULL, the string returned was allocated in the
64 * function and thus need to be freed by the caller. The size argument allows
65 * to specify the size of the resolved_path argument if given, or the size to
69 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
71 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
72 const char *next
, *prev
, *end
;
80 * Identify the end of the path, we don't want to treat the
81 * last char if it is a '/', we will just keep it on the side
82 * to be added at the end, and return a value coherent with
83 * the path given as argument
85 end
= path
+ strlen(path
);
86 if (*(end
-1) == '/') {
90 /* Initiate the values of the pointers before looping */
93 /* Only to ensure try_path is not NULL to enter the while */
94 try_path
= (char *)next
;
96 /* Resolve the canonical path of the first part of the path */
97 while (try_path
!= NULL
&& next
!= end
) {
98 char *try_path_buf
= NULL
;
101 * If there is not any '/' left, we want to try with
104 next
= strpbrk(next
+ 1, "/");
109 /* Cut the part we will be trying to resolve */
110 cut_path
= lttng_strndup(path
, next
- path
);
111 if (cut_path
== NULL
) {
112 PERROR("lttng_strndup");
116 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
122 /* Try to resolve this part */
123 try_path
= realpath((char *) cut_path
, try_path_buf
);
124 if (try_path
== NULL
) {
127 * There was an error, we just want to be assured it
128 * is linked to an unexistent directory, if it's another
129 * reason, we spawn an error
133 /* Ignore the error */
136 PERROR("realpath (partial_realpath)");
141 /* Save the place we are before trying the next step */
144 try_path_prev
= try_path
;
148 /* Free the allocated memory */
153 /* Allocate memory for the resolved path if necessary */
154 if (resolved_path
== NULL
) {
155 resolved_path
= zmalloc(size
);
156 if (resolved_path
== NULL
) {
157 PERROR("zmalloc resolved path");
163 * If we were able to solve at least partially the path, we can concatenate
164 * what worked and what didn't work
166 if (try_path_prev
!= NULL
) {
167 /* If we risk to concatenate two '/', we remove one of them */
168 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
169 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
173 * Duplicate the memory used by prev in case resolved_path and
174 * path are pointers for the same memory space
176 cut_path
= strdup(prev
);
177 if (cut_path
== NULL
) {
182 /* Concatenate the strings */
183 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
185 /* Free the allocated memory */
189 try_path_prev
= NULL
;
191 * Else, we just copy the path in our resolved_path to
195 strncpy(resolved_path
, path
, size
);
198 /* Then we return the 'partially' resolved path */
199 return resolved_path
;
205 if (try_path_prev
!= try_path
) {
212 int expand_double_slashes_dot_and_dotdot(char *path
)
214 size_t expanded_path_len
, path_len
;
215 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
217 path_len
= strlen(path
);
218 path_last_char
= &path
[path_len
];
224 expanded_path_len
= 0;
226 /* We iterate over the provided path to expand the "//", "../" and "./" */
227 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
228 /* Find the next forward slash. */
229 size_t curr_token_len
;
231 if (curr_char
== path_last_char
) {
236 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
237 if (next_slash
== NULL
) {
238 /* Reached the end of the provided path. */
239 next_slash
= path_last_char
;
242 /* Compute how long is the previous token. */
243 curr_token_len
= next_slash
- curr_char
;
244 switch(curr_token_len
) {
247 * The pointer has not move meaning that curr_char is
248 * pointing to a slash. It that case there is no token
249 * to copy, so continue the iteration to find the next
255 * The pointer moved 1 character. Check if that
256 * character is a dot ('.'), if it is: omit it, else
257 * copy the token to the normalized path.
259 if (curr_char
[0] == '.') {
265 * The pointer moved 2 characters. Check if these
266 * characters are double dots ('..'). If that is the
267 * case, we need to remove the last token of the
270 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
272 * Find the previous path component by
273 * using the memrchr function to find the
274 * previous forward slash and substract that
275 * len to the resulting path.
277 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
279 * If prev_slash is NULL, we reached the
280 * beginning of the path. We can't go back any
283 if (prev_slash
!= NULL
) {
284 expanded_path_len
= prev_slash
- path
;
294 * Copy the current token which is neither a '.' nor a '..'.
296 path
[expanded_path_len
++] = '/';
297 memmove(&path
[expanded_path_len
], curr_char
, curr_token_len
);
298 expanded_path_len
+= curr_token_len
;
301 if (expanded_path_len
== 0) {
302 path
[expanded_path_len
++] = '/';
305 path
[expanded_path_len
] = '\0';
312 * Make a full resolution of the given path even if it doesn't exist.
313 * This function uses the utils_partial_realpath function to resolve
314 * symlinks and relatives paths at the start of the string, and
315 * implements functionnalities to resolve the './' and '../' strings
316 * in the middle of a path. This function is only necessary because
317 * realpath(3) does not accept to resolve unexistent paths.
318 * The returned string was allocated in the function, it is thus of
319 * the responsibility of the caller to free this memory.
322 char *_utils_expand_path(const char *path
, bool keep_symlink
)
325 char *absolute_path
= NULL
;
327 bool is_dot
, is_dotdot
;
334 /* Allocate memory for the absolute_path */
335 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
336 if (absolute_path
== NULL
) {
337 PERROR("zmalloc expand path");
341 if (path
[0] == '/') {
342 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
344 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
349 * This is a relative path. We need to get the present working
350 * directory and start the path walk from there.
352 char current_working_dir
[LTTNG_PATH_MAX
];
355 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
360 * Get the number of character in the CWD and allocate an array
361 * to can hold it and the path provided by the caller.
363 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
364 current_working_dir
, path
);
365 if (ret
>= LTTNG_PATH_MAX
) {
366 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
367 current_working_dir
, path
, LTTNG_PATH_MAX
);
373 /* Resolve partially our path */
374 absolute_path
= utils_partial_realpath(absolute_path
,
375 absolute_path
, LTTNG_PATH_MAX
);
376 if (!absolute_path
) {
381 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
386 /* Identify the last token */
387 last_token
= strrchr(absolute_path
, '/');
389 /* Verify that this token is not a relative path */
390 is_dotdot
= (strcmp(last_token
, "/..") == 0);
391 is_dot
= (strcmp(last_token
, "/.") == 0);
393 /* If it is, take action */
394 if (is_dot
|| is_dotdot
) {
395 /* For both, remove this token */
398 /* If it was a reference to parent directory, go back one more time */
400 last_token
= strrchr(absolute_path
, '/');
402 /* If there was only one level left, we keep the first '/' */
403 if (last_token
== absolute_path
) {
411 return absolute_path
;
418 char *utils_expand_path(const char *path
)
420 return _utils_expand_path(path
, true);
424 char *utils_expand_path_keep_symlink(const char *path
)
426 return _utils_expand_path(path
, false);
429 * Create a pipe in dst.
432 int utils_create_pipe(int *dst
)
442 PERROR("create pipe");
449 * Create pipe and set CLOEXEC flag to both fd.
451 * Make sure the pipe opened by this function are closed at some point. Use
452 * utils_close_pipe().
455 int utils_create_pipe_cloexec(int *dst
)
463 ret
= utils_create_pipe(dst
);
468 for (i
= 0; i
< 2; i
++) {
469 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
471 PERROR("fcntl pipe cloexec");
481 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
483 * Make sure the pipe opened by this function are closed at some point. Use
484 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
485 * support OSes other than Linux 2.6.23+.
488 int utils_create_pipe_cloexec_nonblock(int *dst
)
496 ret
= utils_create_pipe(dst
);
501 for (i
= 0; i
< 2; i
++) {
502 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
504 PERROR("fcntl pipe cloexec");
508 * Note: we override any flag that could have been
509 * previously set on the fd.
511 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
513 PERROR("fcntl pipe nonblock");
523 * Close both read and write side of the pipe.
526 void utils_close_pipe(int *src
)
534 for (i
= 0; i
< 2; i
++) {
542 PERROR("close pipe");
549 * Create a new string using two strings range.
552 char *utils_strdupdelim(const char *begin
, const char *end
)
556 str
= zmalloc(end
- begin
+ 1);
558 PERROR("zmalloc strdupdelim");
562 memcpy(str
, begin
, end
- begin
);
563 str
[end
- begin
] = '\0';
570 * Set CLOEXEC flag to the give file descriptor.
573 int utils_set_fd_cloexec(int fd
)
582 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
584 PERROR("fcntl cloexec");
593 * Create pid file to the given path and filename.
596 int utils_create_pid_file(pid_t pid
, const char *filepath
)
603 fp
= fopen(filepath
, "w");
605 PERROR("open pid file %s", filepath
);
610 ret
= fprintf(fp
, "%d\n", (int) pid
);
612 PERROR("fprintf pid file");
619 DBG("Pid %d written in file %s", (int) pid
, filepath
);
626 * Create lock file to the given path and filename.
627 * Returns the associated file descriptor, -1 on error.
630 int utils_create_lock_file(const char *filepath
)
638 memset(&lock
, 0, sizeof(lock
));
639 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
642 PERROR("open lock file %s", filepath
);
648 * Attempt to lock the file. If this fails, there is
649 * already a process using the same lock file running
650 * and we should exit.
652 lock
.l_whence
= SEEK_SET
;
653 lock
.l_type
= F_WRLCK
;
655 ret
= fcntl(fd
, F_SETLK
, &lock
);
657 PERROR("fcntl lock file");
658 ERR("Could not get lock file %s, another instance is running.",
661 PERROR("close lock file");
672 * Create directory using the given path and mode.
674 * On success, return 0 else a negative error code.
677 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
680 struct lttng_directory_handle
*handle
;
681 const struct lttng_credentials creds
= {
682 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
683 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
686 handle
= lttng_directory_handle_create(NULL
);
691 ret
= lttng_directory_handle_create_subdirectory_as_user(
693 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
695 lttng_directory_handle_put(handle
);
700 * Recursively create directory using the given path and mode, under the
701 * provided uid and gid.
703 * On success, return 0 else a negative error code.
706 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
709 struct lttng_directory_handle
*handle
;
710 const struct lttng_credentials creds
= {
711 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
712 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
715 handle
= lttng_directory_handle_create(NULL
);
720 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
722 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
724 lttng_directory_handle_put(handle
);
729 * out_stream_path is the output parameter.
731 * Return 0 on success or else a negative value.
734 int utils_stream_file_path(const char *path_name
, const char *file_name
,
735 uint64_t size
, uint64_t count
, const char *suffix
,
736 char *out_stream_path
, size_t stream_path_len
)
739 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
740 const char *path_separator
;
742 if (path_name
&& (path_name
[0] == '\0' ||
743 path_name
[strlen(path_name
) - 1] == '/')) {
746 path_separator
= "/";
749 path_name
= path_name
? : "";
750 suffix
= suffix
? : "";
752 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
754 assert(ret
> 0 && ret
< sizeof(count_str
));
757 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
758 path_name
, path_separator
, file_name
, count_str
,
760 if (ret
< 0 || ret
>= stream_path_len
) {
761 ERR("Truncation occurred while formatting stream path");
770 * Parse a string that represents a size in human readable format. It
771 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
773 * The suffix multiply the integer by:
778 * @param str The string to parse.
779 * @param size Pointer to a uint64_t that will be filled with the
782 * @return 0 on success, -1 on failure.
785 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
794 DBG("utils_parse_size_suffix: received a NULL string.");
799 /* strtoull will accept a negative number, but we don't want to. */
800 if (strchr(str
, '-') != NULL
) {
801 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
806 /* str_end will point to the \0 */
807 str_end
= str
+ strlen(str
);
809 base_size
= strtoull(str
, &num_end
, 0);
811 PERROR("utils_parse_size_suffix strtoull");
816 if (num_end
== str
) {
817 /* strtoull parsed nothing, not good. */
818 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
823 /* Check if a prefix is present. */
841 DBG("utils_parse_size_suffix: invalid suffix.");
846 /* Check for garbage after the valid input. */
847 if (num_end
!= str_end
) {
848 DBG("utils_parse_size_suffix: Garbage after size string.");
853 *size
= base_size
<< shift
;
855 /* Check for overflow */
856 if ((*size
>> shift
) != base_size
) {
857 DBG("utils_parse_size_suffix: oops, overflow detected.");
868 * Parse a string that represents a time in human readable format. It
869 * supports decimal integers suffixed by:
870 * "us" for microsecond,
871 * "ms" for millisecond,
876 * The suffix multiply the integer by:
883 * Note that unit-less numbers are assumed to be microseconds.
885 * @param str The string to parse, assumed to be NULL-terminated.
886 * @param time_us Pointer to a uint64_t that will be filled with the
887 * resulting time in microseconds.
889 * @return 0 on success, -1 on failure.
892 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
896 uint64_t multiplier
= 1;
901 DBG("utils_parse_time_suffix: received a NULL string.");
906 /* strtoull will accept a negative number, but we don't want to. */
907 if (strchr(str
, '-') != NULL
) {
908 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
913 /* str_end will point to the \0 */
914 str_end
= str
+ strlen(str
);
916 base_time
= strtoull(str
, &num_end
, 10);
918 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
923 if (num_end
== str
) {
924 /* strtoull parsed nothing, not good. */
925 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
930 /* Check if a prefix is present. */
936 * Skip the "us" if the string matches the "us" suffix,
937 * otherwise let the check for the end of the string handle
938 * the error reporting.
940 if (*(num_end
+ 1) == 's') {
945 if (*(num_end
+ 1) == 's') {
946 /* Millisecond (ms) */
947 multiplier
= USEC_PER_MSEC
;
952 multiplier
= USEC_PER_MINUTE
;
958 multiplier
= USEC_PER_SEC
;
963 multiplier
= USEC_PER_HOURS
;
969 DBG("utils_parse_time_suffix: invalid suffix.");
974 /* Check for garbage after the valid input. */
975 if (num_end
!= str_end
) {
976 DBG("utils_parse_time_suffix: Garbage after time string.");
981 *time_us
= base_time
* multiplier
;
983 /* Check for overflow */
984 if ((*time_us
/ multiplier
) != base_time
) {
985 DBG("utils_parse_time_suffix: oops, overflow detected.");
996 * fls: returns the position of the most significant bit.
997 * Returns 0 if no bit is set, else returns the position of the most
998 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1000 #if defined(__i386) || defined(__x86_64)
1001 static inline unsigned int fls_u32(uint32_t x
)
1005 asm("bsrl %1,%0\n\t"
1009 : "=r" (r
) : "rm" (x
));
1015 #if defined(__x86_64) && defined(__LP64__)
1017 unsigned int fls_u64(uint64_t x
)
1021 asm("bsrq %1,%0\n\t"
1025 : "=r" (r
) : "rm" (x
));
1032 static __attribute__((unused
))
1033 unsigned int fls_u64(uint64_t x
)
1035 unsigned int r
= 64;
1040 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1044 if (!(x
& 0xFFFF000000000000ULL
)) {
1048 if (!(x
& 0xFF00000000000000ULL
)) {
1052 if (!(x
& 0xF000000000000000ULL
)) {
1056 if (!(x
& 0xC000000000000000ULL
)) {
1060 if (!(x
& 0x8000000000000000ULL
)) {
1069 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1071 unsigned int r
= 32;
1076 if (!(x
& 0xFFFF0000U
)) {
1080 if (!(x
& 0xFF000000U
)) {
1084 if (!(x
& 0xF0000000U
)) {
1088 if (!(x
& 0xC0000000U
)) {
1092 if (!(x
& 0x80000000U
)) {
1101 * Return the minimum order for which x <= (1UL << order).
1102 * Return -1 if x is 0.
1105 int utils_get_count_order_u32(uint32_t x
)
1111 return fls_u32(x
- 1);
1115 * Return the minimum order for which x <= (1UL << order).
1116 * Return -1 if x is 0.
1119 int utils_get_count_order_u64(uint64_t x
)
1125 return fls_u64(x
- 1);
1129 * Obtain the value of LTTNG_HOME environment variable, if exists.
1130 * Otherwise returns the value of HOME.
1133 const char *utils_get_home_dir(void)
1138 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1142 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1147 /* Fallback on the password file entry. */
1148 pwd
= getpwuid(getuid());
1154 DBG3("Home directory is '%s'", val
);
1161 * Get user's home directory. Dynamically allocated, must be freed
1165 char *utils_get_user_home_dir(uid_t uid
)
1168 struct passwd
*result
;
1169 char *home_dir
= NULL
;
1174 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1179 buf
= zmalloc(buflen
);
1184 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1185 if (ret
|| !result
) {
1186 if (ret
== ERANGE
) {
1194 home_dir
= strdup(pwd
.pw_dir
);
1201 * With the given format, fill dst with the time of len maximum siz.
1203 * Return amount of bytes set in the buffer or else 0 on error.
1206 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1210 struct tm
*timeinfo
;
1215 /* Get date and time for session path */
1217 timeinfo
= localtime(&rawtime
);
1218 ret
= strftime(dst
, len
, format
, timeinfo
);
1220 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1228 * Return 0 on success and set *gid to the group_ID matching the passed name.
1229 * Else -1 if it cannot be found or an error occurred.
1232 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1234 static volatile int warn_once
;
1239 struct group
*result
;
1240 struct lttng_dynamic_buffer buffer
;
1242 /* Get the system limit, if it exists. */
1243 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1244 if (sys_len
== -1) {
1247 len
= (size_t) sys_len
;
1250 lttng_dynamic_buffer_init(&buffer
);
1251 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1253 ERR("Failed to allocate group info buffer");
1258 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1259 const size_t new_len
= 2 * buffer
.size
;
1261 /* Buffer is not big enough, increase its size. */
1262 if (new_len
< buffer
.size
) {
1263 ERR("Group info buffer size overflow");
1268 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1270 ERR("Failed to grow group info buffer to %zu bytes",
1278 DBG("Could not find group file entry for group name '%s'",
1281 PERROR("Failed to get group file entry for group name '%s'",
1289 /* Group not found. */
1295 *gid
= result
->gr_gid
;
1299 if (ret
&& warn
&& !warn_once
) {
1300 WARN("No tracing group detected");
1303 lttng_dynamic_buffer_reset(&buffer
);
1308 * Return a newly allocated option string. This string is to be used as the
1309 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1310 * of elements in the long_options array. Returns NULL if the string's
1314 char *utils_generate_optstring(const struct option
*long_options
,
1318 size_t string_len
= opt_count
, str_pos
= 0;
1322 * Compute the necessary string length. One letter per option, two when an
1323 * argument is necessary, and a trailing NULL.
1325 for (i
= 0; i
< opt_count
; i
++) {
1326 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1329 optstring
= zmalloc(string_len
);
1334 for (i
= 0; i
< opt_count
; i
++) {
1335 if (!long_options
[i
].name
) {
1336 /* Got to the trailing NULL element */
1340 if (long_options
[i
].val
!= '\0') {
1341 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1342 if (long_options
[i
].has_arg
) {
1343 optstring
[str_pos
++] = ':';
1353 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1354 * any file. Try to rmdir any empty directory within the hierarchy.
1357 int utils_recursive_rmdir(const char *path
)
1360 struct lttng_directory_handle
*handle
;
1362 handle
= lttng_directory_handle_create(NULL
);
1367 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1369 lttng_directory_handle_put(handle
);
1374 int utils_truncate_stream_file(int fd
, off_t length
)
1379 ret
= ftruncate(fd
, length
);
1381 PERROR("ftruncate");
1384 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1385 if (lseek_ret
< 0) {
1394 static const char *get_man_bin_path(void)
1396 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1399 return env_man_path
;
1402 return DEFAULT_MAN_BIN_PATH
;
1406 int utils_show_help(int section
, const char *page_name
,
1407 const char *help_msg
)
1409 char section_string
[8];
1410 const char *man_bin_path
= get_man_bin_path();
1414 printf("%s", help_msg
);
1418 /* Section integer -> section string */
1419 ret
= sprintf(section_string
, "%d", section
);
1420 assert(ret
> 0 && ret
< 8);
1423 * Execute man pager.
1425 * We provide -M to man here because LTTng-tools can
1426 * be installed outside /usr, in which case its man pages are
1427 * not located in the default /usr/share/man directory.
1429 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1430 section_string
, page_name
, NULL
);
1437 int read_proc_meminfo_field(const char *field
, size_t *value
)
1441 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1443 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1444 if (!proc_meminfo
) {
1445 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1451 * Read the contents of /proc/meminfo line by line to find the right
1454 while (!feof(proc_meminfo
)) {
1455 unsigned long value_kb
;
1457 ret
= fscanf(proc_meminfo
,
1458 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1462 * fscanf() returning EOF can indicate EOF or an error.
1464 if (ferror(proc_meminfo
)) {
1465 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1470 if (ret
== 2 && strcmp(name
, field
) == 0) {
1472 * This number is displayed in kilo-bytes. Return the
1475 *value
= ((size_t) value_kb
) * 1024;
1480 /* Reached the end of the file without finding the right field. */
1484 fclose(proc_meminfo
);
1490 * Returns an estimate of the number of bytes of memory available based on the
1491 * the information in `/proc/meminfo`. The number returned by this function is
1495 int utils_get_memory_available(size_t *value
)
1497 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1501 * Returns the total size of the memory on the system in bytes based on the
1502 * the information in `/proc/meminfo`.
1505 int utils_get_memory_total(size_t *value
)
1507 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1511 int utils_change_working_directory(const char *path
)
1517 DBG("Changing working directory to \"%s\"", path
);
1520 PERROR("Failed to change working directory to \"%s\"", path
);
1524 /* Check for write access */
1525 if (access(path
, W_OK
)) {
1526 if (errno
== EACCES
) {
1528 * Do not treat this as an error since the permission
1529 * might change in the lifetime of the process
1531 DBG("Working directory \"%s\" is not writable", path
);
1533 PERROR("Failed to check if working directory \"%s\" is writable",
1543 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1545 struct passwd p
, *pres
;
1547 enum lttng_error_code ret_val
= LTTNG_OK
;
1551 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1553 buflen
= FALLBACK_USER_BUFLEN
;
1556 buf
= zmalloc(buflen
);
1558 ret_val
= LTTNG_ERR_NOMEM
;
1563 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1570 buf
= zmalloc(buflen
);
1572 ret_val
= LTTNG_ERR_NOMEM
;
1585 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1588 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1589 user_name
, (int64_t) *uid
);
1597 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1600 ret_val
= LTTNG_ERR_NOMEM
;
1608 enum lttng_error_code
utils_group_id_from_name(
1609 const char *group_name
, gid_t
*gid
)
1611 struct group g
, *gres
;
1613 enum lttng_error_code ret_val
= LTTNG_OK
;
1617 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1619 buflen
= FALLBACK_GROUP_BUFLEN
;
1622 buf
= zmalloc(buflen
);
1624 ret_val
= LTTNG_ERR_NOMEM
;
1629 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1636 buf
= zmalloc(buflen
);
1638 ret_val
= LTTNG_ERR_NOMEM
;
1651 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1654 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1655 group_name
, (int64_t) *gid
);
1663 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1666 ret_val
= LTTNG_ERR_NOMEM
;