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
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)
54 * Return a partial realpath(3) of the path even if the full path does not
55 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
56 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
57 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
58 * point directory does not exist.
59 * In case resolved_path is NULL, the string returned was allocated in the
60 * function and thus need to be freed by the caller. The size argument allows
61 * to specify the size of the resolved_path argument if given, or the size to
65 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
67 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
68 const char *next
, *prev
, *end
;
76 * Identify the end of the path, we don't want to treat the
77 * last char if it is a '/', we will just keep it on the side
78 * to be added at the end, and return a value coherent with
79 * the path given as argument
81 end
= path
+ strlen(path
);
82 if (*(end
-1) == '/') {
86 /* Initiate the values of the pointers before looping */
89 /* Only to ensure try_path is not NULL to enter the while */
90 try_path
= (char *)next
;
92 /* Resolve the canonical path of the first part of the path */
93 while (try_path
!= NULL
&& next
!= end
) {
94 char *try_path_buf
= NULL
;
97 * If there is not any '/' left, we want to try with
100 next
= strpbrk(next
+ 1, "/");
105 /* Cut the part we will be trying to resolve */
106 cut_path
= lttng_strndup(path
, next
- path
);
107 if (cut_path
== NULL
) {
108 PERROR("lttng_strndup");
112 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
118 /* Try to resolve this part */
119 try_path
= realpath((char *) cut_path
, try_path_buf
);
120 if (try_path
== NULL
) {
123 * There was an error, we just want to be assured it
124 * is linked to an unexistent directory, if it's another
125 * reason, we spawn an error
129 /* Ignore the error */
132 PERROR("realpath (partial_realpath)");
137 /* Save the place we are before trying the next step */
140 try_path_prev
= try_path
;
144 /* Free the allocated memory */
149 /* Allocate memory for the resolved path if necessary */
150 if (resolved_path
== NULL
) {
151 resolved_path
= zmalloc(size
);
152 if (resolved_path
== NULL
) {
153 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
, size
, "%s%s", try_path_prev
, cut_path
);
181 /* Free the allocated memory */
185 try_path_prev
= NULL
;
187 * Else, we just copy the path in our resolved_path to
191 strncpy(resolved_path
, path
, size
);
194 /* Then we return the 'partially' resolved path */
195 return resolved_path
;
201 if (try_path_prev
!= try_path
) {
208 int expand_double_slashes_dot_and_dotdot(char *path
)
210 size_t expanded_path_len
, path_len
;
211 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
213 path_len
= strlen(path
);
214 path_last_char
= &path
[path_len
];
220 expanded_path_len
= 0;
222 /* We iterate over the provided path to expand the "//", "../" and "./" */
223 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
224 /* Find the next forward slash. */
225 size_t curr_token_len
;
227 if (curr_char
== path_last_char
) {
232 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
233 if (next_slash
== NULL
) {
234 /* Reached the end of the provided path. */
235 next_slash
= path_last_char
;
238 /* Compute how long is the previous token. */
239 curr_token_len
= next_slash
- curr_char
;
240 switch(curr_token_len
) {
243 * The pointer has not move meaning that curr_char is
244 * pointing to a slash. It that case there is no token
245 * to copy, so continue the iteration to find the next
251 * The pointer moved 1 character. Check if that
252 * character is a dot ('.'), if it is: omit it, else
253 * copy the token to the normalized path.
255 if (curr_char
[0] == '.') {
261 * The pointer moved 2 characters. Check if these
262 * characters are double dots ('..'). If that is the
263 * case, we need to remove the last token of the
266 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
268 * Find the previous path component by
269 * using the memrchr function to find the
270 * previous forward slash and substract that
271 * len to the resulting path.
273 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
275 * If prev_slash is NULL, we reached the
276 * beginning of the path. We can't go back any
279 if (prev_slash
!= NULL
) {
280 expanded_path_len
= prev_slash
- path
;
290 * Copy the current token which is neither a '.' nor a '..'.
292 path
[expanded_path_len
++] = '/';
293 memcpy(&path
[expanded_path_len
], curr_char
, curr_token_len
);
294 expanded_path_len
+= curr_token_len
;
297 if (expanded_path_len
== 0) {
298 path
[expanded_path_len
++] = '/';
301 path
[expanded_path_len
] = '\0';
308 * Make a full resolution of the given path even if it doesn't exist.
309 * This function uses the utils_partial_realpath function to resolve
310 * symlinks and relatives paths at the start of the string, and
311 * implements functionnalities to resolve the './' and '../' strings
312 * in the middle of a path. This function is only necessary because
313 * realpath(3) does not accept to resolve unexistent paths.
314 * The returned string was allocated in the function, it is thus of
315 * the responsibility of the caller to free this memory.
318 char *_utils_expand_path(const char *path
, bool keep_symlink
)
321 char *absolute_path
= NULL
;
323 bool is_dot
, is_dotdot
;
330 /* Allocate memory for the absolute_path */
331 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
332 if (absolute_path
== NULL
) {
333 PERROR("zmalloc expand path");
337 if (path
[0] == '/') {
338 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
340 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
345 * This is a relative path. We need to get the present working
346 * directory and start the path walk from there.
348 char current_working_dir
[LTTNG_PATH_MAX
];
351 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
356 * Get the number of character in the CWD and allocate an array
357 * to can hold it and the path provided by the caller.
359 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
360 current_working_dir
, path
);
361 if (ret
>= LTTNG_PATH_MAX
) {
362 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
363 current_working_dir
, path
, LTTNG_PATH_MAX
);
369 /* Resolve partially our path */
370 absolute_path
= utils_partial_realpath(absolute_path
,
371 absolute_path
, LTTNG_PATH_MAX
);
372 if (!absolute_path
) {
377 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
382 /* Identify the last token */
383 last_token
= strrchr(absolute_path
, '/');
385 /* Verify that this token is not a relative path */
386 is_dotdot
= (strcmp(last_token
, "/..") == 0);
387 is_dot
= (strcmp(last_token
, "/.") == 0);
389 /* If it is, take action */
390 if (is_dot
|| is_dotdot
) {
391 /* For both, remove this token */
394 /* If it was a reference to parent directory, go back one more time */
396 last_token
= strrchr(absolute_path
, '/');
398 /* If there was only one level left, we keep the first '/' */
399 if (last_token
== absolute_path
) {
407 return absolute_path
;
414 char *utils_expand_path(const char *path
)
416 return _utils_expand_path(path
, true);
420 char *utils_expand_path_keep_symlink(const char *path
)
422 return _utils_expand_path(path
, false);
425 * 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().
451 int utils_create_pipe_cloexec(int *dst
)
459 ret
= utils_create_pipe(dst
);
464 for (i
= 0; i
< 2; i
++) {
465 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
467 PERROR("fcntl pipe cloexec");
477 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
479 * Make sure the pipe opened by this function are closed at some point. Use
480 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
481 * support OSes other than Linux 2.6.23+.
484 int utils_create_pipe_cloexec_nonblock(int *dst
)
492 ret
= utils_create_pipe(dst
);
497 for (i
= 0; i
< 2; i
++) {
498 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
500 PERROR("fcntl pipe cloexec");
504 * Note: we override any flag that could have been
505 * previously set on the fd.
507 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
509 PERROR("fcntl pipe nonblock");
519 * Close both read and write side of the pipe.
522 void utils_close_pipe(int *src
)
530 for (i
= 0; i
< 2; i
++) {
538 PERROR("close pipe");
545 * Create a new string using two strings range.
548 char *utils_strdupdelim(const char *begin
, const char *end
)
552 str
= zmalloc(end
- begin
+ 1);
554 PERROR("zmalloc strdupdelim");
558 memcpy(str
, begin
, end
- begin
);
559 str
[end
- begin
] = '\0';
566 * Set CLOEXEC flag to the give file descriptor.
569 int utils_set_fd_cloexec(int fd
)
578 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
580 PERROR("fcntl cloexec");
589 * Create pid file to the given path and filename.
592 int utils_create_pid_file(pid_t pid
, const char *filepath
)
599 fp
= fopen(filepath
, "w");
601 PERROR("open pid file %s", filepath
);
606 ret
= fprintf(fp
, "%d\n", (int) pid
);
608 PERROR("fprintf pid file");
615 DBG("Pid %d written in file %s", (int) pid
, filepath
);
622 * Create lock file to the given path and filename.
623 * Returns the associated file descriptor, -1 on error.
626 int utils_create_lock_file(const char *filepath
)
634 memset(&lock
, 0, sizeof(lock
));
635 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
638 PERROR("open lock file %s", filepath
);
644 * Attempt to lock the file. If this fails, there is
645 * already a process using the same lock file running
646 * and we should exit.
648 lock
.l_whence
= SEEK_SET
;
649 lock
.l_type
= F_WRLCK
;
651 ret
= fcntl(fd
, F_SETLK
, &lock
);
653 PERROR("fcntl lock file");
654 ERR("Could not get lock file %s, another instance is running.",
657 PERROR("close lock file");
668 * Create directory using the given path and mode.
670 * On success, return 0 else a negative error code.
673 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
676 struct lttng_directory_handle
*handle
;
677 const struct lttng_credentials creds
= {
682 handle
= lttng_directory_handle_create(NULL
);
687 ret
= lttng_directory_handle_create_subdirectory_as_user(
689 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
691 lttng_directory_handle_put(handle
);
696 * Recursively create directory using the given path and mode, under the
697 * provided uid and gid.
699 * On success, return 0 else a negative error code.
702 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
705 struct lttng_directory_handle
*handle
;
706 const struct lttng_credentials creds
= {
711 handle
= lttng_directory_handle_create(NULL
);
716 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
718 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
720 lttng_directory_handle_put(handle
);
725 * out_stream_path is the output parameter.
727 * Return 0 on success or else a negative value.
730 int utils_stream_file_path(const char *path_name
, const char *file_name
,
731 uint64_t size
, uint64_t count
, const char *suffix
,
732 char *out_stream_path
, size_t stream_path_len
)
735 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
736 const char *path_separator
;
738 if (path_name
&& (path_name
[0] == '\0' ||
739 path_name
[strlen(path_name
) - 1] == '/')) {
742 path_separator
= "/";
745 path_name
= path_name
? : "";
746 suffix
= suffix
? : "";
748 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
750 assert(ret
> 0 && ret
< sizeof(count_str
));
753 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
754 path_name
, path_separator
, file_name
, count_str
,
756 if (ret
< 0 || ret
>= stream_path_len
) {
757 ERR("Truncation occurred while formatting stream path");
766 * Parse a string that represents a size in human readable format. It
767 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
769 * The suffix multiply the integer by:
774 * @param str The string to parse.
775 * @param size Pointer to a uint64_t that will be filled with the
778 * @return 0 on success, -1 on failure.
781 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
790 DBG("utils_parse_size_suffix: received a NULL string.");
795 /* strtoull will accept a negative number, but we don't want to. */
796 if (strchr(str
, '-') != NULL
) {
797 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
802 /* str_end will point to the \0 */
803 str_end
= str
+ strlen(str
);
805 base_size
= strtoull(str
, &num_end
, 0);
807 PERROR("utils_parse_size_suffix strtoull");
812 if (num_end
== str
) {
813 /* strtoull parsed nothing, not good. */
814 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
819 /* Check if a prefix is present. */
837 DBG("utils_parse_size_suffix: invalid suffix.");
842 /* Check for garbage after the valid input. */
843 if (num_end
!= str_end
) {
844 DBG("utils_parse_size_suffix: Garbage after size string.");
849 *size
= base_size
<< shift
;
851 /* Check for overflow */
852 if ((*size
>> shift
) != base_size
) {
853 DBG("utils_parse_size_suffix: oops, overflow detected.");
864 * Parse a string that represents a time in human readable format. It
865 * supports decimal integers suffixed by:
866 * "us" for microsecond,
867 * "ms" for millisecond,
872 * The suffix multiply the integer by:
879 * Note that unit-less numbers are assumed to be microseconds.
881 * @param str The string to parse, assumed to be NULL-terminated.
882 * @param time_us Pointer to a uint64_t that will be filled with the
883 * resulting time in microseconds.
885 * @return 0 on success, -1 on failure.
888 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
892 uint64_t multiplier
= 1;
897 DBG("utils_parse_time_suffix: received a NULL string.");
902 /* strtoull will accept a negative number, but we don't want to. */
903 if (strchr(str
, '-') != NULL
) {
904 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
909 /* str_end will point to the \0 */
910 str_end
= str
+ strlen(str
);
912 base_time
= strtoull(str
, &num_end
, 10);
914 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
919 if (num_end
== str
) {
920 /* strtoull parsed nothing, not good. */
921 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
926 /* Check if a prefix is present. */
932 * Skip the "us" if the string matches the "us" suffix,
933 * otherwise let the check for the end of the string handle
934 * the error reporting.
936 if (*(num_end
+ 1) == 's') {
941 if (*(num_end
+ 1) == 's') {
942 /* Millisecond (ms) */
943 multiplier
= USEC_PER_MSEC
;
948 multiplier
= USEC_PER_MINUTE
;
954 multiplier
= USEC_PER_SEC
;
959 multiplier
= USEC_PER_HOURS
;
965 DBG("utils_parse_time_suffix: invalid suffix.");
970 /* Check for garbage after the valid input. */
971 if (num_end
!= str_end
) {
972 DBG("utils_parse_time_suffix: Garbage after time string.");
977 *time_us
= base_time
* multiplier
;
979 /* Check for overflow */
980 if ((*time_us
/ multiplier
) != base_time
) {
981 DBG("utils_parse_time_suffix: oops, overflow detected.");
992 * fls: returns the position of the most significant bit.
993 * Returns 0 if no bit is set, else returns the position of the most
994 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
996 #if defined(__i386) || defined(__x86_64)
997 static inline unsigned int fls_u32(uint32_t x
)
1001 asm("bsrl %1,%0\n\t"
1005 : "=r" (r
) : "rm" (x
));
1011 #if defined(__x86_64) && defined(__LP64__)
1013 unsigned int fls_u64(uint64_t x
)
1017 asm("bsrq %1,%0\n\t"
1021 : "=r" (r
) : "rm" (x
));
1028 static __attribute__((unused
))
1029 unsigned int fls_u64(uint64_t x
)
1031 unsigned int r
= 64;
1036 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1040 if (!(x
& 0xFFFF000000000000ULL
)) {
1044 if (!(x
& 0xFF00000000000000ULL
)) {
1048 if (!(x
& 0xF000000000000000ULL
)) {
1052 if (!(x
& 0xC000000000000000ULL
)) {
1056 if (!(x
& 0x8000000000000000ULL
)) {
1065 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1067 unsigned int r
= 32;
1072 if (!(x
& 0xFFFF0000U
)) {
1076 if (!(x
& 0xFF000000U
)) {
1080 if (!(x
& 0xF0000000U
)) {
1084 if (!(x
& 0xC0000000U
)) {
1088 if (!(x
& 0x80000000U
)) {
1097 * Return the minimum order for which x <= (1UL << order).
1098 * Return -1 if x is 0.
1101 int utils_get_count_order_u32(uint32_t x
)
1107 return fls_u32(x
- 1);
1111 * Return the minimum order for which x <= (1UL << order).
1112 * Return -1 if x is 0.
1115 int utils_get_count_order_u64(uint64_t x
)
1121 return fls_u64(x
- 1);
1125 * Obtain the value of LTTNG_HOME environment variable, if exists.
1126 * Otherwise returns the value of HOME.
1129 const char *utils_get_home_dir(void)
1134 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1138 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1143 /* Fallback on the password file entry. */
1144 pwd
= getpwuid(getuid());
1150 DBG3("Home directory is '%s'", val
);
1157 * Get user's home directory. Dynamically allocated, must be freed
1161 char *utils_get_user_home_dir(uid_t uid
)
1164 struct passwd
*result
;
1165 char *home_dir
= NULL
;
1170 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1175 buf
= zmalloc(buflen
);
1180 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1181 if (ret
|| !result
) {
1182 if (ret
== ERANGE
) {
1190 home_dir
= strdup(pwd
.pw_dir
);
1197 * With the given format, fill dst with the time of len maximum siz.
1199 * Return amount of bytes set in the buffer or else 0 on error.
1202 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1206 struct tm
*timeinfo
;
1211 /* Get date and time for session path */
1213 timeinfo
= localtime(&rawtime
);
1214 ret
= strftime(dst
, len
, format
, timeinfo
);
1216 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1224 * Return 0 on success and set *gid to the group_ID matching the passed name.
1225 * Else -1 if it cannot be found or an error occurred.
1228 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1230 static volatile int warn_once
;
1235 struct group
*result
;
1236 struct lttng_dynamic_buffer buffer
;
1238 /* Get the system limit, if it exists. */
1239 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1240 if (sys_len
== -1) {
1243 len
= (size_t) sys_len
;
1246 lttng_dynamic_buffer_init(&buffer
);
1247 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1249 ERR("Failed to allocate group info buffer");
1254 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1255 const size_t new_len
= 2 * buffer
.size
;
1257 /* Buffer is not big enough, increase its size. */
1258 if (new_len
< buffer
.size
) {
1259 ERR("Group info buffer size overflow");
1264 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1266 ERR("Failed to grow group info buffer to %zu bytes",
1273 PERROR("Failed to get group file entry for group name \"%s\"",
1279 /* Group not found. */
1285 *gid
= result
->gr_gid
;
1289 if (ret
&& warn
&& !warn_once
) {
1290 WARN("No tracing group detected");
1293 lttng_dynamic_buffer_reset(&buffer
);
1298 * Return a newly allocated option string. This string is to be used as the
1299 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1300 * of elements in the long_options array. Returns NULL if the string's
1304 char *utils_generate_optstring(const struct option
*long_options
,
1308 size_t string_len
= opt_count
, str_pos
= 0;
1312 * Compute the necessary string length. One letter per option, two when an
1313 * argument is necessary, and a trailing NULL.
1315 for (i
= 0; i
< opt_count
; i
++) {
1316 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1319 optstring
= zmalloc(string_len
);
1324 for (i
= 0; i
< opt_count
; i
++) {
1325 if (!long_options
[i
].name
) {
1326 /* Got to the trailing NULL element */
1330 if (long_options
[i
].val
!= '\0') {
1331 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1332 if (long_options
[i
].has_arg
) {
1333 optstring
[str_pos
++] = ':';
1343 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1344 * any file. Try to rmdir any empty directory within the hierarchy.
1347 int utils_recursive_rmdir(const char *path
)
1350 struct lttng_directory_handle
*handle
;
1352 handle
= lttng_directory_handle_create(NULL
);
1357 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1359 lttng_directory_handle_put(handle
);
1364 int utils_truncate_stream_file(int fd
, off_t length
)
1369 ret
= ftruncate(fd
, length
);
1371 PERROR("ftruncate");
1374 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1375 if (lseek_ret
< 0) {
1384 static const char *get_man_bin_path(void)
1386 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1389 return env_man_path
;
1392 return DEFAULT_MAN_BIN_PATH
;
1396 int utils_show_help(int section
, const char *page_name
,
1397 const char *help_msg
)
1399 char section_string
[8];
1400 const char *man_bin_path
= get_man_bin_path();
1404 printf("%s", help_msg
);
1408 /* Section integer -> section string */
1409 ret
= sprintf(section_string
, "%d", section
);
1410 assert(ret
> 0 && ret
< 8);
1413 * Execute man pager.
1415 * We provide -M to man here because LTTng-tools can
1416 * be installed outside /usr, in which case its man pages are
1417 * not located in the default /usr/share/man directory.
1419 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1420 section_string
, page_name
, NULL
);
1427 int read_proc_meminfo_field(const char *field
, size_t *value
)
1431 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1433 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1434 if (!proc_meminfo
) {
1435 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1441 * Read the contents of /proc/meminfo line by line to find the right
1444 while (!feof(proc_meminfo
)) {
1445 unsigned long value_kb
;
1447 ret
= fscanf(proc_meminfo
,
1448 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1452 * fscanf() returning EOF can indicate EOF or an error.
1454 if (ferror(proc_meminfo
)) {
1455 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1460 if (ret
== 2 && strcmp(name
, field
) == 0) {
1462 * This number is displayed in kilo-bytes. Return the
1465 *value
= ((size_t) value_kb
) * 1024;
1470 /* Reached the end of the file without finding the right field. */
1474 fclose(proc_meminfo
);
1480 * Returns an estimate of the number of bytes of memory available based on the
1481 * the information in `/proc/meminfo`. The number returned by this function is
1485 int utils_get_memory_available(size_t *value
)
1487 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1491 * Returns the total size of the memory on the system in bytes based on the
1492 * the information in `/proc/meminfo`.
1495 int utils_get_memory_total(size_t *value
)
1497 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1501 int utils_change_working_directory(const char *path
)
1507 DBG("Changing working directory to \"%s\"", path
);
1510 PERROR("Failed to change working directory to \"%s\"", path
);
1514 /* Check for write access */
1515 if (access(path
, W_OK
)) {
1516 if (errno
== EACCES
) {
1518 * Do not treat this as an error since the permission
1519 * might change in the lifetime of the process
1521 DBG("Working directory \"%s\" is not writable", path
);
1523 PERROR("Failed to check if working directory \"%s\" is writable",