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
= (char *) 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
= (char *) 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
= (const char *) 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
= (const char *) 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
= (char *) 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
;
416 char *utils_expand_path(const char *path
)
418 return _utils_expand_path(path
, true);
421 char *utils_expand_path_keep_symlink(const char *path
)
423 return _utils_expand_path(path
, false);
426 * Create a pipe in dst.
428 int utils_create_pipe(int *dst
)
438 PERROR("create pipe");
445 * Create pipe and set CLOEXEC flag to both fd.
447 * Make sure the pipe opened by this function are closed at some point. Use
448 * utils_close_pipe().
450 int utils_create_pipe_cloexec(int *dst
)
458 ret
= utils_create_pipe(dst
);
463 for (i
= 0; i
< 2; i
++) {
464 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
466 PERROR("fcntl pipe cloexec");
476 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
478 * Make sure the pipe opened by this function are closed at some point. Use
479 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
480 * support OSes other than Linux 2.6.23+.
482 int utils_create_pipe_cloexec_nonblock(int *dst
)
490 ret
= utils_create_pipe(dst
);
495 for (i
= 0; i
< 2; i
++) {
496 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
498 PERROR("fcntl pipe cloexec");
502 * Note: we override any flag that could have been
503 * previously set on the fd.
505 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
507 PERROR("fcntl pipe nonblock");
517 * Close both read and write side of the pipe.
519 void utils_close_pipe(int *src
)
527 for (i
= 0; i
< 2; i
++) {
535 PERROR("close pipe");
542 * Create a new string using two strings range.
544 char *utils_strdupdelim(const char *begin
, const char *end
)
548 str
= (char *) zmalloc(end
- begin
+ 1);
550 PERROR("zmalloc strdupdelim");
554 memcpy(str
, begin
, end
- begin
);
555 str
[end
- begin
] = '\0';
562 * Set CLOEXEC flag to the give file descriptor.
564 int utils_set_fd_cloexec(int fd
)
573 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
575 PERROR("fcntl cloexec");
584 * Create pid file to the given path and filename.
586 int utils_create_pid_file(pid_t pid
, const char *filepath
)
591 LTTNG_ASSERT(filepath
);
593 fp
= fopen(filepath
, "w");
595 PERROR("open pid file %s", filepath
);
600 ret
= fprintf(fp
, "%d\n", (int) pid
);
602 PERROR("fprintf pid file");
609 DBG("Pid %d written in file %s", (int) pid
, filepath
);
616 * Create lock file to the given path and filename.
617 * Returns the associated file descriptor, -1 on error.
619 int utils_create_lock_file(const char *filepath
)
625 LTTNG_ASSERT(filepath
);
627 memset(&lock
, 0, sizeof(lock
));
628 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
631 PERROR("open lock file %s", filepath
);
637 * Attempt to lock the file. If this fails, there is
638 * already a process using the same lock file running
639 * and we should exit.
641 lock
.l_whence
= SEEK_SET
;
642 lock
.l_type
= F_WRLCK
;
644 ret
= fcntl(fd
, F_SETLK
, &lock
);
646 PERROR("fcntl lock file");
647 ERR("Could not get lock file %s, another instance is running.",
650 PERROR("close lock file");
661 * Create directory using the given path and mode.
663 * On success, return 0 else a negative error code.
665 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
668 struct lttng_directory_handle
*handle
;
669 const struct lttng_credentials creds
= {
670 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
671 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
674 handle
= lttng_directory_handle_create(NULL
);
679 ret
= lttng_directory_handle_create_subdirectory_as_user(
681 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
683 lttng_directory_handle_put(handle
);
688 * Recursively create directory using the given path and mode, under the
689 * provided uid and gid.
691 * On success, return 0 else a negative error code.
693 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
696 struct lttng_directory_handle
*handle
;
697 const struct lttng_credentials creds
= {
698 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
699 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
702 handle
= lttng_directory_handle_create(NULL
);
707 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
709 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
711 lttng_directory_handle_put(handle
);
716 * out_stream_path is the output parameter.
718 * Return 0 on success or else a negative value.
720 int utils_stream_file_path(const char *path_name
, const char *file_name
,
721 uint64_t size
, uint64_t count
, const char *suffix
,
722 char *out_stream_path
, size_t stream_path_len
)
725 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
726 const char *path_separator
;
728 if (path_name
&& (path_name
[0] == '\0' ||
729 path_name
[strlen(path_name
) - 1] == '/')) {
732 path_separator
= "/";
735 path_name
= path_name
? : "";
736 suffix
= suffix
? : "";
738 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
740 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
743 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
744 path_name
, path_separator
, file_name
, count_str
,
746 if (ret
< 0 || ret
>= stream_path_len
) {
747 ERR("Truncation occurred while formatting stream path");
756 * Parse a string that represents a size in human readable format. It
757 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
759 * The suffix multiply the integer by:
764 * @param str The string to parse.
765 * @param size Pointer to a uint64_t that will be filled with the
768 * @return 0 on success, -1 on failure.
770 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
779 DBG("utils_parse_size_suffix: received a NULL string.");
784 /* strtoull will accept a negative number, but we don't want to. */
785 if (strchr(str
, '-') != NULL
) {
786 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
791 /* str_end will point to the \0 */
792 str_end
= str
+ strlen(str
);
794 base_size
= strtoull(str
, &num_end
, 0);
796 PERROR("utils_parse_size_suffix strtoull");
801 if (num_end
== str
) {
802 /* strtoull parsed nothing, not good. */
803 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
808 /* Check if a prefix is present. */
826 DBG("utils_parse_size_suffix: invalid suffix.");
831 /* Check for garbage after the valid input. */
832 if (num_end
!= str_end
) {
833 DBG("utils_parse_size_suffix: Garbage after size string.");
838 *size
= base_size
<< shift
;
840 /* Check for overflow */
841 if ((*size
>> shift
) != base_size
) {
842 DBG("utils_parse_size_suffix: oops, overflow detected.");
853 * Parse a string that represents a time in human readable format. It
854 * supports decimal integers suffixed by:
855 * "us" for microsecond,
856 * "ms" for millisecond,
861 * The suffix multiply the integer by:
868 * Note that unit-less numbers are assumed to be microseconds.
870 * @param str The string to parse, assumed to be NULL-terminated.
871 * @param time_us Pointer to a uint64_t that will be filled with the
872 * resulting time in microseconds.
874 * @return 0 on success, -1 on failure.
876 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
880 uint64_t multiplier
= 1;
885 DBG("utils_parse_time_suffix: received a NULL string.");
890 /* strtoull will accept a negative number, but we don't want to. */
891 if (strchr(str
, '-') != NULL
) {
892 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
897 /* str_end will point to the \0 */
898 str_end
= str
+ strlen(str
);
900 base_time
= strtoull(str
, &num_end
, 10);
902 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
907 if (num_end
== str
) {
908 /* strtoull parsed nothing, not good. */
909 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
914 /* Check if a prefix is present. */
920 * Skip the "us" if the string matches the "us" suffix,
921 * otherwise let the check for the end of the string handle
922 * the error reporting.
924 if (*(num_end
+ 1) == 's') {
929 if (*(num_end
+ 1) == 's') {
930 /* Millisecond (ms) */
931 multiplier
= USEC_PER_MSEC
;
936 multiplier
= USEC_PER_MINUTE
;
942 multiplier
= USEC_PER_SEC
;
947 multiplier
= USEC_PER_HOURS
;
953 DBG("utils_parse_time_suffix: invalid suffix.");
958 /* Check for garbage after the valid input. */
959 if (num_end
!= str_end
) {
960 DBG("utils_parse_time_suffix: Garbage after time string.");
965 *time_us
= base_time
* multiplier
;
967 /* Check for overflow */
968 if ((*time_us
/ multiplier
) != base_time
) {
969 DBG("utils_parse_time_suffix: oops, overflow detected.");
980 * fls: returns the position of the most significant bit.
981 * Returns 0 if no bit is set, else returns the position of the most
982 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
984 #if defined(__i386) || defined(__x86_64)
985 static inline unsigned int fls_u32(uint32_t x
)
993 : "=r" (r
) : "rm" (x
));
999 #if defined(__x86_64) && defined(__LP64__)
1001 unsigned int fls_u64(uint64_t x
)
1005 asm("bsrq %1,%0\n\t"
1009 : "=r" (r
) : "rm" (x
));
1016 static __attribute__((unused
))
1017 unsigned int fls_u64(uint64_t x
)
1019 unsigned int r
= 64;
1024 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1028 if (!(x
& 0xFFFF000000000000ULL
)) {
1032 if (!(x
& 0xFF00000000000000ULL
)) {
1036 if (!(x
& 0xF000000000000000ULL
)) {
1040 if (!(x
& 0xC000000000000000ULL
)) {
1044 if (!(x
& 0x8000000000000000ULL
)) {
1053 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1055 unsigned int r
= 32;
1060 if (!(x
& 0xFFFF0000U
)) {
1064 if (!(x
& 0xFF000000U
)) {
1068 if (!(x
& 0xF0000000U
)) {
1072 if (!(x
& 0xC0000000U
)) {
1076 if (!(x
& 0x80000000U
)) {
1085 * Return the minimum order for which x <= (1UL << order).
1086 * Return -1 if x is 0.
1088 int utils_get_count_order_u32(uint32_t x
)
1094 return fls_u32(x
- 1);
1098 * Return the minimum order for which x <= (1UL << order).
1099 * Return -1 if x is 0.
1101 int utils_get_count_order_u64(uint64_t x
)
1107 return fls_u64(x
- 1);
1111 * Obtain the value of LTTNG_HOME environment variable, if exists.
1112 * Otherwise returns the value of HOME.
1114 const char *utils_get_home_dir(void)
1119 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1123 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1128 /* Fallback on the password file entry. */
1129 pwd
= getpwuid(getuid());
1135 DBG3("Home directory is '%s'", val
);
1142 * Get user's home directory. Dynamically allocated, must be freed
1145 char *utils_get_user_home_dir(uid_t uid
)
1148 struct passwd
*result
;
1149 char *home_dir
= NULL
;
1154 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1159 buf
= (char *) zmalloc(buflen
);
1164 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1165 if (ret
|| !result
) {
1166 if (ret
== ERANGE
) {
1174 home_dir
= strdup(pwd
.pw_dir
);
1181 * With the given format, fill dst with the time of len maximum siz.
1183 * Return amount of bytes set in the buffer or else 0 on error.
1185 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1189 struct tm
*timeinfo
;
1191 LTTNG_ASSERT(format
);
1194 /* Get date and time for session path */
1196 timeinfo
= localtime(&rawtime
);
1198 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
1199 ret
= strftime(dst
, len
, format
, timeinfo
);
1202 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1210 * Return 0 on success and set *gid to the group_ID matching the passed name.
1211 * Else -1 if it cannot be found or an error occurred.
1213 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1215 static volatile int warn_once
;
1220 struct group
*result
;
1221 struct lttng_dynamic_buffer buffer
;
1223 /* Get the system limit, if it exists. */
1224 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1225 if (sys_len
== -1) {
1228 len
= (size_t) sys_len
;
1231 lttng_dynamic_buffer_init(&buffer
);
1232 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1234 ERR("Failed to allocate group info buffer");
1239 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1240 const size_t new_len
= 2 * buffer
.size
;
1242 /* Buffer is not big enough, increase its size. */
1243 if (new_len
< buffer
.size
) {
1244 ERR("Group info buffer size overflow");
1249 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1251 ERR("Failed to grow group info buffer to %zu bytes",
1259 DBG("Could not find group file entry for group name '%s'",
1262 PERROR("Failed to get group file entry for group name '%s'",
1270 /* Group not found. */
1276 *gid
= result
->gr_gid
;
1280 if (ret
&& warn
&& !warn_once
) {
1281 WARN("No tracing group detected");
1284 lttng_dynamic_buffer_reset(&buffer
);
1289 * Return a newly allocated option string. This string is to be used as the
1290 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1291 * of elements in the long_options array. Returns NULL if the string's
1294 char *utils_generate_optstring(const struct option
*long_options
,
1298 size_t string_len
= opt_count
, str_pos
= 0;
1302 * Compute the necessary string length. One letter per option, two when an
1303 * argument is necessary, and a trailing NULL.
1305 for (i
= 0; i
< opt_count
; i
++) {
1306 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1309 optstring
= (char *) zmalloc(string_len
);
1314 for (i
= 0; i
< opt_count
; i
++) {
1315 if (!long_options
[i
].name
) {
1316 /* Got to the trailing NULL element */
1320 if (long_options
[i
].val
!= '\0') {
1321 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1322 if (long_options
[i
].has_arg
) {
1323 optstring
[str_pos
++] = ':';
1333 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1334 * any file. Try to rmdir any empty directory within the hierarchy.
1336 int utils_recursive_rmdir(const char *path
)
1339 struct lttng_directory_handle
*handle
;
1341 handle
= lttng_directory_handle_create(NULL
);
1346 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1348 lttng_directory_handle_put(handle
);
1352 int utils_truncate_stream_file(int fd
, off_t length
)
1357 ret
= ftruncate(fd
, length
);
1359 PERROR("ftruncate");
1362 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1363 if (lseek_ret
< 0) {
1372 static const char *get_man_bin_path(void)
1374 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1377 return env_man_path
;
1380 return DEFAULT_MAN_BIN_PATH
;
1383 int utils_show_help(int section
, const char *page_name
,
1384 const char *help_msg
)
1386 char section_string
[8];
1387 const char *man_bin_path
= get_man_bin_path();
1391 printf("%s", help_msg
);
1395 /* Section integer -> section string */
1396 ret
= sprintf(section_string
, "%d", section
);
1397 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1400 * Execute man pager.
1402 * We provide -M to man here because LTTng-tools can
1403 * be installed outside /usr, in which case its man pages are
1404 * not located in the default /usr/share/man directory.
1406 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1407 section_string
, page_name
, NULL
);
1414 int read_proc_meminfo_field(const char *field
, size_t *value
)
1418 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1420 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1421 if (!proc_meminfo
) {
1422 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1428 * Read the contents of /proc/meminfo line by line to find the right
1431 while (!feof(proc_meminfo
)) {
1432 unsigned long value_kb
;
1434 ret
= fscanf(proc_meminfo
,
1435 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1439 * fscanf() returning EOF can indicate EOF or an error.
1441 if (ferror(proc_meminfo
)) {
1442 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1447 if (ret
== 2 && strcmp(name
, field
) == 0) {
1449 * This number is displayed in kilo-bytes. Return the
1452 *value
= ((size_t) value_kb
) * 1024;
1457 /* Reached the end of the file without finding the right field. */
1461 fclose(proc_meminfo
);
1467 * Returns an estimate of the number of bytes of memory available based on the
1468 * the information in `/proc/meminfo`. The number returned by this function is
1471 int utils_get_memory_available(size_t *value
)
1473 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1477 * Returns the total size of the memory on the system in bytes based on the
1478 * the information in `/proc/meminfo`.
1480 int utils_get_memory_total(size_t *value
)
1482 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1485 int utils_change_working_directory(const char *path
)
1491 DBG("Changing working directory to \"%s\"", path
);
1494 PERROR("Failed to change working directory to \"%s\"", path
);
1498 /* Check for write access */
1499 if (access(path
, W_OK
)) {
1500 if (errno
== EACCES
) {
1502 * Do not treat this as an error since the permission
1503 * might change in the lifetime of the process
1505 DBG("Working directory \"%s\" is not writable", path
);
1507 PERROR("Failed to check if working directory \"%s\" is writable",
1516 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1518 struct passwd p
, *pres
;
1520 enum lttng_error_code ret_val
= LTTNG_OK
;
1524 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1526 buflen
= FALLBACK_USER_BUFLEN
;
1529 buf
= (char *) zmalloc(buflen
);
1531 ret_val
= LTTNG_ERR_NOMEM
;
1536 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1543 buf
= (char *) zmalloc(buflen
);
1545 ret_val
= LTTNG_ERR_NOMEM
;
1558 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1561 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1562 user_name
, (int64_t) *uid
);
1570 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1573 ret_val
= LTTNG_ERR_NOMEM
;
1580 enum lttng_error_code
utils_group_id_from_name(
1581 const char *group_name
, gid_t
*gid
)
1583 struct group g
, *gres
;
1585 enum lttng_error_code ret_val
= LTTNG_OK
;
1589 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1591 buflen
= FALLBACK_GROUP_BUFLEN
;
1594 buf
= (char *) zmalloc(buflen
);
1596 ret_val
= LTTNG_ERR_NOMEM
;
1601 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1608 buf
= (char *) zmalloc(buflen
);
1610 ret_val
= LTTNG_ERR_NOMEM
;
1623 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1626 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1627 group_name
, (int64_t) *gid
);
1635 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1638 ret_val
= LTTNG_ERR_NOMEM
;
1645 int utils_parse_unsigned_long_long(const char *str
,
1646 unsigned long long *value
)
1652 LTTNG_ASSERT(value
);
1655 *value
= strtoull(str
, &endptr
, 10);
1657 /* Conversion failed. Out of range? */
1659 /* Don't print an error; allow the caller to log a better error. */
1660 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1666 /* Not the end of the string or empty string. */
1667 if (*endptr
|| endptr
== str
) {
1668 DBG("Failed to parse string as unsigned long long number: string = '%s'",