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 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License, version 2 only, as
8 * published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <sys/types.h>
35 #include <common/common.h>
36 #include <common/readwrite.h>
37 #include <common/runas.h>
38 #include <common/compat/getenv.h>
39 #include <common/compat/string.h>
40 #include <common/compat/dirent.h>
41 #include <common/compat/directory-handle.h>
42 #include <common/dynamic-buffer.h>
43 #include <lttng/constant.h>
49 #define PROC_MEMINFO_PATH "/proc/meminfo"
50 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
51 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
53 /* The length of the longest field of `/proc/meminfo`. */
54 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
56 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
57 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
59 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
63 * Return a partial realpath(3) of the path even if the full path does not
64 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
65 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
66 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
67 * point directory does not exist.
68 * In case resolved_path is NULL, the string returned was allocated in the
69 * function and thus need to be freed by the caller. The size argument allows
70 * to specify the size of the resolved_path argument if given, or the size to
74 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
76 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
77 const char *next
, *prev
, *end
;
85 * Identify the end of the path, we don't want to treat the
86 * last char if it is a '/', we will just keep it on the side
87 * to be added at the end, and return a value coherent with
88 * the path given as argument
90 end
= path
+ strlen(path
);
91 if (*(end
-1) == '/') {
95 /* Initiate the values of the pointers before looping */
98 /* Only to ensure try_path is not NULL to enter the while */
99 try_path
= (char *)next
;
101 /* Resolve the canonical path of the first part of the path */
102 while (try_path
!= NULL
&& next
!= end
) {
103 char *try_path_buf
= NULL
;
106 * If there is not any '/' left, we want to try with
109 next
= strpbrk(next
+ 1, "/");
114 /* Cut the part we will be trying to resolve */
115 cut_path
= lttng_strndup(path
, next
- path
);
116 if (cut_path
== NULL
) {
117 PERROR("lttng_strndup");
121 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
127 /* Try to resolve this part */
128 try_path
= realpath((char *) cut_path
, try_path_buf
);
129 if (try_path
== NULL
) {
132 * There was an error, we just want to be assured it
133 * is linked to an unexistent directory, if it's another
134 * reason, we spawn an error
138 /* Ignore the error */
141 PERROR("realpath (partial_realpath)");
146 /* Save the place we are before trying the next step */
149 try_path_prev
= try_path
;
153 /* Free the allocated memory */
158 /* Allocate memory for the resolved path if necessary */
159 if (resolved_path
== NULL
) {
160 resolved_path
= zmalloc(size
);
161 if (resolved_path
== NULL
) {
162 PERROR("zmalloc resolved path");
168 * If we were able to solve at least partially the path, we can concatenate
169 * what worked and what didn't work
171 if (try_path_prev
!= NULL
) {
172 /* If we risk to concatenate two '/', we remove one of them */
173 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
174 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
178 * Duplicate the memory used by prev in case resolved_path and
179 * path are pointers for the same memory space
181 cut_path
= strdup(prev
);
182 if (cut_path
== NULL
) {
187 /* Concatenate the strings */
188 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
190 /* Free the allocated memory */
194 try_path_prev
= NULL
;
196 * Else, we just copy the path in our resolved_path to
200 strncpy(resolved_path
, path
, size
);
203 /* Then we return the 'partially' resolved path */
204 return resolved_path
;
210 if (try_path_prev
!= try_path
) {
217 int expand_double_slashes_dot_and_dotdot(char *path
)
219 size_t expanded_path_len
, path_len
;
220 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
222 path_len
= strlen(path
);
223 path_last_char
= &path
[path_len
];
229 expanded_path_len
= 0;
231 /* We iterate over the provided path to expand the "//", "../" and "./" */
232 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
233 /* Find the next forward slash. */
234 size_t curr_token_len
;
236 if (curr_char
== path_last_char
) {
241 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
242 if (next_slash
== NULL
) {
243 /* Reached the end of the provided path. */
244 next_slash
= path_last_char
;
247 /* Compute how long is the previous token. */
248 curr_token_len
= next_slash
- curr_char
;
249 switch(curr_token_len
) {
252 * The pointer has not move meaning that curr_char is
253 * pointing to a slash. It that case there is no token
254 * to copy, so continue the iteration to find the next
260 * The pointer moved 1 character. Check if that
261 * character is a dot ('.'), if it is: omit it, else
262 * copy the token to the normalized path.
264 if (curr_char
[0] == '.') {
270 * The pointer moved 2 characters. Check if these
271 * characters are double dots ('..'). If that is the
272 * case, we need to remove the last token of the
275 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
277 * Find the previous path component by
278 * using the memrchr function to find the
279 * previous forward slash and substract that
280 * len to the resulting path.
282 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
284 * If prev_slash is NULL, we reached the
285 * beginning of the path. We can't go back any
288 if (prev_slash
!= NULL
) {
289 expanded_path_len
= prev_slash
- path
;
299 * Copy the current token which is neither a '.' nor a '..'.
301 path
[expanded_path_len
++] = '/';
302 memcpy(&path
[expanded_path_len
], curr_char
, curr_token_len
);
303 expanded_path_len
+= curr_token_len
;
306 if (expanded_path_len
== 0) {
307 path
[expanded_path_len
++] = '/';
310 path
[expanded_path_len
] = '\0';
317 * Make a full resolution of the given path even if it doesn't exist.
318 * This function uses the utils_partial_realpath function to resolve
319 * symlinks and relatives paths at the start of the string, and
320 * implements functionnalities to resolve the './' and '../' strings
321 * in the middle of a path. This function is only necessary because
322 * realpath(3) does not accept to resolve unexistent paths.
323 * The returned string was allocated in the function, it is thus of
324 * the responsibility of the caller to free this memory.
327 char *_utils_expand_path(const char *path
, bool keep_symlink
)
330 char *absolute_path
= NULL
;
332 bool is_dot
, is_dotdot
;
339 /* Allocate memory for the absolute_path */
340 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
341 if (absolute_path
== NULL
) {
342 PERROR("zmalloc expand path");
346 if (path
[0] == '/') {
347 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
349 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
354 * This is a relative path. We need to get the present working
355 * directory and start the path walk from there.
357 char current_working_dir
[LTTNG_PATH_MAX
];
360 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
365 * Get the number of character in the CWD and allocate an array
366 * to can hold it and the path provided by the caller.
368 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
369 current_working_dir
, path
);
370 if (ret
>= LTTNG_PATH_MAX
) {
371 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
372 current_working_dir
, path
, LTTNG_PATH_MAX
);
378 /* Resolve partially our path */
379 absolute_path
= utils_partial_realpath(absolute_path
,
380 absolute_path
, LTTNG_PATH_MAX
);
383 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
388 /* Identify the last token */
389 last_token
= strrchr(absolute_path
, '/');
391 /* Verify that this token is not a relative path */
392 is_dotdot
= (strcmp(last_token
, "/..") == 0);
393 is_dot
= (strcmp(last_token
, "/.") == 0);
395 /* If it is, take action */
396 if (is_dot
|| is_dotdot
) {
397 /* For both, remove this token */
400 /* If it was a reference to parent directory, go back one more time */
402 last_token
= strrchr(absolute_path
, '/');
404 /* If there was only one level left, we keep the first '/' */
405 if (last_token
== absolute_path
) {
413 return absolute_path
;
420 char *utils_expand_path(const char *path
)
422 return _utils_expand_path(path
, true);
426 char *utils_expand_path_keep_symlink(const char *path
)
428 return _utils_expand_path(path
, false);
431 * Create a pipe in dst.
434 int utils_create_pipe(int *dst
)
444 PERROR("create pipe");
451 * Create pipe and set CLOEXEC flag to both fd.
453 * Make sure the pipe opened by this function are closed at some point. Use
454 * utils_close_pipe().
457 int utils_create_pipe_cloexec(int *dst
)
465 ret
= utils_create_pipe(dst
);
470 for (i
= 0; i
< 2; i
++) {
471 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
473 PERROR("fcntl pipe cloexec");
483 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
485 * Make sure the pipe opened by this function are closed at some point. Use
486 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
487 * support OSes other than Linux 2.6.23+.
490 int utils_create_pipe_cloexec_nonblock(int *dst
)
498 ret
= utils_create_pipe(dst
);
503 for (i
= 0; i
< 2; i
++) {
504 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
506 PERROR("fcntl pipe cloexec");
510 * Note: we override any flag that could have been
511 * previously set on the fd.
513 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
515 PERROR("fcntl pipe nonblock");
525 * Close both read and write side of the pipe.
528 void utils_close_pipe(int *src
)
536 for (i
= 0; i
< 2; i
++) {
544 PERROR("close pipe");
550 * Create a new string using two strings range.
553 char *utils_strdupdelim(const char *begin
, const char *end
)
557 str
= zmalloc(end
- begin
+ 1);
559 PERROR("zmalloc strdupdelim");
563 memcpy(str
, begin
, end
- begin
);
564 str
[end
- begin
] = '\0';
571 * Set CLOEXEC flag to the give file descriptor.
574 int utils_set_fd_cloexec(int fd
)
583 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
585 PERROR("fcntl cloexec");
594 * Create pid file to the given path and filename.
597 int utils_create_pid_file(pid_t pid
, const char *filepath
)
604 fp
= fopen(filepath
, "w");
606 PERROR("open pid file %s", filepath
);
611 ret
= fprintf(fp
, "%d\n", (int) pid
);
613 PERROR("fprintf pid file");
620 DBG("Pid %d written in file %s", (int) pid
, filepath
);
627 * Create lock file to the given path and filename.
628 * Returns the associated file descriptor, -1 on error.
631 int utils_create_lock_file(const char *filepath
)
639 memset(&lock
, 0, sizeof(lock
));
640 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
643 PERROR("open lock file %s", filepath
);
649 * Attempt to lock the file. If this fails, there is
650 * already a process using the same lock file running
651 * and we should exit.
653 lock
.l_whence
= SEEK_SET
;
654 lock
.l_type
= F_WRLCK
;
656 ret
= fcntl(fd
, F_SETLK
, &lock
);
658 PERROR("fcntl lock file");
659 ERR("Could not get lock file %s, another instance is running.",
662 PERROR("close lock file");
673 * Create directory using the given path and mode.
675 * On success, return 0 else a negative error code.
678 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
681 struct lttng_directory_handle handle
;
682 const struct lttng_credentials creds
= {
687 ret
= lttng_directory_handle_init(&handle
, NULL
);
691 ret
= lttng_directory_handle_create_subdirectory_as_user(
693 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
694 lttng_directory_handle_fini(&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
= {
715 ret
= lttng_directory_handle_init(&handle
, NULL
);
719 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
721 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
722 lttng_directory_handle_fini(&handle
);
728 * path is the output parameter. It needs to be PATH_MAX len.
730 * Return 0 on success or else a negative value.
732 static int utils_stream_file_name(char *path
,
733 const char *path_name
, const char *file_name
,
734 uint64_t size
, uint64_t count
,
738 char full_path
[PATH_MAX
];
739 char *path_name_suffix
= NULL
;
742 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
743 path_name
, file_name
);
745 PERROR("snprintf create output file");
749 /* Setup extra string if suffix or/and a count is needed. */
750 if (size
> 0 && suffix
) {
751 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
752 } else if (size
> 0) {
753 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
755 ret
= asprintf(&extra
, "%s", suffix
);
758 PERROR("Allocating extra string to name");
763 * If we split the trace in multiple files, we have to add the count at
764 * the end of the tracefile name.
767 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
769 PERROR("Allocating path name with extra string");
770 goto error_free_suffix
;
772 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
773 path
[PATH_MAX
- 1] = '\0';
775 ret
= lttng_strncpy(path
, full_path
, PATH_MAX
);
777 ERR("Failed to copy stream file name");
778 goto error_free_suffix
;
781 path
[PATH_MAX
- 1] = '\0';
784 free(path_name_suffix
);
792 * Create the stream file on disk.
794 * Return 0 on success or else a negative value.
797 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
798 uint64_t count
, int uid
, int gid
, char *suffix
)
800 int ret
, flags
, mode
;
803 ret
= utils_stream_file_name(path
, path_name
, file_name
,
804 size
, count
, suffix
);
810 * With the session rotation feature on the relay, we might need to seek
811 * and truncate a tracefile, so we need read and write access.
813 flags
= O_RDWR
| O_CREAT
| O_TRUNC
;
814 /* Open with 660 mode */
815 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
817 if (uid
< 0 || gid
< 0) {
818 ret
= open(path
, flags
, mode
);
820 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
823 PERROR("open stream path %s", path
);
830 * Unlink the stream tracefile from disk.
832 * Return 0 on success or else a negative value.
835 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
836 uint64_t count
, int uid
, int gid
, char *suffix
)
841 ret
= utils_stream_file_name(path
, path_name
, file_name
,
842 size
, count
, suffix
);
846 if (uid
< 0 || gid
< 0) {
849 ret
= run_as_unlink(path
, uid
, gid
);
855 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
860 * Change the output tracefile according to the given size and count The
861 * new_count pointer is set during this operation.
863 * From the consumer, the stream lock MUST be held before calling this function
864 * because we are modifying the stream status.
866 * Return 0 on success or else a negative value.
869 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
870 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
879 PERROR("Closing tracefile");
886 * In tracefile rotation, for the relay daemon we need
887 * to unlink the old file if present, because it may
888 * still be open in reading by the live thread, and we
889 * need to ensure that we do not overwrite the content
890 * between get_index and get_packet. Since we have no
891 * way to verify integrity of the data content compared
892 * to the associated index, we need to ensure the reader
893 * has exclusive access to the file content, and that
894 * the open of the data file is performed in get_index.
895 * Unlinking the old file rather than overwriting it
899 *new_count
= (*new_count
+ 1) % count
;
901 ret
= utils_unlink_stream_file(path_name
, file_name
, size
,
902 new_count
? *new_count
: 0, uid
, gid
, 0);
903 if (ret
< 0 && errno
!= ENOENT
) {
912 ret
= utils_create_stream_file(path_name
, file_name
, size
,
913 new_count
? *new_count
: 0, uid
, gid
, 0);
928 * Parse a string that represents a size in human readable format. It
929 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
931 * The suffix multiply the integer by:
936 * @param str The string to parse.
937 * @param size Pointer to a uint64_t that will be filled with the
940 * @return 0 on success, -1 on failure.
943 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
952 DBG("utils_parse_size_suffix: received a NULL string.");
957 /* strtoull will accept a negative number, but we don't want to. */
958 if (strchr(str
, '-') != NULL
) {
959 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
964 /* str_end will point to the \0 */
965 str_end
= str
+ strlen(str
);
967 base_size
= strtoull(str
, &num_end
, 0);
969 PERROR("utils_parse_size_suffix strtoull");
974 if (num_end
== str
) {
975 /* strtoull parsed nothing, not good. */
976 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
981 /* Check if a prefix is present. */
999 DBG("utils_parse_size_suffix: invalid suffix.");
1004 /* Check for garbage after the valid input. */
1005 if (num_end
!= str_end
) {
1006 DBG("utils_parse_size_suffix: Garbage after size string.");
1011 *size
= base_size
<< shift
;
1013 /* Check for overflow */
1014 if ((*size
>> shift
) != base_size
) {
1015 DBG("utils_parse_size_suffix: oops, overflow detected.");
1026 * Parse a string that represents a time in human readable format. It
1027 * supports decimal integers suffixed by:
1028 * "us" for microsecond,
1029 * "ms" for millisecond,
1034 * The suffix multiply the integer by:
1041 * Note that unit-less numbers are assumed to be microseconds.
1043 * @param str The string to parse, assumed to be NULL-terminated.
1044 * @param time_us Pointer to a uint64_t that will be filled with the
1045 * resulting time in microseconds.
1047 * @return 0 on success, -1 on failure.
1050 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
1054 uint64_t multiplier
= 1;
1055 const char *str_end
;
1059 DBG("utils_parse_time_suffix: received a NULL string.");
1064 /* strtoull will accept a negative number, but we don't want to. */
1065 if (strchr(str
, '-') != NULL
) {
1066 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1071 /* str_end will point to the \0 */
1072 str_end
= str
+ strlen(str
);
1074 base_time
= strtoull(str
, &num_end
, 10);
1076 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
1081 if (num_end
== str
) {
1082 /* strtoull parsed nothing, not good. */
1083 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1088 /* Check if a prefix is present. */
1094 * Skip the "us" if the string matches the "us" suffix,
1095 * otherwise let the check for the end of the string handle
1096 * the error reporting.
1098 if (*(num_end
+ 1) == 's') {
1103 if (*(num_end
+ 1) == 's') {
1104 /* Millisecond (ms) */
1105 multiplier
= USEC_PER_MSEC
;
1110 multiplier
= USEC_PER_MINUTE
;
1116 multiplier
= USEC_PER_SEC
;
1121 multiplier
= USEC_PER_HOURS
;
1127 DBG("utils_parse_time_suffix: invalid suffix.");
1132 /* Check for garbage after the valid input. */
1133 if (num_end
!= str_end
) {
1134 DBG("utils_parse_time_suffix: Garbage after time string.");
1139 *time_us
= base_time
* multiplier
;
1141 /* Check for overflow */
1142 if ((*time_us
/ multiplier
) != base_time
) {
1143 DBG("utils_parse_time_suffix: oops, overflow detected.");
1154 * fls: returns the position of the most significant bit.
1155 * Returns 0 if no bit is set, else returns the position of the most
1156 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1158 #if defined(__i386) || defined(__x86_64)
1159 static inline unsigned int fls_u32(uint32_t x
)
1163 asm("bsrl %1,%0\n\t"
1167 : "=r" (r
) : "rm" (x
));
1173 #if defined(__x86_64)
1175 unsigned int fls_u64(uint64_t x
)
1179 asm("bsrq %1,%0\n\t"
1183 : "=r" (r
) : "rm" (x
));
1190 static __attribute__((unused
))
1191 unsigned int fls_u64(uint64_t x
)
1193 unsigned int r
= 64;
1198 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1202 if (!(x
& 0xFFFF000000000000ULL
)) {
1206 if (!(x
& 0xFF00000000000000ULL
)) {
1210 if (!(x
& 0xF000000000000000ULL
)) {
1214 if (!(x
& 0xC000000000000000ULL
)) {
1218 if (!(x
& 0x8000000000000000ULL
)) {
1227 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1229 unsigned int r
= 32;
1234 if (!(x
& 0xFFFF0000U
)) {
1238 if (!(x
& 0xFF000000U
)) {
1242 if (!(x
& 0xF0000000U
)) {
1246 if (!(x
& 0xC0000000U
)) {
1250 if (!(x
& 0x80000000U
)) {
1259 * Return the minimum order for which x <= (1UL << order).
1260 * Return -1 if x is 0.
1263 int utils_get_count_order_u32(uint32_t x
)
1269 return fls_u32(x
- 1);
1273 * Return the minimum order for which x <= (1UL << order).
1274 * Return -1 if x is 0.
1277 int utils_get_count_order_u64(uint64_t x
)
1283 return fls_u64(x
- 1);
1287 * Obtain the value of LTTNG_HOME environment variable, if exists.
1288 * Otherwise returns the value of HOME.
1291 char *utils_get_home_dir(void)
1296 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1300 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1305 /* Fallback on the password file entry. */
1306 pwd
= getpwuid(getuid());
1312 DBG3("Home directory is '%s'", val
);
1319 * Get user's home directory. Dynamically allocated, must be freed
1323 char *utils_get_user_home_dir(uid_t uid
)
1326 struct passwd
*result
;
1327 char *home_dir
= NULL
;
1332 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1337 buf
= zmalloc(buflen
);
1342 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1343 if (ret
|| !result
) {
1344 if (ret
== ERANGE
) {
1352 home_dir
= strdup(pwd
.pw_dir
);
1359 * With the given format, fill dst with the time of len maximum siz.
1361 * Return amount of bytes set in the buffer or else 0 on error.
1364 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1368 struct tm
*timeinfo
;
1373 /* Get date and time for session path */
1375 timeinfo
= localtime(&rawtime
);
1376 ret
= strftime(dst
, len
, format
, timeinfo
);
1378 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1386 * Return 0 on success and set *gid to the group_ID matching the passed name.
1387 * Else -1 if it cannot be found or an error occurred.
1390 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1392 static volatile int warn_once
;
1397 struct group
*result
;
1398 struct lttng_dynamic_buffer buffer
;
1400 /* Get the system limit, if it exists. */
1401 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1402 if (sys_len
== -1) {
1405 len
= (size_t) sys_len
;
1408 lttng_dynamic_buffer_init(&buffer
);
1409 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1411 ERR("Failed to allocate group info buffer");
1416 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1417 const size_t new_len
= 2 * buffer
.size
;
1419 /* Buffer is not big enough, increase its size. */
1420 if (new_len
< buffer
.size
) {
1421 ERR("Group info buffer size overflow");
1426 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1428 ERR("Failed to grow group info buffer to %zu bytes",
1435 PERROR("Failed to get group file entry for group name \"%s\"",
1441 /* Group not found. */
1447 *gid
= result
->gr_gid
;
1451 if (ret
&& warn
&& !warn_once
) {
1452 WARN("No tracing group detected");
1455 lttng_dynamic_buffer_reset(&buffer
);
1460 * Return a newly allocated option string. This string is to be used as the
1461 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1462 * of elements in the long_options array. Returns NULL if the string's
1466 char *utils_generate_optstring(const struct option
*long_options
,
1470 size_t string_len
= opt_count
, str_pos
= 0;
1474 * Compute the necessary string length. One letter per option, two when an
1475 * argument is necessary, and a trailing NULL.
1477 for (i
= 0; i
< opt_count
; i
++) {
1478 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1481 optstring
= zmalloc(string_len
);
1486 for (i
= 0; i
< opt_count
; i
++) {
1487 if (!long_options
[i
].name
) {
1488 /* Got to the trailing NULL element */
1492 if (long_options
[i
].val
!= '\0') {
1493 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1494 if (long_options
[i
].has_arg
) {
1495 optstring
[str_pos
++] = ':';
1505 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1506 * any file. Try to rmdir any empty directory within the hierarchy.
1509 int utils_recursive_rmdir(const char *path
)
1513 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1514 struct dirent
*entry
;
1516 /* Open directory */
1517 dir
= opendir(path
);
1519 PERROR("Cannot open '%s' path", path
);
1522 dir_fd
= lttng_dirfd(dir
);
1524 PERROR("lttng_dirfd");
1528 path_len
= strlen(path
);
1529 while ((entry
= readdir(dir
))) {
1532 char filename
[PATH_MAX
];
1534 if (!strcmp(entry
->d_name
, ".")
1535 || !strcmp(entry
->d_name
, "..")) {
1539 name_len
= strlen(entry
->d_name
);
1540 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1541 ERR("Failed to remove file: path name too long (%s/%s)",
1542 path
, entry
->d_name
);
1545 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1546 path
, entry
->d_name
) < 0) {
1547 ERR("Failed to format path.");
1551 if (stat(filename
, &st
)) {
1556 if (S_ISDIR(st
.st_mode
)) {
1557 char subpath
[PATH_MAX
];
1559 strncpy(subpath
, path
, PATH_MAX
);
1560 subpath
[PATH_MAX
- 1] = '\0';
1561 strncat(subpath
, "/",
1562 PATH_MAX
- strlen(subpath
) - 1);
1563 strncat(subpath
, entry
->d_name
,
1564 PATH_MAX
- strlen(subpath
) - 1);
1565 if (utils_recursive_rmdir(subpath
)) {
1568 } else if (S_ISREG(st
.st_mode
)) {
1576 closeret
= closedir(dir
);
1581 DBG3("Attempting rmdir %s", path
);
1588 int utils_truncate_stream_file(int fd
, off_t length
)
1593 ret
= ftruncate(fd
, length
);
1595 PERROR("ftruncate");
1598 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1599 if (lseek_ret
< 0) {
1608 static const char *get_man_bin_path(void)
1610 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1613 return env_man_path
;
1616 return DEFAULT_MAN_BIN_PATH
;
1620 int utils_show_help(int section
, const char *page_name
,
1621 const char *help_msg
)
1623 char section_string
[8];
1624 const char *man_bin_path
= get_man_bin_path();
1628 printf("%s", help_msg
);
1632 /* Section integer -> section string */
1633 ret
= sprintf(section_string
, "%d", section
);
1634 assert(ret
> 0 && ret
< 8);
1637 * Execute man pager.
1639 * We provide -M to man here because LTTng-tools can
1640 * be installed outside /usr, in which case its man pages are
1641 * not located in the default /usr/share/man directory.
1643 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1644 section_string
, page_name
, NULL
);
1651 int read_proc_meminfo_field(const char *field
, size_t *value
)
1655 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1657 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1658 if (!proc_meminfo
) {
1659 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1665 * Read the contents of /proc/meminfo line by line to find the right
1668 while (!feof(proc_meminfo
)) {
1669 unsigned long value_kb
;
1671 ret
= fscanf(proc_meminfo
,
1672 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1676 * fscanf() returning EOF can indicate EOF or an error.
1678 if (ferror(proc_meminfo
)) {
1679 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1684 if (ret
== 2 && strcmp(name
, field
) == 0) {
1686 * This number is displayed in kilo-bytes. Return the
1689 *value
= ((size_t) value_kb
) * 1024;
1694 /* Reached the end of the file without finding the right field. */
1698 fclose(proc_meminfo
);
1704 * Returns an estimate of the number of bytes of memory available based on the
1705 * the information in `/proc/meminfo`. The number returned by this function is
1709 int utils_get_memory_available(size_t *value
)
1711 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1715 * Returns the total size of the memory on the system in bytes based on the
1716 * the information in `/proc/meminfo`.
1719 int utils_get_memory_total(size_t *value
)
1721 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);