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: GPL-2.0-only
9 #include "common/macros.h"
16 #include <sys/types.h>
24 #include <common/common.h>
25 #include <common/readwrite.h>
26 #include <common/runas.h>
27 #include <common/compat/getenv.h>
28 #include <common/compat/string.h>
29 #include <common/compat/dirent.h>
30 #include <common/compat/directory-handle.h>
31 #include <common/dynamic-buffer.h>
32 #include <common/string-utils/format.h>
33 #include <lttng/constant.h>
39 #define PROC_MEMINFO_PATH "/proc/meminfo"
40 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
41 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
43 /* The length of the longest field of `/proc/meminfo`. */
44 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
46 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
47 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
49 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
52 #define FALLBACK_USER_BUFLEN 16384
53 #define FALLBACK_GROUP_BUFLEN 16384
56 * Create a pipe in dst.
58 int utils_create_pipe(int *dst
)
68 PERROR("create pipe");
75 * Create pipe and set CLOEXEC flag to both fd.
77 * Make sure the pipe opened by this function are closed at some point. Use
80 int utils_create_pipe_cloexec(int *dst
)
88 ret
= utils_create_pipe(dst
);
93 for (i
= 0; i
< 2; i
++) {
94 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
96 PERROR("fcntl pipe cloexec");
106 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
108 * Make sure the pipe opened by this function are closed at some point. Use
109 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
110 * support OSes other than Linux 2.6.23+.
112 int utils_create_pipe_cloexec_nonblock(int *dst
)
120 ret
= utils_create_pipe(dst
);
125 for (i
= 0; i
< 2; i
++) {
126 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
128 PERROR("fcntl pipe cloexec");
132 * Note: we override any flag that could have been
133 * previously set on the fd.
135 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
137 PERROR("fcntl pipe nonblock");
147 * Close both read and write side of the pipe.
149 void utils_close_pipe(int *src
)
157 for (i
= 0; i
< 2; i
++) {
165 PERROR("close pipe");
172 * Create a new string using two strings range.
174 char *utils_strdupdelim(const char *begin
, const char *end
)
178 str
= (char *) zmalloc(end
- begin
+ 1);
180 PERROR("zmalloc strdupdelim");
184 memcpy(str
, begin
, end
- begin
);
185 str
[end
- begin
] = '\0';
192 * Set CLOEXEC flag to the give file descriptor.
194 int utils_set_fd_cloexec(int fd
)
203 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
205 PERROR("fcntl cloexec");
214 * Create pid file to the given path and filename.
216 int utils_create_pid_file(pid_t pid
, const char *filepath
)
221 LTTNG_ASSERT(filepath
);
223 fp
= fopen(filepath
, "w");
225 PERROR("open pid file %s", filepath
);
230 ret
= fprintf(fp
, "%d\n", (int) pid
);
232 PERROR("fprintf pid file");
239 DBG("Pid %d written in file %s", (int) pid
, filepath
);
246 * Create lock file to the given path and filename.
247 * Returns the associated file descriptor, -1 on error.
249 int utils_create_lock_file(const char *filepath
)
255 LTTNG_ASSERT(filepath
);
257 memset(&lock
, 0, sizeof(lock
));
258 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
261 PERROR("open lock file %s", filepath
);
267 * Attempt to lock the file. If this fails, there is
268 * already a process using the same lock file running
269 * and we should exit.
271 lock
.l_whence
= SEEK_SET
;
272 lock
.l_type
= F_WRLCK
;
274 ret
= fcntl(fd
, F_SETLK
, &lock
);
276 PERROR("fcntl lock file");
277 ERR("Could not get lock file %s, another instance is running.",
280 PERROR("close lock file");
291 * Create directory using the given path and mode.
293 * On success, return 0 else a negative error code.
295 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
298 struct lttng_directory_handle
*handle
;
299 const struct lttng_credentials creds
= {
300 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
301 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
304 handle
= lttng_directory_handle_create(NULL
);
309 ret
= lttng_directory_handle_create_subdirectory_as_user(
311 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
313 lttng_directory_handle_put(handle
);
318 * Recursively create directory using the given path and mode, under the
319 * provided uid and gid.
321 * On success, return 0 else a negative error code.
323 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
326 struct lttng_directory_handle
*handle
;
327 const struct lttng_credentials creds
= {
328 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
329 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
332 handle
= lttng_directory_handle_create(NULL
);
337 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
339 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
341 lttng_directory_handle_put(handle
);
346 * out_stream_path is the output parameter.
348 * Return 0 on success or else a negative value.
350 int utils_stream_file_path(const char *path_name
, const char *file_name
,
351 uint64_t size
, uint64_t count
, const char *suffix
,
352 char *out_stream_path
, size_t stream_path_len
)
355 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
356 const char *path_separator
;
358 if (path_name
&& (path_name
[0] == '\0' ||
359 path_name
[strlen(path_name
) - 1] == '/')) {
362 path_separator
= "/";
365 path_name
= path_name
? : "";
366 suffix
= suffix
? : "";
368 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
370 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
373 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
374 path_name
, path_separator
, file_name
, count_str
,
376 if (ret
< 0 || ret
>= stream_path_len
) {
377 ERR("Truncation occurred while formatting stream path");
386 * Parse a string that represents a size in human readable format. It
387 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
389 * The suffix multiply the integer by:
394 * @param str The string to parse.
395 * @param size Pointer to a uint64_t that will be filled with the
398 * @return 0 on success, -1 on failure.
400 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
409 DBG("utils_parse_size_suffix: received a NULL string.");
414 /* strtoull will accept a negative number, but we don't want to. */
415 if (strchr(str
, '-') != NULL
) {
416 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
421 /* str_end will point to the \0 */
422 str_end
= str
+ strlen(str
);
424 base_size
= strtoull(str
, &num_end
, 0);
426 PERROR("utils_parse_size_suffix strtoull");
431 if (num_end
== str
) {
432 /* strtoull parsed nothing, not good. */
433 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
438 /* Check if a prefix is present. */
456 DBG("utils_parse_size_suffix: invalid suffix.");
461 /* Check for garbage after the valid input. */
462 if (num_end
!= str_end
) {
463 DBG("utils_parse_size_suffix: Garbage after size string.");
468 *size
= base_size
<< shift
;
470 /* Check for overflow */
471 if ((*size
>> shift
) != base_size
) {
472 DBG("utils_parse_size_suffix: oops, overflow detected.");
483 * Parse a string that represents a time in human readable format. It
484 * supports decimal integers suffixed by:
485 * "us" for microsecond,
486 * "ms" for millisecond,
491 * The suffix multiply the integer by:
498 * Note that unit-less numbers are assumed to be microseconds.
500 * @param str The string to parse, assumed to be NULL-terminated.
501 * @param time_us Pointer to a uint64_t that will be filled with the
502 * resulting time in microseconds.
504 * @return 0 on success, -1 on failure.
506 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
510 uint64_t multiplier
= 1;
515 DBG("utils_parse_time_suffix: received a NULL string.");
520 /* strtoull will accept a negative number, but we don't want to. */
521 if (strchr(str
, '-') != NULL
) {
522 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
527 /* str_end will point to the \0 */
528 str_end
= str
+ strlen(str
);
530 base_time
= strtoull(str
, &num_end
, 10);
532 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
537 if (num_end
== str
) {
538 /* strtoull parsed nothing, not good. */
539 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
544 /* Check if a prefix is present. */
550 * Skip the "us" if the string matches the "us" suffix,
551 * otherwise let the check for the end of the string handle
552 * the error reporting.
554 if (*(num_end
+ 1) == 's') {
559 if (*(num_end
+ 1) == 's') {
560 /* Millisecond (ms) */
561 multiplier
= USEC_PER_MSEC
;
566 multiplier
= USEC_PER_MINUTE
;
572 multiplier
= USEC_PER_SEC
;
577 multiplier
= USEC_PER_HOURS
;
583 DBG("utils_parse_time_suffix: invalid suffix.");
588 /* Check for garbage after the valid input. */
589 if (num_end
!= str_end
) {
590 DBG("utils_parse_time_suffix: Garbage after time string.");
595 *time_us
= base_time
* multiplier
;
597 /* Check for overflow */
598 if ((*time_us
/ multiplier
) != base_time
) {
599 DBG("utils_parse_time_suffix: oops, overflow detected.");
610 * fls: returns the position of the most significant bit.
611 * Returns 0 if no bit is set, else returns the position of the most
612 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
614 #if defined(__i386) || defined(__x86_64)
615 static inline unsigned int fls_u32(uint32_t x
)
623 : "=r" (r
) : "rm" (x
));
629 #if defined(__x86_64) && defined(__LP64__)
631 unsigned int fls_u64(uint64_t x
)
639 : "=r" (r
) : "rm" (x
));
646 static __attribute__((unused
))
647 unsigned int fls_u64(uint64_t x
)
654 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
658 if (!(x
& 0xFFFF000000000000ULL
)) {
662 if (!(x
& 0xFF00000000000000ULL
)) {
666 if (!(x
& 0xF000000000000000ULL
)) {
670 if (!(x
& 0xC000000000000000ULL
)) {
674 if (!(x
& 0x8000000000000000ULL
)) {
683 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
690 if (!(x
& 0xFFFF0000U
)) {
694 if (!(x
& 0xFF000000U
)) {
698 if (!(x
& 0xF0000000U
)) {
702 if (!(x
& 0xC0000000U
)) {
706 if (!(x
& 0x80000000U
)) {
715 * Return the minimum order for which x <= (1UL << order).
716 * Return -1 if x is 0.
718 int utils_get_count_order_u32(uint32_t x
)
724 return fls_u32(x
- 1);
728 * Return the minimum order for which x <= (1UL << order).
729 * Return -1 if x is 0.
731 int utils_get_count_order_u64(uint64_t x
)
737 return fls_u64(x
- 1);
741 * Obtain the value of LTTNG_HOME environment variable, if exists.
742 * Otherwise returns the value of HOME.
744 const char *utils_get_home_dir(void)
749 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
753 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
758 /* Fallback on the password file entry. */
759 pwd
= getpwuid(getuid());
765 DBG3("Home directory is '%s'", val
);
772 * Get user's home directory. Dynamically allocated, must be freed
775 char *utils_get_user_home_dir(uid_t uid
)
778 struct passwd
*result
;
779 char *home_dir
= NULL
;
784 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
789 buf
= (char *) zmalloc(buflen
);
794 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
795 if (ret
|| !result
) {
804 home_dir
= strdup(pwd
.pw_dir
);
811 * With the given format, fill dst with the time of len maximum siz.
813 * Return amount of bytes set in the buffer or else 0 on error.
815 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
821 LTTNG_ASSERT(format
);
824 /* Get date and time for session path */
826 timeinfo
= localtime(&rawtime
);
828 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
829 ret
= strftime(dst
, len
, format
, timeinfo
);
832 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
840 * Return 0 on success and set *gid to the group_ID matching the passed name.
841 * Else -1 if it cannot be found or an error occurred.
843 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
845 static volatile int warn_once
;
850 struct group
*result
;
851 struct lttng_dynamic_buffer buffer
;
853 /* Get the system limit, if it exists. */
854 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
858 len
= (size_t) sys_len
;
861 lttng_dynamic_buffer_init(&buffer
);
862 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
864 ERR("Failed to allocate group info buffer");
869 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
870 const size_t new_len
= 2 * buffer
.size
;
872 /* Buffer is not big enough, increase its size. */
873 if (new_len
< buffer
.size
) {
874 ERR("Group info buffer size overflow");
879 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
881 ERR("Failed to grow group info buffer to %zu bytes",
889 DBG("Could not find group file entry for group name '%s'",
892 PERROR("Failed to get group file entry for group name '%s'",
900 /* Group not found. */
906 *gid
= result
->gr_gid
;
910 if (ret
&& warn
&& !warn_once
) {
911 WARN("No tracing group detected");
914 lttng_dynamic_buffer_reset(&buffer
);
919 * Return a newly allocated option string. This string is to be used as the
920 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
921 * of elements in the long_options array. Returns NULL if the string's
924 char *utils_generate_optstring(const struct option
*long_options
,
928 size_t string_len
= opt_count
, str_pos
= 0;
932 * Compute the necessary string length. One letter per option, two when an
933 * argument is necessary, and a trailing NULL.
935 for (i
= 0; i
< opt_count
; i
++) {
936 string_len
+= long_options
[i
].has_arg
? 1 : 0;
939 optstring
= (char *) zmalloc(string_len
);
944 for (i
= 0; i
< opt_count
; i
++) {
945 if (!long_options
[i
].name
) {
946 /* Got to the trailing NULL element */
950 if (long_options
[i
].val
!= '\0') {
951 optstring
[str_pos
++] = (char) long_options
[i
].val
;
952 if (long_options
[i
].has_arg
) {
953 optstring
[str_pos
++] = ':';
963 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
964 * any file. Try to rmdir any empty directory within the hierarchy.
966 int utils_recursive_rmdir(const char *path
)
969 struct lttng_directory_handle
*handle
;
971 handle
= lttng_directory_handle_create(NULL
);
976 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
978 lttng_directory_handle_put(handle
);
982 int utils_truncate_stream_file(int fd
, off_t length
)
987 ret
= ftruncate(fd
, length
);
992 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1002 static const char *get_man_bin_path(void)
1004 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1007 return env_man_path
;
1010 return DEFAULT_MAN_BIN_PATH
;
1013 int utils_show_help(int section
, const char *page_name
,
1014 const char *help_msg
)
1016 char section_string
[8];
1017 const char *man_bin_path
= get_man_bin_path();
1021 printf("%s", help_msg
);
1025 /* Section integer -> section string */
1026 ret
= sprintf(section_string
, "%d", section
);
1027 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1030 * Execute man pager.
1032 * We provide -M to man here because LTTng-tools can
1033 * be installed outside /usr, in which case its man pages are
1034 * not located in the default /usr/share/man directory.
1036 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1037 section_string
, page_name
, NULL
);
1044 int read_proc_meminfo_field(const char *field
, size_t *value
)
1048 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1050 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1051 if (!proc_meminfo
) {
1052 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1058 * Read the contents of /proc/meminfo line by line to find the right
1061 while (!feof(proc_meminfo
)) {
1062 unsigned long value_kb
;
1064 ret
= fscanf(proc_meminfo
,
1065 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1069 * fscanf() returning EOF can indicate EOF or an error.
1071 if (ferror(proc_meminfo
)) {
1072 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1077 if (ret
== 2 && strcmp(name
, field
) == 0) {
1079 * This number is displayed in kilo-bytes. Return the
1082 *value
= ((size_t) value_kb
) * 1024;
1087 /* Reached the end of the file without finding the right field. */
1091 fclose(proc_meminfo
);
1097 * Returns an estimate of the number of bytes of memory available based on the
1098 * the information in `/proc/meminfo`. The number returned by this function is
1101 int utils_get_memory_available(size_t *value
)
1103 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1107 * Returns the total size of the memory on the system in bytes based on the
1108 * the information in `/proc/meminfo`.
1110 int utils_get_memory_total(size_t *value
)
1112 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1115 int utils_change_working_directory(const char *path
)
1121 DBG("Changing working directory to \"%s\"", path
);
1124 PERROR("Failed to change working directory to \"%s\"", path
);
1128 /* Check for write access */
1129 if (access(path
, W_OK
)) {
1130 if (errno
== EACCES
) {
1132 * Do not treat this as an error since the permission
1133 * might change in the lifetime of the process
1135 DBG("Working directory \"%s\" is not writable", path
);
1137 PERROR("Failed to check if working directory \"%s\" is writable",
1146 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1148 struct passwd p
, *pres
;
1150 enum lttng_error_code ret_val
= LTTNG_OK
;
1154 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1156 buflen
= FALLBACK_USER_BUFLEN
;
1159 buf
= (char *) zmalloc(buflen
);
1161 ret_val
= LTTNG_ERR_NOMEM
;
1166 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1173 buf
= (char *) zmalloc(buflen
);
1175 ret_val
= LTTNG_ERR_NOMEM
;
1188 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1191 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1192 user_name
, (int64_t) *uid
);
1200 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1203 ret_val
= LTTNG_ERR_NOMEM
;
1210 enum lttng_error_code
utils_group_id_from_name(
1211 const char *group_name
, gid_t
*gid
)
1213 struct group g
, *gres
;
1215 enum lttng_error_code ret_val
= LTTNG_OK
;
1219 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1221 buflen
= FALLBACK_GROUP_BUFLEN
;
1224 buf
= (char *) zmalloc(buflen
);
1226 ret_val
= LTTNG_ERR_NOMEM
;
1231 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1238 buf
= (char *) zmalloc(buflen
);
1240 ret_val
= LTTNG_ERR_NOMEM
;
1253 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1256 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1257 group_name
, (int64_t) *gid
);
1265 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1268 ret_val
= LTTNG_ERR_NOMEM
;
1275 int utils_parse_unsigned_long_long(const char *str
,
1276 unsigned long long *value
)
1282 LTTNG_ASSERT(value
);
1285 *value
= strtoull(str
, &endptr
, 10);
1287 /* Conversion failed. Out of range? */
1289 /* Don't print an error; allow the caller to log a better error. */
1290 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1296 /* Not the end of the string or empty string. */
1297 if (*endptr
|| endptr
== str
) {
1298 DBG("Failed to parse string as unsigned long long number: string = '%s'",