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 <common/string-utils/format.h>
44 #include <lttng/constant.h>
50 #define PROC_MEMINFO_PATH "/proc/meminfo"
51 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
52 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
54 /* The length of the longest field of `/proc/meminfo`. */
55 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
57 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
58 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
60 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
64 * Return a partial realpath(3) of the path even if the full path does not
65 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
66 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
67 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
68 * point directory does not exist.
69 * In case resolved_path is NULL, the string returned was allocated in the
70 * function and thus need to be freed by the caller. The size argument allows
71 * to specify the size of the resolved_path argument if given, or the size to
75 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
77 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
78 const char *next
, *prev
, *end
;
86 * Identify the end of the path, we don't want to treat the
87 * last char if it is a '/', we will just keep it on the side
88 * to be added at the end, and return a value coherent with
89 * the path given as argument
91 end
= path
+ strlen(path
);
92 if (*(end
-1) == '/') {
96 /* Initiate the values of the pointers before looping */
99 /* Only to ensure try_path is not NULL to enter the while */
100 try_path
= (char *)next
;
102 /* Resolve the canonical path of the first part of the path */
103 while (try_path
!= NULL
&& next
!= end
) {
104 char *try_path_buf
= NULL
;
107 * If there is not any '/' left, we want to try with
110 next
= strpbrk(next
+ 1, "/");
115 /* Cut the part we will be trying to resolve */
116 cut_path
= lttng_strndup(path
, next
- path
);
117 if (cut_path
== NULL
) {
118 PERROR("lttng_strndup");
122 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
128 /* Try to resolve this part */
129 try_path
= realpath((char *) cut_path
, try_path_buf
);
130 if (try_path
== NULL
) {
133 * There was an error, we just want to be assured it
134 * is linked to an unexistent directory, if it's another
135 * reason, we spawn an error
139 /* Ignore the error */
142 PERROR("realpath (partial_realpath)");
147 /* Save the place we are before trying the next step */
150 try_path_prev
= try_path
;
154 /* Free the allocated memory */
159 /* Allocate memory for the resolved path if necessary */
160 if (resolved_path
== NULL
) {
161 resolved_path
= zmalloc(size
);
162 if (resolved_path
== NULL
) {
163 PERROR("zmalloc resolved path");
169 * If we were able to solve at least partially the path, we can concatenate
170 * what worked and what didn't work
172 if (try_path_prev
!= NULL
) {
173 /* If we risk to concatenate two '/', we remove one of them */
174 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
175 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
179 * Duplicate the memory used by prev in case resolved_path and
180 * path are pointers for the same memory space
182 cut_path
= strdup(prev
);
183 if (cut_path
== NULL
) {
188 /* Concatenate the strings */
189 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
191 /* Free the allocated memory */
195 try_path_prev
= NULL
;
197 * Else, we just copy the path in our resolved_path to
201 strncpy(resolved_path
, path
, size
);
204 /* Then we return the 'partially' resolved path */
205 return resolved_path
;
211 if (try_path_prev
!= try_path
) {
218 int expand_double_slashes_dot_and_dotdot(char *path
)
220 size_t expanded_path_len
, path_len
;
221 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
223 path_len
= strlen(path
);
224 path_last_char
= &path
[path_len
];
230 expanded_path_len
= 0;
232 /* We iterate over the provided path to expand the "//", "../" and "./" */
233 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
234 /* Find the next forward slash. */
235 size_t curr_token_len
;
237 if (curr_char
== path_last_char
) {
242 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
243 if (next_slash
== NULL
) {
244 /* Reached the end of the provided path. */
245 next_slash
= path_last_char
;
248 /* Compute how long is the previous token. */
249 curr_token_len
= next_slash
- curr_char
;
250 switch(curr_token_len
) {
253 * The pointer has not move meaning that curr_char is
254 * pointing to a slash. It that case there is no token
255 * to copy, so continue the iteration to find the next
261 * The pointer moved 1 character. Check if that
262 * character is a dot ('.'), if it is: omit it, else
263 * copy the token to the normalized path.
265 if (curr_char
[0] == '.') {
271 * The pointer moved 2 characters. Check if these
272 * characters are double dots ('..'). If that is the
273 * case, we need to remove the last token of the
276 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
278 * Find the previous path component by
279 * using the memrchr function to find the
280 * previous forward slash and substract that
281 * len to the resulting path.
283 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
285 * If prev_slash is NULL, we reached the
286 * beginning of the path. We can't go back any
289 if (prev_slash
!= NULL
) {
290 expanded_path_len
= prev_slash
- path
;
300 * Copy the current token which is neither a '.' nor a '..'.
302 path
[expanded_path_len
++] = '/';
303 memcpy(&path
[expanded_path_len
], curr_char
, curr_token_len
);
304 expanded_path_len
+= curr_token_len
;
307 if (expanded_path_len
== 0) {
308 path
[expanded_path_len
++] = '/';
311 path
[expanded_path_len
] = '\0';
318 * Make a full resolution of the given path even if it doesn't exist.
319 * This function uses the utils_partial_realpath function to resolve
320 * symlinks and relatives paths at the start of the string, and
321 * implements functionnalities to resolve the './' and '../' strings
322 * in the middle of a path. This function is only necessary because
323 * realpath(3) does not accept to resolve unexistent paths.
324 * The returned string was allocated in the function, it is thus of
325 * the responsibility of the caller to free this memory.
328 char *_utils_expand_path(const char *path
, bool keep_symlink
)
331 char *absolute_path
= NULL
;
333 bool is_dot
, is_dotdot
;
340 /* Allocate memory for the absolute_path */
341 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
342 if (absolute_path
== NULL
) {
343 PERROR("zmalloc expand path");
347 if (path
[0] == '/') {
348 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
350 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
355 * This is a relative path. We need to get the present working
356 * directory and start the path walk from there.
358 char current_working_dir
[LTTNG_PATH_MAX
];
361 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
366 * Get the number of character in the CWD and allocate an array
367 * to can hold it and the path provided by the caller.
369 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
370 current_working_dir
, path
);
371 if (ret
>= LTTNG_PATH_MAX
) {
372 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
373 current_working_dir
, path
, LTTNG_PATH_MAX
);
379 /* Resolve partially our path */
380 absolute_path
= utils_partial_realpath(absolute_path
,
381 absolute_path
, LTTNG_PATH_MAX
);
384 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
389 /* Identify the last token */
390 last_token
= strrchr(absolute_path
, '/');
392 /* Verify that this token is not a relative path */
393 is_dotdot
= (strcmp(last_token
, "/..") == 0);
394 is_dot
= (strcmp(last_token
, "/.") == 0);
396 /* If it is, take action */
397 if (is_dot
|| is_dotdot
) {
398 /* For both, remove this token */
401 /* If it was a reference to parent directory, go back one more time */
403 last_token
= strrchr(absolute_path
, '/');
405 /* If there was only one level left, we keep the first '/' */
406 if (last_token
== absolute_path
) {
414 return absolute_path
;
421 char *utils_expand_path(const char *path
)
423 return _utils_expand_path(path
, true);
427 char *utils_expand_path_keep_symlink(const char *path
)
429 return _utils_expand_path(path
, false);
432 * Create a pipe in dst.
435 int utils_create_pipe(int *dst
)
445 PERROR("create pipe");
452 * Create pipe and set CLOEXEC flag to both fd.
454 * Make sure the pipe opened by this function are closed at some point. Use
455 * utils_close_pipe().
458 int utils_create_pipe_cloexec(int *dst
)
466 ret
= utils_create_pipe(dst
);
471 for (i
= 0; i
< 2; i
++) {
472 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
474 PERROR("fcntl pipe cloexec");
484 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
486 * Make sure the pipe opened by this function are closed at some point. Use
487 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
488 * support OSes other than Linux 2.6.23+.
491 int utils_create_pipe_cloexec_nonblock(int *dst
)
499 ret
= utils_create_pipe(dst
);
504 for (i
= 0; i
< 2; i
++) {
505 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
507 PERROR("fcntl pipe cloexec");
511 * Note: we override any flag that could have been
512 * previously set on the fd.
514 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
516 PERROR("fcntl pipe nonblock");
526 * Close both read and write side of the pipe.
529 void utils_close_pipe(int *src
)
537 for (i
= 0; i
< 2; i
++) {
545 PERROR("close pipe");
551 * Create a new string using two strings range.
554 char *utils_strdupdelim(const char *begin
, const char *end
)
558 str
= zmalloc(end
- begin
+ 1);
560 PERROR("zmalloc strdupdelim");
564 memcpy(str
, begin
, end
- begin
);
565 str
[end
- begin
] = '\0';
572 * Set CLOEXEC flag to the give file descriptor.
575 int utils_set_fd_cloexec(int fd
)
584 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
586 PERROR("fcntl cloexec");
595 * Create pid file to the given path and filename.
598 int utils_create_pid_file(pid_t pid
, const char *filepath
)
605 fp
= fopen(filepath
, "w");
607 PERROR("open pid file %s", filepath
);
612 ret
= fprintf(fp
, "%d\n", (int) pid
);
614 PERROR("fprintf pid file");
621 DBG("Pid %d written in file %s", (int) pid
, filepath
);
628 * Create lock file to the given path and filename.
629 * Returns the associated file descriptor, -1 on error.
632 int utils_create_lock_file(const char *filepath
)
640 memset(&lock
, 0, sizeof(lock
));
641 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
644 PERROR("open lock file %s", filepath
);
650 * Attempt to lock the file. If this fails, there is
651 * already a process using the same lock file running
652 * and we should exit.
654 lock
.l_whence
= SEEK_SET
;
655 lock
.l_type
= F_WRLCK
;
657 ret
= fcntl(fd
, F_SETLK
, &lock
);
659 PERROR("fcntl lock file");
660 ERR("Could not get lock file %s, another instance is running.",
663 PERROR("close lock file");
674 * Create directory using the given path and mode.
676 * On success, return 0 else a negative error code.
679 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
682 struct lttng_directory_handle handle
;
683 const struct lttng_credentials creds
= {
688 ret
= lttng_directory_handle_init(&handle
, NULL
);
692 ret
= lttng_directory_handle_create_subdirectory_as_user(
694 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
695 lttng_directory_handle_fini(&handle
);
701 * Recursively create directory using the given path and mode, under the
702 * provided uid and gid.
704 * On success, return 0 else a negative error code.
707 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
710 struct lttng_directory_handle handle
;
711 const struct lttng_credentials creds
= {
716 ret
= lttng_directory_handle_init(&handle
, NULL
);
720 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
722 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
723 lttng_directory_handle_fini(&handle
);
729 * out_stream_path is the output parameter.
731 * Return 0 on success or else a negative value.
734 int utils_stream_file_path(const char *path_name
, const char *file_name
,
735 uint64_t size
, uint64_t count
, const char *suffix
,
736 char *out_stream_path
, size_t stream_path_len
)
739 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
740 const char *path_separator
;
742 if (path_name
&& path_name
[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 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 * Create the stream file on disk.
771 * Return 0 on success or else a negative value.
774 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
775 uint64_t count
, int uid
, int gid
, char *suffix
)
777 int ret
, flags
, mode
;
778 char path
[LTTNG_PATH_MAX
];
780 ret
= utils_stream_file_path(path_name
, file_name
,
781 size
, count
, suffix
, path
, sizeof(path
));
787 * With the session rotation feature on the relay, we might need to seek
788 * and truncate a tracefile, so we need read and write access.
790 flags
= O_RDWR
| O_CREAT
| O_TRUNC
;
791 /* Open with 660 mode */
792 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
794 if (uid
< 0 || gid
< 0) {
795 ret
= open(path
, flags
, mode
);
797 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
800 PERROR("open stream path %s", path
);
807 * Unlink the stream tracefile from disk.
809 * Return 0 on success or else a negative value.
812 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
813 uint64_t count
, int uid
, int gid
, char *suffix
)
816 char path
[LTTNG_PATH_MAX
];
818 ret
= utils_stream_file_path(path_name
, file_name
, size
, count
, suffix
,
823 if (uid
< 0 || gid
< 0) {
826 ret
= run_as_unlink(path
, uid
, gid
);
832 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
837 * Parse a string that represents a size in human readable format. It
838 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
840 * The suffix multiply the integer by:
845 * @param str The string to parse.
846 * @param size Pointer to a uint64_t that will be filled with the
849 * @return 0 on success, -1 on failure.
852 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
861 DBG("utils_parse_size_suffix: received a NULL string.");
866 /* strtoull will accept a negative number, but we don't want to. */
867 if (strchr(str
, '-') != NULL
) {
868 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
873 /* str_end will point to the \0 */
874 str_end
= str
+ strlen(str
);
876 base_size
= strtoull(str
, &num_end
, 0);
878 PERROR("utils_parse_size_suffix strtoull");
883 if (num_end
== str
) {
884 /* strtoull parsed nothing, not good. */
885 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
890 /* Check if a prefix is present. */
908 DBG("utils_parse_size_suffix: invalid suffix.");
913 /* Check for garbage after the valid input. */
914 if (num_end
!= str_end
) {
915 DBG("utils_parse_size_suffix: Garbage after size string.");
920 *size
= base_size
<< shift
;
922 /* Check for overflow */
923 if ((*size
>> shift
) != base_size
) {
924 DBG("utils_parse_size_suffix: oops, overflow detected.");
935 * Parse a string that represents a time in human readable format. It
936 * supports decimal integers suffixed by:
937 * "us" for microsecond,
938 * "ms" for millisecond,
943 * The suffix multiply the integer by:
950 * Note that unit-less numbers are assumed to be microseconds.
952 * @param str The string to parse, assumed to be NULL-terminated.
953 * @param time_us Pointer to a uint64_t that will be filled with the
954 * resulting time in microseconds.
956 * @return 0 on success, -1 on failure.
959 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
963 uint64_t multiplier
= 1;
968 DBG("utils_parse_time_suffix: received a NULL string.");
973 /* strtoull will accept a negative number, but we don't want to. */
974 if (strchr(str
, '-') != NULL
) {
975 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
980 /* str_end will point to the \0 */
981 str_end
= str
+ strlen(str
);
983 base_time
= strtoull(str
, &num_end
, 10);
985 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
990 if (num_end
== str
) {
991 /* strtoull parsed nothing, not good. */
992 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
997 /* Check if a prefix is present. */
1003 * Skip the "us" if the string matches the "us" suffix,
1004 * otherwise let the check for the end of the string handle
1005 * the error reporting.
1007 if (*(num_end
+ 1) == 's') {
1012 if (*(num_end
+ 1) == 's') {
1013 /* Millisecond (ms) */
1014 multiplier
= USEC_PER_MSEC
;
1019 multiplier
= USEC_PER_MINUTE
;
1025 multiplier
= USEC_PER_SEC
;
1030 multiplier
= USEC_PER_HOURS
;
1036 DBG("utils_parse_time_suffix: invalid suffix.");
1041 /* Check for garbage after the valid input. */
1042 if (num_end
!= str_end
) {
1043 DBG("utils_parse_time_suffix: Garbage after time string.");
1048 *time_us
= base_time
* multiplier
;
1050 /* Check for overflow */
1051 if ((*time_us
/ multiplier
) != base_time
) {
1052 DBG("utils_parse_time_suffix: oops, overflow detected.");
1063 * fls: returns the position of the most significant bit.
1064 * Returns 0 if no bit is set, else returns the position of the most
1065 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1067 #if defined(__i386) || defined(__x86_64)
1068 static inline unsigned int fls_u32(uint32_t x
)
1072 asm("bsrl %1,%0\n\t"
1076 : "=r" (r
) : "rm" (x
));
1082 #if defined(__x86_64)
1084 unsigned int fls_u64(uint64_t x
)
1088 asm("bsrq %1,%0\n\t"
1092 : "=r" (r
) : "rm" (x
));
1099 static __attribute__((unused
))
1100 unsigned int fls_u64(uint64_t x
)
1102 unsigned int r
= 64;
1107 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1111 if (!(x
& 0xFFFF000000000000ULL
)) {
1115 if (!(x
& 0xFF00000000000000ULL
)) {
1119 if (!(x
& 0xF000000000000000ULL
)) {
1123 if (!(x
& 0xC000000000000000ULL
)) {
1127 if (!(x
& 0x8000000000000000ULL
)) {
1136 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1138 unsigned int r
= 32;
1143 if (!(x
& 0xFFFF0000U
)) {
1147 if (!(x
& 0xFF000000U
)) {
1151 if (!(x
& 0xF0000000U
)) {
1155 if (!(x
& 0xC0000000U
)) {
1159 if (!(x
& 0x80000000U
)) {
1168 * Return the minimum order for which x <= (1UL << order).
1169 * Return -1 if x is 0.
1172 int utils_get_count_order_u32(uint32_t x
)
1178 return fls_u32(x
- 1);
1182 * Return the minimum order for which x <= (1UL << order).
1183 * Return -1 if x is 0.
1186 int utils_get_count_order_u64(uint64_t x
)
1192 return fls_u64(x
- 1);
1196 * Obtain the value of LTTNG_HOME environment variable, if exists.
1197 * Otherwise returns the value of HOME.
1200 const char *utils_get_home_dir(void)
1205 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1209 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1214 /* Fallback on the password file entry. */
1215 pwd
= getpwuid(getuid());
1221 DBG3("Home directory is '%s'", val
);
1228 * Get user's home directory. Dynamically allocated, must be freed
1232 char *utils_get_user_home_dir(uid_t uid
)
1235 struct passwd
*result
;
1236 char *home_dir
= NULL
;
1241 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1246 buf
= zmalloc(buflen
);
1251 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1252 if (ret
|| !result
) {
1253 if (ret
== ERANGE
) {
1261 home_dir
= strdup(pwd
.pw_dir
);
1268 * With the given format, fill dst with the time of len maximum siz.
1270 * Return amount of bytes set in the buffer or else 0 on error.
1273 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1277 struct tm
*timeinfo
;
1282 /* Get date and time for session path */
1284 timeinfo
= localtime(&rawtime
);
1285 ret
= strftime(dst
, len
, format
, timeinfo
);
1287 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1295 * Return 0 on success and set *gid to the group_ID matching the passed name.
1296 * Else -1 if it cannot be found or an error occurred.
1299 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1301 static volatile int warn_once
;
1306 struct group
*result
;
1307 struct lttng_dynamic_buffer buffer
;
1309 /* Get the system limit, if it exists. */
1310 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1311 if (sys_len
== -1) {
1314 len
= (size_t) sys_len
;
1317 lttng_dynamic_buffer_init(&buffer
);
1318 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1320 ERR("Failed to allocate group info buffer");
1325 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1326 const size_t new_len
= 2 * buffer
.size
;
1328 /* Buffer is not big enough, increase its size. */
1329 if (new_len
< buffer
.size
) {
1330 ERR("Group info buffer size overflow");
1335 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1337 ERR("Failed to grow group info buffer to %zu bytes",
1344 PERROR("Failed to get group file entry for group name \"%s\"",
1350 /* Group not found. */
1356 *gid
= result
->gr_gid
;
1360 if (ret
&& warn
&& !warn_once
) {
1361 WARN("No tracing group detected");
1364 lttng_dynamic_buffer_reset(&buffer
);
1369 * Return a newly allocated option string. This string is to be used as the
1370 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1371 * of elements in the long_options array. Returns NULL if the string's
1375 char *utils_generate_optstring(const struct option
*long_options
,
1379 size_t string_len
= opt_count
, str_pos
= 0;
1383 * Compute the necessary string length. One letter per option, two when an
1384 * argument is necessary, and a trailing NULL.
1386 for (i
= 0; i
< opt_count
; i
++) {
1387 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1390 optstring
= zmalloc(string_len
);
1395 for (i
= 0; i
< opt_count
; i
++) {
1396 if (!long_options
[i
].name
) {
1397 /* Got to the trailing NULL element */
1401 if (long_options
[i
].val
!= '\0') {
1402 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1403 if (long_options
[i
].has_arg
) {
1404 optstring
[str_pos
++] = ':';
1414 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1415 * any file. Try to rmdir any empty directory within the hierarchy.
1418 int utils_recursive_rmdir(const char *path
)
1421 struct lttng_directory_handle handle
;
1423 ret
= lttng_directory_handle_init(&handle
, NULL
);
1427 ret
= lttng_directory_handle_remove_subdirectory(&handle
, path
);
1428 lttng_directory_handle_fini(&handle
);
1434 int utils_truncate_stream_file(int fd
, off_t length
)
1439 ret
= ftruncate(fd
, length
);
1441 PERROR("ftruncate");
1444 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1445 if (lseek_ret
< 0) {
1454 static const char *get_man_bin_path(void)
1456 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1459 return env_man_path
;
1462 return DEFAULT_MAN_BIN_PATH
;
1466 int utils_show_help(int section
, const char *page_name
,
1467 const char *help_msg
)
1469 char section_string
[8];
1470 const char *man_bin_path
= get_man_bin_path();
1474 printf("%s", help_msg
);
1478 /* Section integer -> section string */
1479 ret
= sprintf(section_string
, "%d", section
);
1480 assert(ret
> 0 && ret
< 8);
1483 * Execute man pager.
1485 * We provide -M to man here because LTTng-tools can
1486 * be installed outside /usr, in which case its man pages are
1487 * not located in the default /usr/share/man directory.
1489 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1490 section_string
, page_name
, NULL
);
1497 int read_proc_meminfo_field(const char *field
, size_t *value
)
1501 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1503 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1504 if (!proc_meminfo
) {
1505 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1511 * Read the contents of /proc/meminfo line by line to find the right
1514 while (!feof(proc_meminfo
)) {
1515 unsigned long value_kb
;
1517 ret
= fscanf(proc_meminfo
,
1518 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1522 * fscanf() returning EOF can indicate EOF or an error.
1524 if (ferror(proc_meminfo
)) {
1525 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1530 if (ret
== 2 && strcmp(name
, field
) == 0) {
1532 * This number is displayed in kilo-bytes. Return the
1535 *value
= ((size_t) value_kb
) * 1024;
1540 /* Reached the end of the file without finding the right field. */
1544 fclose(proc_meminfo
);
1550 * Returns an estimate of the number of bytes of memory available based on the
1551 * the information in `/proc/meminfo`. The number returned by this function is
1555 int utils_get_memory_available(size_t *value
)
1557 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1561 * Returns the total size of the memory on the system in bytes based on the
1562 * the information in `/proc/meminfo`.
1565 int utils_get_memory_total(size_t *value
)
1567 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);