2 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * SPDX-License-Identifier: LGPL-2.1-only
9 #include "common/macros.h"
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)
53 #define FALLBACK_USER_BUFLEN 16384
54 #define FALLBACK_GROUP_BUFLEN 16384
57 * Create a pipe in dst.
59 int utils_create_pipe(int *dst
)
69 PERROR("create pipe");
76 * Create pipe and set CLOEXEC flag to both fd.
78 * Make sure the pipe opened by this function are closed at some point. Use
81 int utils_create_pipe_cloexec(int *dst
)
89 ret
= utils_create_pipe(dst
);
94 for (i
= 0; i
< 2; i
++) {
95 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
97 PERROR("fcntl pipe cloexec");
107 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
109 * Make sure the pipe opened by this function are closed at some point. Use
110 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
111 * support OSes other than Linux 2.6.23+.
113 int utils_create_pipe_cloexec_nonblock(int *dst
)
121 ret
= utils_create_pipe(dst
);
126 for (i
= 0; i
< 2; i
++) {
127 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
129 PERROR("fcntl pipe cloexec");
133 * Note: we override any flag that could have been
134 * previously set on the fd.
136 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
138 PERROR("fcntl pipe nonblock");
148 * Close both read and write side of the pipe.
150 void utils_close_pipe(int *src
)
158 for (i
= 0; i
< 2; i
++) {
166 PERROR("close pipe");
173 * Create a new string using two strings range.
175 char *utils_strdupdelim(const char *begin
, const char *end
)
179 str
= (char *) zmalloc(end
- begin
+ 1);
181 PERROR("zmalloc strdupdelim");
185 memcpy(str
, begin
, end
- begin
);
186 str
[end
- begin
] = '\0';
193 * Set CLOEXEC flag to the give file descriptor.
195 int utils_set_fd_cloexec(int fd
)
204 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
206 PERROR("fcntl cloexec");
215 * Create pid file to the given path and filename.
217 int utils_create_pid_file(pid_t pid
, const char *filepath
)
222 LTTNG_ASSERT(filepath
);
224 fp
= fopen(filepath
, "w");
226 PERROR("open pid file %s", filepath
);
231 ret
= fprintf(fp
, "%d\n", (int) pid
);
233 PERROR("fprintf pid file");
240 DBG("Pid %d written in file %s", (int) pid
, filepath
);
247 * Create lock file to the given path and filename.
248 * Returns the associated file descriptor, -1 on error.
250 int utils_create_lock_file(const char *filepath
)
256 LTTNG_ASSERT(filepath
);
258 memset(&lock
, 0, sizeof(lock
));
259 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
262 PERROR("open lock file %s", filepath
);
268 * Attempt to lock the file. If this fails, there is
269 * already a process using the same lock file running
270 * and we should exit.
272 lock
.l_whence
= SEEK_SET
;
273 lock
.l_type
= F_WRLCK
;
275 ret
= fcntl(fd
, F_SETLK
, &lock
);
277 PERROR("fcntl lock file");
278 ERR("Could not get lock file %s, another instance is running.",
281 PERROR("close lock file");
292 * Create directory using the given path and mode.
294 * On success, return 0 else a negative error code.
296 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
299 struct lttng_directory_handle
*handle
;
300 const struct lttng_credentials creds
= {
301 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
302 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
305 handle
= lttng_directory_handle_create(NULL
);
310 ret
= lttng_directory_handle_create_subdirectory_as_user(
312 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
314 lttng_directory_handle_put(handle
);
319 * Recursively create directory using the given path and mode, under the
320 * provided uid and gid.
322 * On success, return 0 else a negative error code.
324 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
327 struct lttng_directory_handle
*handle
;
328 const struct lttng_credentials creds
= {
329 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
330 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
333 handle
= lttng_directory_handle_create(NULL
);
338 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
340 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
342 lttng_directory_handle_put(handle
);
347 * out_stream_path is the output parameter.
349 * Return 0 on success or else a negative value.
351 int utils_stream_file_path(const char *path_name
, const char *file_name
,
352 uint64_t size
, uint64_t count
, const char *suffix
,
353 char *out_stream_path
, size_t stream_path_len
)
356 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
357 const char *path_separator
;
359 if (path_name
&& (path_name
[0] == '\0' ||
360 path_name
[strlen(path_name
) - 1] == '/')) {
363 path_separator
= "/";
366 path_name
= path_name
? : "";
367 suffix
= suffix
? : "";
369 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
371 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
374 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
375 path_name
, path_separator
, file_name
, count_str
,
377 if (ret
< 0 || ret
>= stream_path_len
) {
378 ERR("Truncation occurred while formatting stream path");
387 * Parse a string that represents a size in human readable format. It
388 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
390 * The suffix multiply the integer by:
395 * @param str The string to parse.
396 * @param size Pointer to a uint64_t that will be filled with the
399 * @return 0 on success, -1 on failure.
401 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
410 DBG("utils_parse_size_suffix: received a NULL string.");
415 /* strtoull will accept a negative number, but we don't want to. */
416 if (strchr(str
, '-') != NULL
) {
417 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
422 /* str_end will point to the \0 */
423 str_end
= str
+ strlen(str
);
425 base_size
= strtoull(str
, &num_end
, 0);
427 PERROR("utils_parse_size_suffix strtoull");
432 if (num_end
== str
) {
433 /* strtoull parsed nothing, not good. */
434 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
439 /* Check if a prefix is present. */
457 DBG("utils_parse_size_suffix: invalid suffix.");
462 /* Check for garbage after the valid input. */
463 if (num_end
!= str_end
) {
464 DBG("utils_parse_size_suffix: Garbage after size string.");
469 *size
= base_size
<< shift
;
471 /* Check for overflow */
472 if ((*size
>> shift
) != base_size
) {
473 DBG("utils_parse_size_suffix: oops, overflow detected.");
484 * Parse a string that represents a time in human readable format. It
485 * supports decimal integers suffixed by:
486 * "us" for microsecond,
487 * "ms" for millisecond,
492 * The suffix multiply the integer by:
499 * Note that unit-less numbers are assumed to be microseconds.
501 * @param str The string to parse, assumed to be NULL-terminated.
502 * @param time_us Pointer to a uint64_t that will be filled with the
503 * resulting time in microseconds.
505 * @return 0 on success, -1 on failure.
507 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
511 uint64_t multiplier
= 1;
516 DBG("utils_parse_time_suffix: received a NULL string.");
521 /* strtoull will accept a negative number, but we don't want to. */
522 if (strchr(str
, '-') != NULL
) {
523 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
528 /* str_end will point to the \0 */
529 str_end
= str
+ strlen(str
);
531 base_time
= strtoull(str
, &num_end
, 10);
533 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
538 if (num_end
== str
) {
539 /* strtoull parsed nothing, not good. */
540 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
545 /* Check if a prefix is present. */
551 * Skip the "us" if the string matches the "us" suffix,
552 * otherwise let the check for the end of the string handle
553 * the error reporting.
555 if (*(num_end
+ 1) == 's') {
560 if (*(num_end
+ 1) == 's') {
561 /* Millisecond (ms) */
562 multiplier
= USEC_PER_MSEC
;
567 multiplier
= USEC_PER_MINUTE
;
573 multiplier
= USEC_PER_SEC
;
578 multiplier
= USEC_PER_HOURS
;
584 DBG("utils_parse_time_suffix: invalid suffix.");
589 /* Check for garbage after the valid input. */
590 if (num_end
!= str_end
) {
591 DBG("utils_parse_time_suffix: Garbage after time string.");
596 *time_us
= base_time
* multiplier
;
598 /* Check for overflow */
599 if ((*time_us
/ multiplier
) != base_time
) {
600 DBG("utils_parse_time_suffix: oops, overflow detected.");
611 * fls: returns the position of the most significant bit.
612 * Returns 0 if no bit is set, else returns the position of the most
613 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
615 #if defined(__i386) || defined(__x86_64)
616 static inline unsigned int fls_u32(uint32_t x
)
624 : "=r" (r
) : "rm" (x
));
630 #if defined(__x86_64) && defined(__LP64__)
632 unsigned int fls_u64(uint64_t x
)
640 : "=r" (r
) : "rm" (x
));
647 static __attribute__((unused
))
648 unsigned int fls_u64(uint64_t x
)
655 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
659 if (!(x
& 0xFFFF000000000000ULL
)) {
663 if (!(x
& 0xFF00000000000000ULL
)) {
667 if (!(x
& 0xF000000000000000ULL
)) {
671 if (!(x
& 0xC000000000000000ULL
)) {
675 if (!(x
& 0x8000000000000000ULL
)) {
684 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
691 if (!(x
& 0xFFFF0000U
)) {
695 if (!(x
& 0xFF000000U
)) {
699 if (!(x
& 0xF0000000U
)) {
703 if (!(x
& 0xC0000000U
)) {
707 if (!(x
& 0x80000000U
)) {
716 * Return the minimum order for which x <= (1UL << order).
717 * Return -1 if x is 0.
719 int utils_get_count_order_u32(uint32_t x
)
725 return fls_u32(x
- 1);
729 * Return the minimum order for which x <= (1UL << order).
730 * Return -1 if x is 0.
732 int utils_get_count_order_u64(uint64_t x
)
738 return fls_u64(x
- 1);
742 * Obtain the value of LTTNG_HOME environment variable, if exists.
743 * Otherwise returns the value of HOME.
745 const char *utils_get_home_dir(void)
750 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
754 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
759 /* Fallback on the password file entry. */
760 pwd
= getpwuid(getuid());
766 DBG3("Home directory is '%s'", val
);
773 * Get user's home directory. Dynamically allocated, must be freed
776 char *utils_get_user_home_dir(uid_t uid
)
779 struct passwd
*result
;
780 char *home_dir
= NULL
;
785 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
790 buf
= (char *) zmalloc(buflen
);
795 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
796 if (ret
|| !result
) {
805 home_dir
= strdup(pwd
.pw_dir
);
812 * With the given format, fill dst with the time of len maximum siz.
814 * Return amount of bytes set in the buffer or else 0 on error.
816 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
822 LTTNG_ASSERT(format
);
825 /* Get date and time for session path */
827 timeinfo
= localtime(&rawtime
);
829 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
830 ret
= strftime(dst
, len
, format
, timeinfo
);
833 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
841 * Return 0 on success and set *gid to the group_ID matching the passed name.
842 * Else -1 if it cannot be found or an error occurred.
844 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
846 static volatile int warn_once
;
851 struct group
*result
;
852 struct lttng_dynamic_buffer buffer
;
854 /* Get the system limit, if it exists. */
855 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
859 len
= (size_t) sys_len
;
862 lttng_dynamic_buffer_init(&buffer
);
863 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
865 ERR("Failed to allocate group info buffer");
870 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
871 const size_t new_len
= 2 * buffer
.size
;
873 /* Buffer is not big enough, increase its size. */
874 if (new_len
< buffer
.size
) {
875 ERR("Group info buffer size overflow");
880 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
882 ERR("Failed to grow group info buffer to %zu bytes",
890 DBG("Could not find group file entry for group name '%s'",
893 PERROR("Failed to get group file entry for group name '%s'",
901 /* Group not found. */
907 *gid
= result
->gr_gid
;
911 if (ret
&& warn
&& !warn_once
) {
912 WARN("No tracing group detected");
915 lttng_dynamic_buffer_reset(&buffer
);
920 * Return a newly allocated option string. This string is to be used as the
921 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
922 * of elements in the long_options array. Returns NULL if the string's
925 char *utils_generate_optstring(const struct option
*long_options
,
929 size_t string_len
= opt_count
, str_pos
= 0;
933 * Compute the necessary string length. One letter per option, two when an
934 * argument is necessary, and a trailing NULL.
936 for (i
= 0; i
< opt_count
; i
++) {
937 string_len
+= long_options
[i
].has_arg
? 1 : 0;
940 optstring
= (char *) zmalloc(string_len
);
945 for (i
= 0; i
< opt_count
; i
++) {
946 if (!long_options
[i
].name
) {
947 /* Got to the trailing NULL element */
951 if (long_options
[i
].val
!= '\0') {
952 optstring
[str_pos
++] = (char) long_options
[i
].val
;
953 if (long_options
[i
].has_arg
) {
954 optstring
[str_pos
++] = ':';
964 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
965 * any file. Try to rmdir any empty directory within the hierarchy.
967 int utils_recursive_rmdir(const char *path
)
970 struct lttng_directory_handle
*handle
;
972 handle
= lttng_directory_handle_create(NULL
);
977 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
979 lttng_directory_handle_put(handle
);
983 int utils_truncate_stream_file(int fd
, off_t length
)
988 ret
= ftruncate(fd
, length
);
993 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1003 static const char *get_man_bin_path(void)
1005 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1008 return env_man_path
;
1011 return DEFAULT_MAN_BIN_PATH
;
1014 int utils_show_help(int section
, const char *page_name
,
1015 const char *help_msg
)
1017 char section_string
[8];
1018 const char *man_bin_path
= get_man_bin_path();
1022 printf("%s", help_msg
);
1026 /* Section integer -> section string */
1027 ret
= sprintf(section_string
, "%d", section
);
1028 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1031 * Execute man pager.
1033 * We provide -M to man here because LTTng-tools can
1034 * be installed outside /usr, in which case its man pages are
1035 * not located in the default /usr/share/man directory.
1037 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1038 section_string
, page_name
, NULL
);
1045 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1049 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1051 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1052 if (!proc_meminfo
) {
1053 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1059 * Read the contents of /proc/meminfo line by line to find the right
1062 while (!feof(proc_meminfo
)) {
1065 ret
= fscanf(proc_meminfo
,
1066 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1070 * fscanf() returning EOF can indicate EOF or an error.
1072 if (ferror(proc_meminfo
)) {
1073 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1078 if (ret
== 2 && strcmp(name
, field
) == 0) {
1080 * This number is displayed in kilo-bytes. Return the
1083 if (value_kb
> UINT64_MAX
/ 1024) {
1084 ERR("Overflow on kb to bytes conversion");
1088 *value
= value_kb
* 1024;
1093 /* Reached the end of the file without finding the right field. */
1097 fclose(proc_meminfo
);
1103 * Returns an estimate of the number of bytes of memory available based on the
1104 * the information in `/proc/meminfo`. The number returned by this function is
1107 int utils_get_memory_available(uint64_t *value
)
1109 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1113 * Returns the total size of the memory on the system in bytes based on the
1114 * the information in `/proc/meminfo`.
1116 int utils_get_memory_total(uint64_t *value
)
1118 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1121 int utils_change_working_directory(const char *path
)
1127 DBG("Changing working directory to \"%s\"", path
);
1130 PERROR("Failed to change working directory to \"%s\"", path
);
1134 /* Check for write access */
1135 if (access(path
, W_OK
)) {
1136 if (errno
== EACCES
) {
1138 * Do not treat this as an error since the permission
1139 * might change in the lifetime of the process
1141 DBG("Working directory \"%s\" is not writable", path
);
1143 PERROR("Failed to check if working directory \"%s\" is writable",
1152 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1154 struct passwd p
, *pres
;
1156 enum lttng_error_code ret_val
= LTTNG_OK
;
1160 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1162 buflen
= FALLBACK_USER_BUFLEN
;
1165 buf
= (char *) zmalloc(buflen
);
1167 ret_val
= LTTNG_ERR_NOMEM
;
1172 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1179 buf
= (char *) zmalloc(buflen
);
1181 ret_val
= LTTNG_ERR_NOMEM
;
1194 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1197 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1198 user_name
, (int64_t) *uid
);
1206 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1209 ret_val
= LTTNG_ERR_NOMEM
;
1216 enum lttng_error_code
utils_group_id_from_name(
1217 const char *group_name
, gid_t
*gid
)
1219 struct group g
, *gres
;
1221 enum lttng_error_code ret_val
= LTTNG_OK
;
1225 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1227 buflen
= FALLBACK_GROUP_BUFLEN
;
1230 buf
= (char *) zmalloc(buflen
);
1232 ret_val
= LTTNG_ERR_NOMEM
;
1237 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1244 buf
= (char *) zmalloc(buflen
);
1246 ret_val
= LTTNG_ERR_NOMEM
;
1259 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1262 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1263 group_name
, (int64_t) *gid
);
1271 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1274 ret_val
= LTTNG_ERR_NOMEM
;
1281 int utils_parse_unsigned_long_long(const char *str
,
1282 unsigned long long *value
)
1288 LTTNG_ASSERT(value
);
1291 *value
= strtoull(str
, &endptr
, 10);
1293 /* Conversion failed. Out of range? */
1295 /* Don't print an error; allow the caller to log a better error. */
1296 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1302 /* Not the end of the string or empty string. */
1303 if (*endptr
|| endptr
== str
) {
1304 DBG("Failed to parse string as unsigned long long number: string = '%s'",