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");
544 * Create a new string using two strings range.
547 char *utils_strdupdelim(const char *begin
, const char *end
)
551 str
= zmalloc(end
- begin
+ 1);
553 PERROR("zmalloc strdupdelim");
557 memcpy(str
, begin
, end
- begin
);
558 str
[end
- begin
] = '\0';
565 * Set CLOEXEC flag to the give file descriptor.
568 int utils_set_fd_cloexec(int fd
)
577 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
579 PERROR("fcntl cloexec");
588 * Create pid file to the given path and filename.
591 int utils_create_pid_file(pid_t pid
, const char *filepath
)
598 fp
= fopen(filepath
, "w");
600 PERROR("open pid file %s", filepath
);
605 ret
= fprintf(fp
, "%d\n", (int) pid
);
607 PERROR("fprintf pid file");
614 DBG("Pid %d written in file %s", (int) pid
, filepath
);
621 * Create lock file to the given path and filename.
622 * Returns the associated file descriptor, -1 on error.
625 int utils_create_lock_file(const char *filepath
)
633 memset(&lock
, 0, sizeof(lock
));
634 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
637 PERROR("open lock file %s", filepath
);
643 * Attempt to lock the file. If this fails, there is
644 * already a process using the same lock file running
645 * and we should exit.
647 lock
.l_whence
= SEEK_SET
;
648 lock
.l_type
= F_WRLCK
;
650 ret
= fcntl(fd
, F_SETLK
, &lock
);
652 PERROR("fcntl lock file");
653 ERR("Could not get lock file %s, another instance is running.",
656 PERROR("close lock file");
667 * Create directory using the given path and mode.
669 * On success, return 0 else a negative error code.
672 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
675 struct lttng_directory_handle
*handle
;
676 const struct lttng_credentials creds
= {
681 handle
= lttng_directory_handle_create(NULL
);
686 ret
= lttng_directory_handle_create_subdirectory_as_user(
688 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
690 lttng_directory_handle_put(handle
);
695 * Recursively create directory using the given path and mode, under the
696 * provided uid and gid.
698 * On success, return 0 else a negative error code.
701 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
704 struct lttng_directory_handle
*handle
;
705 const struct lttng_credentials creds
= {
710 handle
= lttng_directory_handle_create(NULL
);
715 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
717 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
719 lttng_directory_handle_put(handle
);
724 * out_stream_path is the output parameter.
726 * Return 0 on success or else a negative value.
729 int utils_stream_file_path(const char *path_name
, const char *file_name
,
730 uint64_t size
, uint64_t count
, const char *suffix
,
731 char *out_stream_path
, size_t stream_path_len
)
734 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
735 const char *path_separator
;
737 if (path_name
&& (path_name
[0] == '\0' ||
738 path_name
[strlen(path_name
) - 1] == '/')) {
741 path_separator
= "/";
744 path_name
= path_name
? : "";
745 suffix
= suffix
? : "";
747 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
749 assert(ret
> 0 && ret
< sizeof(count_str
));
752 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
753 path_name
, path_separator
, file_name
, count_str
,
755 if (ret
< 0 || ret
>= stream_path_len
) {
756 ERR("Truncation occurred while formatting stream path");
765 * Parse a string that represents a size in human readable format. It
766 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
768 * The suffix multiply the integer by:
773 * @param str The string to parse.
774 * @param size Pointer to a uint64_t that will be filled with the
777 * @return 0 on success, -1 on failure.
780 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
789 DBG("utils_parse_size_suffix: received a NULL string.");
794 /* strtoull will accept a negative number, but we don't want to. */
795 if (strchr(str
, '-') != NULL
) {
796 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
801 /* str_end will point to the \0 */
802 str_end
= str
+ strlen(str
);
804 base_size
= strtoull(str
, &num_end
, 0);
806 PERROR("utils_parse_size_suffix strtoull");
811 if (num_end
== str
) {
812 /* strtoull parsed nothing, not good. */
813 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
818 /* Check if a prefix is present. */
836 DBG("utils_parse_size_suffix: invalid suffix.");
841 /* Check for garbage after the valid input. */
842 if (num_end
!= str_end
) {
843 DBG("utils_parse_size_suffix: Garbage after size string.");
848 *size
= base_size
<< shift
;
850 /* Check for overflow */
851 if ((*size
>> shift
) != base_size
) {
852 DBG("utils_parse_size_suffix: oops, overflow detected.");
863 * Parse a string that represents a time in human readable format. It
864 * supports decimal integers suffixed by:
865 * "us" for microsecond,
866 * "ms" for millisecond,
871 * The suffix multiply the integer by:
878 * Note that unit-less numbers are assumed to be microseconds.
880 * @param str The string to parse, assumed to be NULL-terminated.
881 * @param time_us Pointer to a uint64_t that will be filled with the
882 * resulting time in microseconds.
884 * @return 0 on success, -1 on failure.
887 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
891 uint64_t multiplier
= 1;
896 DBG("utils_parse_time_suffix: received a NULL string.");
901 /* strtoull will accept a negative number, but we don't want to. */
902 if (strchr(str
, '-') != NULL
) {
903 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
908 /* str_end will point to the \0 */
909 str_end
= str
+ strlen(str
);
911 base_time
= strtoull(str
, &num_end
, 10);
913 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
918 if (num_end
== str
) {
919 /* strtoull parsed nothing, not good. */
920 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
925 /* Check if a prefix is present. */
931 * Skip the "us" if the string matches the "us" suffix,
932 * otherwise let the check for the end of the string handle
933 * the error reporting.
935 if (*(num_end
+ 1) == 's') {
940 if (*(num_end
+ 1) == 's') {
941 /* Millisecond (ms) */
942 multiplier
= USEC_PER_MSEC
;
947 multiplier
= USEC_PER_MINUTE
;
953 multiplier
= USEC_PER_SEC
;
958 multiplier
= USEC_PER_HOURS
;
964 DBG("utils_parse_time_suffix: invalid suffix.");
969 /* Check for garbage after the valid input. */
970 if (num_end
!= str_end
) {
971 DBG("utils_parse_time_suffix: Garbage after time string.");
976 *time_us
= base_time
* multiplier
;
978 /* Check for overflow */
979 if ((*time_us
/ multiplier
) != base_time
) {
980 DBG("utils_parse_time_suffix: oops, overflow detected.");
991 * fls: returns the position of the most significant bit.
992 * Returns 0 if no bit is set, else returns the position of the most
993 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
995 #if defined(__i386) || defined(__x86_64)
996 static inline unsigned int fls_u32(uint32_t x
)
1000 asm("bsrl %1,%0\n\t"
1004 : "=r" (r
) : "rm" (x
));
1010 #if defined(__x86_64) && defined(__LP64__)
1012 unsigned int fls_u64(uint64_t x
)
1016 asm("bsrq %1,%0\n\t"
1020 : "=r" (r
) : "rm" (x
));
1027 static __attribute__((unused
))
1028 unsigned int fls_u64(uint64_t x
)
1030 unsigned int r
= 64;
1035 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1039 if (!(x
& 0xFFFF000000000000ULL
)) {
1043 if (!(x
& 0xFF00000000000000ULL
)) {
1047 if (!(x
& 0xF000000000000000ULL
)) {
1051 if (!(x
& 0xC000000000000000ULL
)) {
1055 if (!(x
& 0x8000000000000000ULL
)) {
1064 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1066 unsigned int r
= 32;
1071 if (!(x
& 0xFFFF0000U
)) {
1075 if (!(x
& 0xFF000000U
)) {
1079 if (!(x
& 0xF0000000U
)) {
1083 if (!(x
& 0xC0000000U
)) {
1087 if (!(x
& 0x80000000U
)) {
1096 * Return the minimum order for which x <= (1UL << order).
1097 * Return -1 if x is 0.
1100 int utils_get_count_order_u32(uint32_t x
)
1106 return fls_u32(x
- 1);
1110 * Return the minimum order for which x <= (1UL << order).
1111 * Return -1 if x is 0.
1114 int utils_get_count_order_u64(uint64_t x
)
1120 return fls_u64(x
- 1);
1124 * Obtain the value of LTTNG_HOME environment variable, if exists.
1125 * Otherwise returns the value of HOME.
1128 const char *utils_get_home_dir(void)
1133 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1137 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1142 /* Fallback on the password file entry. */
1143 pwd
= getpwuid(getuid());
1149 DBG3("Home directory is '%s'", val
);
1156 * Get user's home directory. Dynamically allocated, must be freed
1160 char *utils_get_user_home_dir(uid_t uid
)
1163 struct passwd
*result
;
1164 char *home_dir
= NULL
;
1169 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1174 buf
= zmalloc(buflen
);
1179 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1180 if (ret
|| !result
) {
1181 if (ret
== ERANGE
) {
1189 home_dir
= strdup(pwd
.pw_dir
);
1196 * With the given format, fill dst with the time of len maximum siz.
1198 * Return amount of bytes set in the buffer or else 0 on error.
1201 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1205 struct tm
*timeinfo
;
1210 /* Get date and time for session path */
1212 timeinfo
= localtime(&rawtime
);
1213 ret
= strftime(dst
, len
, format
, timeinfo
);
1215 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1223 * Return 0 on success and set *gid to the group_ID matching the passed name.
1224 * Else -1 if it cannot be found or an error occurred.
1227 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1229 static volatile int warn_once
;
1234 struct group
*result
;
1235 struct lttng_dynamic_buffer buffer
;
1237 /* Get the system limit, if it exists. */
1238 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1239 if (sys_len
== -1) {
1242 len
= (size_t) sys_len
;
1245 lttng_dynamic_buffer_init(&buffer
);
1246 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1248 ERR("Failed to allocate group info buffer");
1253 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1254 const size_t new_len
= 2 * buffer
.size
;
1256 /* Buffer is not big enough, increase its size. */
1257 if (new_len
< buffer
.size
) {
1258 ERR("Group info buffer size overflow");
1263 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1265 ERR("Failed to grow group info buffer to %zu bytes",
1272 PERROR("Failed to get group file entry for group name \"%s\"",
1278 /* Group not found. */
1284 *gid
= result
->gr_gid
;
1288 if (ret
&& warn
&& !warn_once
) {
1289 WARN("No tracing group detected");
1292 lttng_dynamic_buffer_reset(&buffer
);
1297 * Return a newly allocated option string. This string is to be used as the
1298 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1299 * of elements in the long_options array. Returns NULL if the string's
1303 char *utils_generate_optstring(const struct option
*long_options
,
1307 size_t string_len
= opt_count
, str_pos
= 0;
1311 * Compute the necessary string length. One letter per option, two when an
1312 * argument is necessary, and a trailing NULL.
1314 for (i
= 0; i
< opt_count
; i
++) {
1315 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1318 optstring
= zmalloc(string_len
);
1323 for (i
= 0; i
< opt_count
; i
++) {
1324 if (!long_options
[i
].name
) {
1325 /* Got to the trailing NULL element */
1329 if (long_options
[i
].val
!= '\0') {
1330 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1331 if (long_options
[i
].has_arg
) {
1332 optstring
[str_pos
++] = ':';
1342 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1343 * any file. Try to rmdir any empty directory within the hierarchy.
1346 int utils_recursive_rmdir(const char *path
)
1349 struct lttng_directory_handle
*handle
;
1351 handle
= lttng_directory_handle_create(NULL
);
1356 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1358 lttng_directory_handle_put(handle
);
1363 int utils_truncate_stream_file(int fd
, off_t length
)
1368 ret
= ftruncate(fd
, length
);
1370 PERROR("ftruncate");
1373 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1374 if (lseek_ret
< 0) {
1383 static const char *get_man_bin_path(void)
1385 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1388 return env_man_path
;
1391 return DEFAULT_MAN_BIN_PATH
;
1395 int utils_show_help(int section
, const char *page_name
,
1396 const char *help_msg
)
1398 char section_string
[8];
1399 const char *man_bin_path
= get_man_bin_path();
1403 printf("%s", help_msg
);
1407 /* Section integer -> section string */
1408 ret
= sprintf(section_string
, "%d", section
);
1409 assert(ret
> 0 && ret
< 8);
1412 * Execute man pager.
1414 * We provide -M to man here because LTTng-tools can
1415 * be installed outside /usr, in which case its man pages are
1416 * not located in the default /usr/share/man directory.
1418 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1419 section_string
, page_name
, NULL
);
1426 int read_proc_meminfo_field(const char *field
, size_t *value
)
1430 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1432 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1433 if (!proc_meminfo
) {
1434 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1440 * Read the contents of /proc/meminfo line by line to find the right
1443 while (!feof(proc_meminfo
)) {
1444 unsigned long value_kb
;
1446 ret
= fscanf(proc_meminfo
,
1447 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1451 * fscanf() returning EOF can indicate EOF or an error.
1453 if (ferror(proc_meminfo
)) {
1454 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1459 if (ret
== 2 && strcmp(name
, field
) == 0) {
1461 * This number is displayed in kilo-bytes. Return the
1464 *value
= ((size_t) value_kb
) * 1024;
1469 /* Reached the end of the file without finding the right field. */
1473 fclose(proc_meminfo
);
1479 * Returns an estimate of the number of bytes of memory available based on the
1480 * the information in `/proc/meminfo`. The number returned by this function is
1484 int utils_get_memory_available(size_t *value
)
1486 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1490 * Returns the total size of the memory on the system in bytes based on the
1491 * the information in `/proc/meminfo`.
1494 int utils_get_memory_total(size_t *value
)
1496 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1500 int utils_change_working_directory(const char *path
)
1506 DBG("Changing working directory to \"%s\"", path
);
1509 PERROR("Failed to change working directory to \"%s\"", path
);
1513 /* Check for write access */
1514 if (access(path
, W_OK
)) {
1515 if (errno
== EACCES
) {
1517 * Do not treat this as an error since the permission
1518 * might change in the lifetime of the process
1520 DBG("Working directory \"%s\" is not writable", path
);
1522 PERROR("Failed to check if working directory \"%s\" is writable",