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"
17 #include <sys/types.h>
25 #include <common/common.h>
26 #include <common/readwrite.h>
27 #include <common/runas.h>
28 #include <common/compat/getenv.h>
29 #include <common/compat/string.h>
30 #include <common/compat/dirent.h>
31 #include <common/compat/directory-handle.h>
32 #include <common/dynamic-buffer.h>
33 #include <common/string-utils/format.h>
34 #include <lttng/constant.h>
40 #define PROC_MEMINFO_PATH "/proc/meminfo"
41 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
42 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
44 /* The length of the longest field of `/proc/meminfo`. */
45 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
47 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
48 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
50 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
53 #define FALLBACK_USER_BUFLEN 16384
54 #define FALLBACK_GROUP_BUFLEN 16384
57 * Return a partial realpath(3) of the path even if the full path does not
58 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
59 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
60 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
61 * point directory does not exist.
63 * Return a newly-allocated string.
66 char *utils_partial_realpath(const char *path
)
68 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
69 const char *next
, *prev
, *end
;
70 char *resolved_path
= NULL
;
78 * Identify the end of the path, we don't want to treat the
79 * last char if it is a '/', we will just keep it on the side
80 * to be added at the end, and return a value coherent with
81 * the path given as argument
83 end
= path
+ strlen(path
);
84 if (*(end
-1) == '/') {
88 /* Initiate the values of the pointers before looping */
91 /* Only to ensure try_path is not NULL to enter the while */
92 try_path
= (char *)next
;
94 /* Resolve the canonical path of the first part of the path */
95 while (try_path
!= NULL
&& next
!= end
) {
96 char *try_path_buf
= NULL
;
99 * If there is not any '/' left, we want to try with
102 next
= strpbrk(next
+ 1, "/");
107 /* Cut the part we will be trying to resolve */
108 cut_path
= lttng_strndup(path
, next
- path
);
109 if (cut_path
== NULL
) {
110 PERROR("lttng_strndup");
114 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
120 /* Try to resolve this part */
121 try_path
= realpath((char *) cut_path
, try_path_buf
);
122 if (try_path
== NULL
) {
125 * There was an error, we just want to be assured it
126 * is linked to an unexistent directory, if it's another
127 * reason, we spawn an error
131 /* Ignore the error */
134 PERROR("realpath (partial_realpath)");
139 /* Save the place we are before trying the next step */
142 try_path_prev
= try_path
;
146 /* Free the allocated memory */
151 /* Allocate memory for the resolved path. */
152 resolved_path
= zmalloc(LTTNG_PATH_MAX
);
153 if (resolved_path
== NULL
) {
154 PERROR("zmalloc resolved path");
159 * If we were able to solve at least partially the path, we can concatenate
160 * what worked and what didn't work
162 if (try_path_prev
!= NULL
) {
163 /* If we risk to concatenate two '/', we remove one of them */
164 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
165 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
169 * Duplicate the memory used by prev in case resolved_path and
170 * path are pointers for the same memory space
172 cut_path
= strdup(prev
);
173 if (cut_path
== NULL
) {
178 /* Concatenate the strings */
179 snprintf(resolved_path
, LTTNG_PATH_MAX
, "%s%s",
180 try_path_prev
, cut_path
);
182 /* Free the allocated memory */
186 try_path_prev
= NULL
;
188 * Else, we just copy the path in our resolved_path to
192 strncpy(resolved_path
, path
, LTTNG_PATH_MAX
);
195 /* Then we return the 'partially' resolved path */
196 return resolved_path
;
202 if (try_path_prev
!= try_path
) {
209 int expand_double_slashes_dot_and_dotdot(char *path
)
211 size_t expanded_path_len
, path_len
;
212 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
214 path_len
= strlen(path
);
215 path_last_char
= &path
[path_len
];
221 expanded_path_len
= 0;
223 /* We iterate over the provided path to expand the "//", "../" and "./" */
224 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
225 /* Find the next forward slash. */
226 size_t curr_token_len
;
228 if (curr_char
== path_last_char
) {
233 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
234 if (next_slash
== NULL
) {
235 /* Reached the end of the provided path. */
236 next_slash
= path_last_char
;
239 /* Compute how long is the previous token. */
240 curr_token_len
= next_slash
- curr_char
;
241 switch(curr_token_len
) {
244 * The pointer has not move meaning that curr_char is
245 * pointing to a slash. It that case there is no token
246 * to copy, so continue the iteration to find the next
252 * The pointer moved 1 character. Check if that
253 * character is a dot ('.'), if it is: omit it, else
254 * copy the token to the normalized path.
256 if (curr_char
[0] == '.') {
262 * The pointer moved 2 characters. Check if these
263 * characters are double dots ('..'). If that is the
264 * case, we need to remove the last token of the
267 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
269 * Find the previous path component by
270 * using the memrchr function to find the
271 * previous forward slash and substract that
272 * len to the resulting path.
274 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
276 * If prev_slash is NULL, we reached the
277 * beginning of the path. We can't go back any
280 if (prev_slash
!= NULL
) {
281 expanded_path_len
= prev_slash
- path
;
291 * Copy the current token which is neither a '.' nor a '..'.
293 path
[expanded_path_len
++] = '/';
294 memmove(&path
[expanded_path_len
], curr_char
, curr_token_len
);
295 expanded_path_len
+= curr_token_len
;
298 if (expanded_path_len
== 0) {
299 path
[expanded_path_len
++] = '/';
302 path
[expanded_path_len
] = '\0';
309 * Make a full resolution of the given path even if it doesn't exist.
310 * This function uses the utils_partial_realpath function to resolve
311 * symlinks and relatives paths at the start of the string, and
312 * implements functionnalities to resolve the './' and '../' strings
313 * in the middle of a path. This function is only necessary because
314 * realpath(3) does not accept to resolve unexistent paths.
315 * The returned string was allocated in the function, it is thus of
316 * the responsibility of the caller to free this memory.
319 char *_utils_expand_path(const char *path
, bool keep_symlink
)
322 char *absolute_path
= NULL
;
324 bool is_dot
, is_dotdot
;
331 /* Allocate memory for the absolute_path */
332 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
333 if (absolute_path
== NULL
) {
334 PERROR("zmalloc expand path");
338 if (path
[0] == '/') {
339 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
341 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
346 * This is a relative path. We need to get the present working
347 * directory and start the path walk from there.
349 char current_working_dir
[LTTNG_PATH_MAX
];
352 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
357 * Get the number of character in the CWD and allocate an array
358 * to can hold it and the path provided by the caller.
360 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
361 current_working_dir
, path
);
362 if (ret
>= LTTNG_PATH_MAX
) {
363 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
364 current_working_dir
, path
, LTTNG_PATH_MAX
);
370 /* Resolve partially our path */
371 char *new_absolute_path
= utils_partial_realpath(absolute_path
);
372 if (!new_absolute_path
) {
377 absolute_path
= new_absolute_path
;
380 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
385 /* Identify the last token */
386 last_token
= strrchr(absolute_path
, '/');
388 /* Verify that this token is not a relative path */
389 is_dotdot
= (strcmp(last_token
, "/..") == 0);
390 is_dot
= (strcmp(last_token
, "/.") == 0);
392 /* If it is, take action */
393 if (is_dot
|| is_dotdot
) {
394 /* For both, remove this token */
397 /* If it was a reference to parent directory, go back one more time */
399 last_token
= strrchr(absolute_path
, '/');
401 /* If there was only one level left, we keep the first '/' */
402 if (last_token
== absolute_path
) {
410 return absolute_path
;
417 char *utils_expand_path(const char *path
)
419 return _utils_expand_path(path
, true);
423 char *utils_expand_path_keep_symlink(const char *path
)
425 return _utils_expand_path(path
, false);
428 * Create a pipe in dst.
431 int utils_create_pipe(int *dst
)
441 PERROR("create pipe");
448 * Create pipe and set CLOEXEC flag to both fd.
450 * Make sure the pipe opened by this function are closed at some point. Use
451 * utils_close_pipe().
454 int utils_create_pipe_cloexec(int *dst
)
462 ret
= utils_create_pipe(dst
);
467 for (i
= 0; i
< 2; i
++) {
468 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
470 PERROR("fcntl pipe cloexec");
480 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
482 * Make sure the pipe opened by this function are closed at some point. Use
483 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
484 * support OSes other than Linux 2.6.23+.
487 int utils_create_pipe_cloexec_nonblock(int *dst
)
495 ret
= utils_create_pipe(dst
);
500 for (i
= 0; i
< 2; i
++) {
501 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
503 PERROR("fcntl pipe cloexec");
507 * Note: we override any flag that could have been
508 * previously set on the fd.
510 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
512 PERROR("fcntl pipe nonblock");
522 * Close both read and write side of the pipe.
525 void utils_close_pipe(int *src
)
533 for (i
= 0; i
< 2; i
++) {
541 PERROR("close pipe");
548 * Create a new string using two strings range.
551 char *utils_strdupdelim(const char *begin
, const char *end
)
555 str
= zmalloc(end
- begin
+ 1);
557 PERROR("zmalloc strdupdelim");
561 memcpy(str
, begin
, end
- begin
);
562 str
[end
- begin
] = '\0';
569 * Set CLOEXEC flag to the give file descriptor.
572 int utils_set_fd_cloexec(int fd
)
581 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
583 PERROR("fcntl cloexec");
592 * Create pid file to the given path and filename.
595 int utils_create_pid_file(pid_t pid
, const char *filepath
)
600 LTTNG_ASSERT(filepath
);
602 fp
= fopen(filepath
, "w");
604 PERROR("open pid file %s", filepath
);
609 ret
= fprintf(fp
, "%d\n", (int) pid
);
611 PERROR("fprintf pid file");
618 DBG("Pid %d written in file %s", (int) pid
, filepath
);
625 * Create lock file to the given path and filename.
626 * Returns the associated file descriptor, -1 on error.
629 int utils_create_lock_file(const char *filepath
)
635 LTTNG_ASSERT(filepath
);
637 memset(&lock
, 0, sizeof(lock
));
638 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
641 PERROR("open lock file %s", filepath
);
647 * Attempt to lock the file. If this fails, there is
648 * already a process using the same lock file running
649 * and we should exit.
651 lock
.l_whence
= SEEK_SET
;
652 lock
.l_type
= F_WRLCK
;
654 ret
= fcntl(fd
, F_SETLK
, &lock
);
656 PERROR("fcntl lock file");
657 ERR("Could not get lock file %s, another instance is running.",
660 PERROR("close lock file");
671 * Create directory using the given path and mode.
673 * On success, return 0 else a negative error code.
676 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
679 struct lttng_directory_handle
*handle
;
680 const struct lttng_credentials creds
= {
681 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
682 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
685 handle
= lttng_directory_handle_create(NULL
);
690 ret
= lttng_directory_handle_create_subdirectory_as_user(
692 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
694 lttng_directory_handle_put(handle
);
699 * Recursively create directory using the given path and mode, under the
700 * provided uid and gid.
702 * On success, return 0 else a negative error code.
705 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
708 struct lttng_directory_handle
*handle
;
709 const struct lttng_credentials creds
= {
710 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
711 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
714 handle
= lttng_directory_handle_create(NULL
);
719 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
721 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
723 lttng_directory_handle_put(handle
);
728 * out_stream_path is the output parameter.
730 * Return 0 on success or else a negative value.
733 int utils_stream_file_path(const char *path_name
, const char *file_name
,
734 uint64_t size
, uint64_t count
, const char *suffix
,
735 char *out_stream_path
, size_t stream_path_len
)
738 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
739 const char *path_separator
;
741 if (path_name
&& (path_name
[0] == '\0' ||
742 path_name
[strlen(path_name
) - 1] == '/')) {
745 path_separator
= "/";
748 path_name
= path_name
? : "";
749 suffix
= suffix
? : "";
751 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
753 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
756 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
757 path_name
, path_separator
, file_name
, count_str
,
759 if (ret
< 0 || ret
>= stream_path_len
) {
760 ERR("Truncation occurred while formatting stream path");
769 * Parse a string that represents a size in human readable format. It
770 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
772 * The suffix multiply the integer by:
777 * @param str The string to parse.
778 * @param size Pointer to a uint64_t that will be filled with the
781 * @return 0 on success, -1 on failure.
784 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
793 DBG("utils_parse_size_suffix: received a NULL string.");
798 /* strtoull will accept a negative number, but we don't want to. */
799 if (strchr(str
, '-') != NULL
) {
800 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
805 /* str_end will point to the \0 */
806 str_end
= str
+ strlen(str
);
808 base_size
= strtoull(str
, &num_end
, 0);
810 PERROR("utils_parse_size_suffix strtoull");
815 if (num_end
== str
) {
816 /* strtoull parsed nothing, not good. */
817 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
822 /* Check if a prefix is present. */
840 DBG("utils_parse_size_suffix: invalid suffix.");
845 /* Check for garbage after the valid input. */
846 if (num_end
!= str_end
) {
847 DBG("utils_parse_size_suffix: Garbage after size string.");
852 *size
= base_size
<< shift
;
854 /* Check for overflow */
855 if ((*size
>> shift
) != base_size
) {
856 DBG("utils_parse_size_suffix: oops, overflow detected.");
867 * Parse a string that represents a time in human readable format. It
868 * supports decimal integers suffixed by:
869 * "us" for microsecond,
870 * "ms" for millisecond,
875 * The suffix multiply the integer by:
882 * Note that unit-less numbers are assumed to be microseconds.
884 * @param str The string to parse, assumed to be NULL-terminated.
885 * @param time_us Pointer to a uint64_t that will be filled with the
886 * resulting time in microseconds.
888 * @return 0 on success, -1 on failure.
891 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
895 uint64_t multiplier
= 1;
900 DBG("utils_parse_time_suffix: received a NULL string.");
905 /* strtoull will accept a negative number, but we don't want to. */
906 if (strchr(str
, '-') != NULL
) {
907 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
912 /* str_end will point to the \0 */
913 str_end
= str
+ strlen(str
);
915 base_time
= strtoull(str
, &num_end
, 10);
917 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
922 if (num_end
== str
) {
923 /* strtoull parsed nothing, not good. */
924 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
929 /* Check if a prefix is present. */
935 * Skip the "us" if the string matches the "us" suffix,
936 * otherwise let the check for the end of the string handle
937 * the error reporting.
939 if (*(num_end
+ 1) == 's') {
944 if (*(num_end
+ 1) == 's') {
945 /* Millisecond (ms) */
946 multiplier
= USEC_PER_MSEC
;
951 multiplier
= USEC_PER_MINUTE
;
957 multiplier
= USEC_PER_SEC
;
962 multiplier
= USEC_PER_HOURS
;
968 DBG("utils_parse_time_suffix: invalid suffix.");
973 /* Check for garbage after the valid input. */
974 if (num_end
!= str_end
) {
975 DBG("utils_parse_time_suffix: Garbage after time string.");
980 *time_us
= base_time
* multiplier
;
982 /* Check for overflow */
983 if ((*time_us
/ multiplier
) != base_time
) {
984 DBG("utils_parse_time_suffix: oops, overflow detected.");
995 * fls: returns the position of the most significant bit.
996 * Returns 0 if no bit is set, else returns the position of the most
997 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
999 #if defined(__i386) || defined(__x86_64)
1000 static inline unsigned int fls_u32(uint32_t x
)
1004 asm("bsrl %1,%0\n\t"
1008 : "=r" (r
) : "rm" (x
));
1014 #if defined(__x86_64) && defined(__LP64__)
1016 unsigned int fls_u64(uint64_t x
)
1020 asm("bsrq %1,%0\n\t"
1024 : "=r" (r
) : "rm" (x
));
1031 static __attribute__((unused
))
1032 unsigned int fls_u64(uint64_t x
)
1034 unsigned int r
= 64;
1039 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1043 if (!(x
& 0xFFFF000000000000ULL
)) {
1047 if (!(x
& 0xFF00000000000000ULL
)) {
1051 if (!(x
& 0xF000000000000000ULL
)) {
1055 if (!(x
& 0xC000000000000000ULL
)) {
1059 if (!(x
& 0x8000000000000000ULL
)) {
1068 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1070 unsigned int r
= 32;
1075 if (!(x
& 0xFFFF0000U
)) {
1079 if (!(x
& 0xFF000000U
)) {
1083 if (!(x
& 0xF0000000U
)) {
1087 if (!(x
& 0xC0000000U
)) {
1091 if (!(x
& 0x80000000U
)) {
1100 * Return the minimum order for which x <= (1UL << order).
1101 * Return -1 if x is 0.
1104 int utils_get_count_order_u32(uint32_t x
)
1110 return fls_u32(x
- 1);
1114 * Return the minimum order for which x <= (1UL << order).
1115 * Return -1 if x is 0.
1118 int utils_get_count_order_u64(uint64_t x
)
1124 return fls_u64(x
- 1);
1128 * Obtain the value of LTTNG_HOME environment variable, if exists.
1129 * Otherwise returns the value of HOME.
1132 const char *utils_get_home_dir(void)
1137 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1141 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1146 /* Fallback on the password file entry. */
1147 pwd
= getpwuid(getuid());
1153 DBG3("Home directory is '%s'", val
);
1160 * Get user's home directory. Dynamically allocated, must be freed
1164 char *utils_get_user_home_dir(uid_t uid
)
1167 struct passwd
*result
;
1168 char *home_dir
= NULL
;
1173 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1178 buf
= zmalloc(buflen
);
1183 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1184 if (ret
|| !result
) {
1185 if (ret
== ERANGE
) {
1193 home_dir
= strdup(pwd
.pw_dir
);
1200 * With the given format, fill dst with the time of len maximum siz.
1202 * Return amount of bytes set in the buffer or else 0 on error.
1205 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1209 struct tm
*timeinfo
;
1211 LTTNG_ASSERT(format
);
1214 /* Get date and time for session path */
1216 timeinfo
= localtime(&rawtime
);
1217 ret
= strftime(dst
, len
, format
, timeinfo
);
1219 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1227 * Return 0 on success and set *gid to the group_ID matching the passed name.
1228 * Else -1 if it cannot be found or an error occurred.
1231 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1233 static volatile int warn_once
;
1238 struct group
*result
;
1239 struct lttng_dynamic_buffer buffer
;
1241 /* Get the system limit, if it exists. */
1242 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1243 if (sys_len
== -1) {
1246 len
= (size_t) sys_len
;
1249 lttng_dynamic_buffer_init(&buffer
);
1250 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1252 ERR("Failed to allocate group info buffer");
1257 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1258 const size_t new_len
= 2 * buffer
.size
;
1260 /* Buffer is not big enough, increase its size. */
1261 if (new_len
< buffer
.size
) {
1262 ERR("Group info buffer size overflow");
1267 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1269 ERR("Failed to grow group info buffer to %zu bytes",
1277 DBG("Could not find group file entry for group name '%s'",
1280 PERROR("Failed to get group file entry for group name '%s'",
1288 /* Group not found. */
1294 *gid
= result
->gr_gid
;
1298 if (ret
&& warn
&& !warn_once
) {
1299 WARN("No tracing group detected");
1302 lttng_dynamic_buffer_reset(&buffer
);
1307 * Return a newly allocated option string. This string is to be used as the
1308 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1309 * of elements in the long_options array. Returns NULL if the string's
1313 char *utils_generate_optstring(const struct option
*long_options
,
1317 size_t string_len
= opt_count
, str_pos
= 0;
1321 * Compute the necessary string length. One letter per option, two when an
1322 * argument is necessary, and a trailing NULL.
1324 for (i
= 0; i
< opt_count
; i
++) {
1325 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1328 optstring
= zmalloc(string_len
);
1333 for (i
= 0; i
< opt_count
; i
++) {
1334 if (!long_options
[i
].name
) {
1335 /* Got to the trailing NULL element */
1339 if (long_options
[i
].val
!= '\0') {
1340 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1341 if (long_options
[i
].has_arg
) {
1342 optstring
[str_pos
++] = ':';
1352 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1353 * any file. Try to rmdir any empty directory within the hierarchy.
1356 int utils_recursive_rmdir(const char *path
)
1359 struct lttng_directory_handle
*handle
;
1361 handle
= lttng_directory_handle_create(NULL
);
1366 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1368 lttng_directory_handle_put(handle
);
1373 int utils_truncate_stream_file(int fd
, off_t length
)
1378 ret
= ftruncate(fd
, length
);
1380 PERROR("ftruncate");
1383 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1384 if (lseek_ret
< 0) {
1393 static const char *get_man_bin_path(void)
1395 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1398 return env_man_path
;
1401 return DEFAULT_MAN_BIN_PATH
;
1405 int utils_show_help(int section
, const char *page_name
,
1406 const char *help_msg
)
1408 char section_string
[8];
1409 const char *man_bin_path
= get_man_bin_path();
1413 printf("%s", help_msg
);
1417 /* Section integer -> section string */
1418 ret
= sprintf(section_string
, "%d", section
);
1419 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1422 * Execute man pager.
1424 * We provide -M to man here because LTTng-tools can
1425 * be installed outside /usr, in which case its man pages are
1426 * not located in the default /usr/share/man directory.
1428 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1429 section_string
, page_name
, NULL
);
1436 int read_proc_meminfo_field(const char *field
, size_t *value
)
1440 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1442 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1443 if (!proc_meminfo
) {
1444 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1450 * Read the contents of /proc/meminfo line by line to find the right
1453 while (!feof(proc_meminfo
)) {
1454 unsigned long value_kb
;
1456 ret
= fscanf(proc_meminfo
,
1457 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1461 * fscanf() returning EOF can indicate EOF or an error.
1463 if (ferror(proc_meminfo
)) {
1464 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1469 if (ret
== 2 && strcmp(name
, field
) == 0) {
1471 * This number is displayed in kilo-bytes. Return the
1474 *value
= ((size_t) value_kb
) * 1024;
1479 /* Reached the end of the file without finding the right field. */
1483 fclose(proc_meminfo
);
1489 * Returns an estimate of the number of bytes of memory available based on the
1490 * the information in `/proc/meminfo`. The number returned by this function is
1494 int utils_get_memory_available(size_t *value
)
1496 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1500 * Returns the total size of the memory on the system in bytes based on the
1501 * the information in `/proc/meminfo`.
1504 int utils_get_memory_total(size_t *value
)
1506 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1510 int utils_change_working_directory(const char *path
)
1516 DBG("Changing working directory to \"%s\"", path
);
1519 PERROR("Failed to change working directory to \"%s\"", path
);
1523 /* Check for write access */
1524 if (access(path
, W_OK
)) {
1525 if (errno
== EACCES
) {
1527 * Do not treat this as an error since the permission
1528 * might change in the lifetime of the process
1530 DBG("Working directory \"%s\" is not writable", path
);
1532 PERROR("Failed to check if working directory \"%s\" is writable",
1542 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1544 struct passwd p
, *pres
;
1546 enum lttng_error_code ret_val
= LTTNG_OK
;
1550 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1552 buflen
= FALLBACK_USER_BUFLEN
;
1555 buf
= zmalloc(buflen
);
1557 ret_val
= LTTNG_ERR_NOMEM
;
1562 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1569 buf
= zmalloc(buflen
);
1571 ret_val
= LTTNG_ERR_NOMEM
;
1584 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1587 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1588 user_name
, (int64_t) *uid
);
1596 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1599 ret_val
= LTTNG_ERR_NOMEM
;
1607 enum lttng_error_code
utils_group_id_from_name(
1608 const char *group_name
, gid_t
*gid
)
1610 struct group g
, *gres
;
1612 enum lttng_error_code ret_val
= LTTNG_OK
;
1616 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1618 buflen
= FALLBACK_GROUP_BUFLEN
;
1621 buf
= zmalloc(buflen
);
1623 ret_val
= LTTNG_ERR_NOMEM
;
1628 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1635 buf
= zmalloc(buflen
);
1637 ret_val
= LTTNG_ERR_NOMEM
;
1650 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1653 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1654 group_name
, (int64_t) *gid
);
1662 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1665 ret_val
= LTTNG_ERR_NOMEM
;
1673 int utils_parse_unsigned_long_long(const char *str
,
1674 unsigned long long *value
)
1680 LTTNG_ASSERT(value
);
1683 *value
= strtoull(str
, &endptr
, 10);
1685 /* Conversion failed. Out of range? */
1687 /* Don't print an error; allow the caller to log a better error. */
1688 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1694 /* Not the end of the string or empty string. */
1695 if (*endptr
|| endptr
== str
) {
1696 DBG("Failed to parse string as unsigned long long number: string = '%s'",