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/runas.h>
37 #include <common/compat/getenv.h>
38 #include <common/compat/string.h>
39 #include <common/compat/dirent.h>
40 #include <lttng/constant.h>
47 * Return a partial realpath(3) of the path even if the full path does not
48 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
49 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
50 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
51 * point directory does not exist.
52 * In case resolved_path is NULL, the string returned was allocated in the
53 * function and thus need to be freed by the caller. The size argument allows
54 * to specify the size of the resolved_path argument if given, or the size to
58 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
60 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
61 const char *next
, *prev
, *end
;
69 * Identify the end of the path, we don't want to treat the
70 * last char if it is a '/', we will just keep it on the side
71 * to be added at the end, and return a value coherent with
72 * the path given as argument
74 end
= path
+ strlen(path
);
75 if (*(end
-1) == '/') {
79 /* Initiate the values of the pointers before looping */
82 /* Only to ensure try_path is not NULL to enter the while */
83 try_path
= (char *)next
;
85 /* Resolve the canonical path of the first part of the path */
86 while (try_path
!= NULL
&& next
!= end
) {
87 char *try_path_buf
= NULL
;
90 * If there is not any '/' left, we want to try with
93 next
= strpbrk(next
+ 1, "/");
98 /* Cut the part we will be trying to resolve */
99 cut_path
= lttng_strndup(path
, next
- path
);
100 if (cut_path
== NULL
) {
101 PERROR("lttng_strndup");
105 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
111 /* Try to resolve this part */
112 try_path
= realpath((char *) cut_path
, try_path_buf
);
113 if (try_path
== NULL
) {
116 * There was an error, we just want to be assured it
117 * is linked to an unexistent directory, if it's another
118 * reason, we spawn an error
122 /* Ignore the error */
125 PERROR("realpath (partial_realpath)");
130 /* Save the place we are before trying the next step */
133 try_path_prev
= try_path
;
137 /* Free the allocated memory */
142 /* Allocate memory for the resolved path if necessary */
143 if (resolved_path
== NULL
) {
144 resolved_path
= zmalloc(size
);
145 if (resolved_path
== NULL
) {
146 PERROR("zmalloc resolved path");
152 * If we were able to solve at least partially the path, we can concatenate
153 * what worked and what didn't work
155 if (try_path_prev
!= NULL
) {
156 /* If we risk to concatenate two '/', we remove one of them */
157 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
158 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
162 * Duplicate the memory used by prev in case resolved_path and
163 * path are pointers for the same memory space
165 cut_path
= strdup(prev
);
166 if (cut_path
== NULL
) {
171 /* Concatenate the strings */
172 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
174 /* Free the allocated memory */
178 try_path_prev
= NULL
;
180 * Else, we just copy the path in our resolved_path to
184 strncpy(resolved_path
, path
, size
);
187 /* Then we return the 'partially' resolved path */
188 return resolved_path
;
194 if (try_path_prev
!= try_path
) {
201 int expand_double_slashes_dot_and_dotdot(char *path
)
203 size_t expanded_path_len
, path_len
;
204 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
206 path_len
= strlen(path
);
207 path_last_char
= &path
[path_len
];
213 expanded_path_len
= 0;
215 /* We iterate over the provided path to expand the "//", "../" and "./" */
216 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
217 /* Find the next forward slash. */
218 size_t curr_token_len
;
220 if (curr_char
== path_last_char
) {
225 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
226 if (next_slash
== NULL
) {
227 /* Reached the end of the provided path. */
228 next_slash
= path_last_char
;
231 /* Compute how long is the previous token. */
232 curr_token_len
= next_slash
- curr_char
;
233 switch(curr_token_len
) {
236 * The pointer has not move meaning that curr_char is
237 * pointing to a slash. It that case there is no token
238 * to copy, so continue the iteration to find the next
244 * The pointer moved 1 character. Check if that
245 * character is a dot ('.'), if it is: omit it, else
246 * copy the token to the normalized path.
248 if (curr_char
[0] == '.') {
254 * The pointer moved 2 characters. Check if these
255 * characters are double dots ('..'). If that is the
256 * case, we need to remove the last token of the
259 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
261 * Find the previous path component by
262 * using the memrchr function to find the
263 * previous forward slash and substract that
264 * len to the resulting path.
266 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
268 * If prev_slash is NULL, we reached the
269 * beginning of the path. We can't go back any
272 if (prev_slash
!= NULL
) {
273 expanded_path_len
= prev_slash
- path
;
283 * Copy the current token which is neither a '.' nor a '..'.
285 path
[expanded_path_len
++] = '/';
286 memcpy(&path
[expanded_path_len
], curr_char
, curr_token_len
);
287 expanded_path_len
+= curr_token_len
;
290 if (expanded_path_len
== 0) {
291 path
[expanded_path_len
++] = '/';
294 path
[expanded_path_len
] = '\0';
301 * Make a full resolution of the given path even if it doesn't exist.
302 * This function uses the utils_partial_realpath function to resolve
303 * symlinks and relatives paths at the start of the string, and
304 * implements functionnalities to resolve the './' and '../' strings
305 * in the middle of a path. This function is only necessary because
306 * realpath(3) does not accept to resolve unexistent paths.
307 * The returned string was allocated in the function, it is thus of
308 * the responsibility of the caller to free this memory.
311 char *_utils_expand_path(const char *path
, bool keep_symlink
)
314 char *absolute_path
= NULL
;
316 bool is_dot
, is_dotdot
;
323 /* Allocate memory for the absolute_path */
324 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
325 if (absolute_path
== NULL
) {
326 PERROR("zmalloc expand path");
330 if (path
[0] == '/') {
331 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
333 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
338 * This is a relative path. We need to get the present working
339 * directory and start the path walk from there.
341 char current_working_dir
[LTTNG_PATH_MAX
];
344 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
349 * Get the number of character in the CWD and allocate an array
350 * to can hold it and the path provided by the caller.
352 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
353 current_working_dir
, path
);
354 if (ret
>= LTTNG_PATH_MAX
) {
355 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
356 current_working_dir
, path
, LTTNG_PATH_MAX
);
362 /* Resolve partially our path */
363 absolute_path
= utils_partial_realpath(absolute_path
,
364 absolute_path
, LTTNG_PATH_MAX
);
367 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
372 /* Identify the last token */
373 last_token
= strrchr(absolute_path
, '/');
375 /* Verify that this token is not a relative path */
376 is_dotdot
= (strcmp(last_token
, "/..") == 0);
377 is_dot
= (strcmp(last_token
, "/.") == 0);
379 /* If it is, take action */
380 if (is_dot
|| is_dotdot
) {
381 /* For both, remove this token */
384 /* If it was a reference to parent directory, go back one more time */
386 last_token
= strrchr(absolute_path
, '/');
388 /* If there was only one level left, we keep the first '/' */
389 if (last_token
== absolute_path
) {
397 return absolute_path
;
404 char *utils_expand_path(const char *path
)
406 return _utils_expand_path(path
, true);
410 char *utils_expand_path_keep_symlink(const char *path
)
412 return _utils_expand_path(path
, false);
415 * Create a pipe in dst.
418 int utils_create_pipe(int *dst
)
428 PERROR("create pipe");
435 * Create pipe and set CLOEXEC flag to both fd.
437 * Make sure the pipe opened by this function are closed at some point. Use
438 * utils_close_pipe().
441 int utils_create_pipe_cloexec(int *dst
)
449 ret
= utils_create_pipe(dst
);
454 for (i
= 0; i
< 2; i
++) {
455 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
457 PERROR("fcntl pipe cloexec");
467 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
469 * Make sure the pipe opened by this function are closed at some point. Use
470 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
471 * support OSes other than Linux 2.6.23+.
474 int utils_create_pipe_cloexec_nonblock(int *dst
)
482 ret
= utils_create_pipe(dst
);
487 for (i
= 0; i
< 2; i
++) {
488 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
490 PERROR("fcntl pipe cloexec");
494 * Note: we override any flag that could have been
495 * previously set on the fd.
497 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
499 PERROR("fcntl pipe nonblock");
509 * Close both read and write side of the pipe.
512 void utils_close_pipe(int *src
)
520 for (i
= 0; i
< 2; i
++) {
528 PERROR("close pipe");
534 * Create a new string using two strings range.
537 char *utils_strdupdelim(const char *begin
, const char *end
)
541 str
= zmalloc(end
- begin
+ 1);
543 PERROR("zmalloc strdupdelim");
547 memcpy(str
, begin
, end
- begin
);
548 str
[end
- begin
] = '\0';
555 * Set CLOEXEC flag to the give file descriptor.
558 int utils_set_fd_cloexec(int fd
)
567 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
569 PERROR("fcntl cloexec");
578 * Create pid file to the given path and filename.
581 int utils_create_pid_file(pid_t pid
, const char *filepath
)
588 fp
= fopen(filepath
, "w");
590 PERROR("open pid file %s", filepath
);
595 ret
= fprintf(fp
, "%d\n", (int) pid
);
597 PERROR("fprintf pid file");
604 DBG("Pid %d written in file %s", (int) pid
, filepath
);
611 * Create lock file to the given path and filename.
612 * Returns the associated file descriptor, -1 on error.
615 int utils_create_lock_file(const char *filepath
)
623 memset(&lock
, 0, sizeof(lock
));
624 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
627 PERROR("open lock file %s", filepath
);
633 * Attempt to lock the file. If this fails, there is
634 * already a process using the same lock file running
635 * and we should exit.
637 lock
.l_whence
= SEEK_SET
;
638 lock
.l_type
= F_WRLCK
;
640 ret
= fcntl(fd
, F_SETLK
, &lock
);
642 PERROR("fcntl lock file");
643 ERR("Could not get lock file %s, another instance is running.",
646 PERROR("close lock file");
657 * On some filesystems (e.g. nfs), mkdir will validate access rights before
658 * checking for the existence of the path element. This means that on a setup
659 * where "/home/" is a mounted NFS share, and running as an unpriviledged user,
660 * recursively creating a path of the form "/home/my_user/trace/" will fail with
661 * EACCES on mkdir("/home", ...).
663 * Performing a stat(...) on the path to check for existence allows us to
664 * work around this behaviour.
667 int mkdir_check_exists(const char *path
, mode_t mode
)
672 ret
= stat(path
, &st
);
674 if (S_ISDIR(st
.st_mode
)) {
675 /* Directory exists, skip. */
678 /* Exists, but is not a directory. */
686 * Let mkdir handle other errors as the caller expects mkdir
689 ret
= mkdir(path
, mode
);
695 * Create directory using the given path and mode.
697 * On success, return 0 else a negative error code.
700 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
704 if (uid
< 0 || gid
< 0) {
705 ret
= mkdir_check_exists(path
, mode
);
707 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
710 if (errno
!= EEXIST
) {
711 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
722 * Internal version of mkdir_recursive. Runs as the current user.
723 * Don't call directly; use utils_mkdir_recursive().
725 * This function is ominously marked as "unsafe" since it should only
726 * be called by a caller that has transitioned to the uid and gid under which
727 * the directory creation should occur.
730 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
732 char *p
, tmp
[PATH_MAX
];
738 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
740 PERROR("snprintf mkdir");
745 if (tmp
[len
- 1] == '/') {
749 for (p
= tmp
+ 1; *p
; p
++) {
752 if (tmp
[strlen(tmp
) - 1] == '.' &&
753 tmp
[strlen(tmp
) - 2] == '.' &&
754 tmp
[strlen(tmp
) - 3] == '/') {
755 ERR("Using '/../' is not permitted in the trace path (%s)",
760 ret
= mkdir_check_exists(tmp
, mode
);
762 if (errno
!= EACCES
) {
763 PERROR("mkdir recursive");
772 ret
= mkdir_check_exists(tmp
, mode
);
774 PERROR("mkdir recursive last element");
783 * Recursively create directory using the given path and mode, under the
784 * provided uid and gid.
786 * On success, return 0 else a negative error code.
789 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
793 if (uid
< 0 || gid
< 0) {
794 /* Run as current user. */
795 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
797 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
800 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
808 * path is the output parameter. It needs to be PATH_MAX len.
810 * Return 0 on success or else a negative value.
812 static int utils_stream_file_name(char *path
,
813 const char *path_name
, const char *file_name
,
814 uint64_t size
, uint64_t count
,
818 char full_path
[PATH_MAX
];
819 char *path_name_suffix
= NULL
;
822 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
823 path_name
, file_name
);
825 PERROR("snprintf create output file");
829 /* Setup extra string if suffix or/and a count is needed. */
830 if (size
> 0 && suffix
) {
831 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
832 } else if (size
> 0) {
833 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
835 ret
= asprintf(&extra
, "%s", suffix
);
838 PERROR("Allocating extra string to name");
843 * If we split the trace in multiple files, we have to add the count at
844 * the end of the tracefile name.
847 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
849 PERROR("Allocating path name with extra string");
850 goto error_free_suffix
;
852 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
853 path
[PATH_MAX
- 1] = '\0';
855 ret
= lttng_strncpy(path
, full_path
, PATH_MAX
);
857 ERR("Failed to copy stream file name");
858 goto error_free_suffix
;
861 path
[PATH_MAX
- 1] = '\0';
864 free(path_name_suffix
);
872 * Create the stream file on disk.
874 * Return 0 on success or else a negative value.
877 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
878 uint64_t count
, int uid
, int gid
, char *suffix
)
880 int ret
, flags
, mode
;
883 ret
= utils_stream_file_name(path
, path_name
, file_name
,
884 size
, count
, suffix
);
890 * With the session rotation feature on the relay, we might need to seek
891 * and truncate a tracefile, so we need read and write access.
893 flags
= O_RDWR
| O_CREAT
| O_TRUNC
;
894 /* Open with 660 mode */
895 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
897 if (uid
< 0 || gid
< 0) {
898 ret
= open(path
, flags
, mode
);
900 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
903 PERROR("open stream path %s", path
);
910 * Unlink the stream tracefile from disk.
912 * Return 0 on success or else a negative value.
915 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
916 uint64_t count
, int uid
, int gid
, char *suffix
)
921 ret
= utils_stream_file_name(path
, path_name
, file_name
,
922 size
, count
, suffix
);
926 if (uid
< 0 || gid
< 0) {
929 ret
= run_as_unlink(path
, uid
, gid
);
935 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
940 * Change the output tracefile according to the given size and count The
941 * new_count pointer is set during this operation.
943 * From the consumer, the stream lock MUST be held before calling this function
944 * because we are modifying the stream status.
946 * Return 0 on success or else a negative value.
949 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
950 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
959 PERROR("Closing tracefile");
966 * In tracefile rotation, for the relay daemon we need
967 * to unlink the old file if present, because it may
968 * still be open in reading by the live thread, and we
969 * need to ensure that we do not overwrite the content
970 * between get_index and get_packet. Since we have no
971 * way to verify integrity of the data content compared
972 * to the associated index, we need to ensure the reader
973 * has exclusive access to the file content, and that
974 * the open of the data file is performed in get_index.
975 * Unlinking the old file rather than overwriting it
979 *new_count
= (*new_count
+ 1) % count
;
981 ret
= utils_unlink_stream_file(path_name
, file_name
, size
,
982 new_count
? *new_count
: 0, uid
, gid
, 0);
983 if (ret
< 0 && errno
!= ENOENT
) {
992 ret
= utils_create_stream_file(path_name
, file_name
, size
,
993 new_count
? *new_count
: 0, uid
, gid
, 0);
1008 * Parse a string that represents a size in human readable format. It
1009 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
1011 * The suffix multiply the integer by:
1016 * @param str The string to parse.
1017 * @param size Pointer to a uint64_t that will be filled with the
1020 * @return 0 on success, -1 on failure.
1023 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
1028 const char *str_end
;
1032 DBG("utils_parse_size_suffix: received a NULL string.");
1037 /* strtoull will accept a negative number, but we don't want to. */
1038 if (strchr(str
, '-') != NULL
) {
1039 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
1044 /* str_end will point to the \0 */
1045 str_end
= str
+ strlen(str
);
1047 base_size
= strtoull(str
, &num_end
, 0);
1049 PERROR("utils_parse_size_suffix strtoull");
1054 if (num_end
== str
) {
1055 /* strtoull parsed nothing, not good. */
1056 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
1061 /* Check if a prefix is present. */
1079 DBG("utils_parse_size_suffix: invalid suffix.");
1084 /* Check for garbage after the valid input. */
1085 if (num_end
!= str_end
) {
1086 DBG("utils_parse_size_suffix: Garbage after size string.");
1091 *size
= base_size
<< shift
;
1093 /* Check for overflow */
1094 if ((*size
>> shift
) != base_size
) {
1095 DBG("utils_parse_size_suffix: oops, overflow detected.");
1106 * Parse a string that represents a time in human readable format. It
1107 * supports decimal integers suffixed by 's', 'u', 'm', 'us', and 'ms'.
1109 * The suffix multiply the integer by:
1114 * Note that unit-less numbers are assumed to be microseconds.
1116 * @param str The string to parse, assumed to be NULL-terminated.
1117 * @param time_us Pointer to a uint64_t that will be filled with the
1118 * resulting time in microseconds.
1120 * @return 0 on success, -1 on failure.
1123 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
1127 long multiplier
= 1;
1128 const char *str_end
;
1132 DBG("utils_parse_time_suffix: received a NULL string.");
1137 /* strtoull will accept a negative number, but we don't want to. */
1138 if (strchr(str
, '-') != NULL
) {
1139 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1144 /* str_end will point to the \0 */
1145 str_end
= str
+ strlen(str
);
1147 base_time
= strtoull(str
, &num_end
, 10);
1149 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
1154 if (num_end
== str
) {
1155 /* strtoull parsed nothing, not good. */
1156 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1161 /* Check if a prefix is present. */
1165 /* Skip another letter in the 'us' case. */
1166 num_end
+= (*(num_end
+ 1) == 's') ? 2 : 1;
1170 /* Skip another letter in the 'ms' case. */
1171 num_end
+= (*(num_end
+ 1) == 's') ? 2 : 1;
1174 multiplier
= 1000000;
1180 DBG("utils_parse_time_suffix: invalid suffix.");
1185 /* Check for garbage after the valid input. */
1186 if (num_end
!= str_end
) {
1187 DBG("utils_parse_time_suffix: Garbage after time string.");
1192 *time_us
= base_time
* multiplier
;
1194 /* Check for overflow */
1195 if ((*time_us
/ multiplier
) != base_time
) {
1196 DBG("utils_parse_time_suffix: oops, overflow detected.");
1207 * fls: returns the position of the most significant bit.
1208 * Returns 0 if no bit is set, else returns the position of the most
1209 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1211 #if defined(__i386) || defined(__x86_64)
1212 static inline unsigned int fls_u32(uint32_t x
)
1216 asm("bsrl %1,%0\n\t"
1220 : "=r" (r
) : "rm" (x
));
1226 #if defined(__x86_64)
1228 unsigned int fls_u64(uint64_t x
)
1232 asm("bsrq %1,%0\n\t"
1236 : "=r" (r
) : "rm" (x
));
1243 static __attribute__((unused
))
1244 unsigned int fls_u64(uint64_t x
)
1246 unsigned int r
= 64;
1251 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1255 if (!(x
& 0xFFFF000000000000ULL
)) {
1259 if (!(x
& 0xFF00000000000000ULL
)) {
1263 if (!(x
& 0xF000000000000000ULL
)) {
1267 if (!(x
& 0xC000000000000000ULL
)) {
1271 if (!(x
& 0x8000000000000000ULL
)) {
1280 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1282 unsigned int r
= 32;
1287 if (!(x
& 0xFFFF0000U
)) {
1291 if (!(x
& 0xFF000000U
)) {
1295 if (!(x
& 0xF0000000U
)) {
1299 if (!(x
& 0xC0000000U
)) {
1303 if (!(x
& 0x80000000U
)) {
1312 * Return the minimum order for which x <= (1UL << order).
1313 * Return -1 if x is 0.
1316 int utils_get_count_order_u32(uint32_t x
)
1322 return fls_u32(x
- 1);
1326 * Return the minimum order for which x <= (1UL << order).
1327 * Return -1 if x is 0.
1330 int utils_get_count_order_u64(uint64_t x
)
1336 return fls_u64(x
- 1);
1340 * Obtain the value of LTTNG_HOME environment variable, if exists.
1341 * Otherwise returns the value of HOME.
1344 char *utils_get_home_dir(void)
1349 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1353 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1358 /* Fallback on the password file entry. */
1359 pwd
= getpwuid(getuid());
1365 DBG3("Home directory is '%s'", val
);
1372 * Get user's home directory. Dynamically allocated, must be freed
1376 char *utils_get_user_home_dir(uid_t uid
)
1379 struct passwd
*result
;
1380 char *home_dir
= NULL
;
1385 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1390 buf
= zmalloc(buflen
);
1395 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1396 if (ret
|| !result
) {
1397 if (ret
== ERANGE
) {
1405 home_dir
= strdup(pwd
.pw_dir
);
1412 * With the given format, fill dst with the time of len maximum siz.
1414 * Return amount of bytes set in the buffer or else 0 on error.
1417 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1421 struct tm
*timeinfo
;
1426 /* Get date and time for session path */
1428 timeinfo
= localtime(&rawtime
);
1429 ret
= strftime(dst
, len
, format
, timeinfo
);
1431 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1439 * Return the group ID matching name, else 0 if it cannot be found.
1442 gid_t
utils_get_group_id(const char *name
)
1446 grp
= getgrnam(name
);
1448 static volatile int warn_once
;
1451 WARN("No tracing group detected");
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
);