2 * Babeltrace common functions
4 * Copyright 2016 Philippe Proulx <pproulx@efficios.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 #define BT_LOG_OUTPUT_LEVEL log_level
26 #define BT_LOG_TAG "COMMON"
27 #include "logging/log.h"
32 #include <sys/types.h>
35 #include "common/assert.h"
43 #include "common/macros.h"
44 #include "common/common.h"
45 #include "compat/unistd.h"
49 #include <sys/ioctl.h>
52 #define SYSTEM_PLUGIN_PATH BABELTRACE_PLUGINS_DIR
53 #define HOME_ENV_VAR "HOME"
54 #define HOME_PLUGIN_SUBPATH "/.local/lib/babeltrace2/plugins"
56 static const char *bt_common_color_code_reset
= "";
57 static const char *bt_common_color_code_bold
= "";
58 static const char *bt_common_color_code_fg_default
= "";
59 static const char *bt_common_color_code_fg_red
= "";
60 static const char *bt_common_color_code_fg_green
= "";
61 static const char *bt_common_color_code_fg_yellow
= "";
62 static const char *bt_common_color_code_fg_blue
= "";
63 static const char *bt_common_color_code_fg_magenta
= "";
64 static const char *bt_common_color_code_fg_cyan
= "";
65 static const char *bt_common_color_code_fg_light_gray
= "";
66 static const char *bt_common_color_code_bg_default
= "";
67 static const char *bt_common_color_code_bg_red
= "";
68 static const char *bt_common_color_code_bg_green
= "";
69 static const char *bt_common_color_code_bg_yellow
= "";
70 static const char *bt_common_color_code_bg_blue
= "";
71 static const char *bt_common_color_code_bg_magenta
= "";
72 static const char *bt_common_color_code_bg_cyan
= "";
73 static const char *bt_common_color_code_bg_light_gray
= "";
76 void __attribute__((constructor
)) bt_common_color_ctor(void)
78 if (bt_common_colors_supported()) {
79 bt_common_color_code_reset
= BT_COMMON_COLOR_RESET
;
80 bt_common_color_code_bold
= BT_COMMON_COLOR_BOLD
;
81 bt_common_color_code_fg_default
= BT_COMMON_COLOR_FG_DEFAULT
;
82 bt_common_color_code_fg_red
= BT_COMMON_COLOR_FG_RED
;
83 bt_common_color_code_fg_green
= BT_COMMON_COLOR_FG_GREEN
;
84 bt_common_color_code_fg_yellow
= BT_COMMON_COLOR_FG_YELLOW
;
85 bt_common_color_code_fg_blue
= BT_COMMON_COLOR_FG_BLUE
;
86 bt_common_color_code_fg_magenta
= BT_COMMON_COLOR_FG_MAGENTA
;
87 bt_common_color_code_fg_cyan
= BT_COMMON_COLOR_FG_CYAN
;
88 bt_common_color_code_fg_light_gray
= BT_COMMON_COLOR_FG_LIGHT_GRAY
;
89 bt_common_color_code_bg_default
= BT_COMMON_COLOR_BG_DEFAULT
;
90 bt_common_color_code_bg_red
= BT_COMMON_COLOR_BG_RED
;
91 bt_common_color_code_bg_green
= BT_COMMON_COLOR_BG_GREEN
;
92 bt_common_color_code_bg_yellow
= BT_COMMON_COLOR_BG_YELLOW
;
93 bt_common_color_code_bg_blue
= BT_COMMON_COLOR_BG_BLUE
;
94 bt_common_color_code_bg_magenta
= BT_COMMON_COLOR_BG_MAGENTA
;
95 bt_common_color_code_bg_cyan
= BT_COMMON_COLOR_BG_CYAN
;
96 bt_common_color_code_bg_light_gray
= BT_COMMON_COLOR_BG_LIGHT_GRAY
;
101 const char *bt_common_get_system_plugin_path(void)
103 return SYSTEM_PLUGIN_PATH
;
108 bool bt_common_is_setuid_setgid(void)
112 #else /* __MINGW32__ */
114 bool bt_common_is_setuid_setgid(void)
116 return (geteuid() != getuid() || getegid() != getgid());
118 #endif /* __MINGW32__ */
122 const char *bt_get_home_dir(int log_level
)
124 return g_get_home_dir();
126 #else /* __MINGW32__ */
128 char *bt_secure_getenv(const char *name
, int log_level
)
130 if (bt_common_is_setuid_setgid()) {
131 BT_LOGD("Disregarding environment variable for setuid/setgid binary: "
132 "name=\"%s\"", name
);
139 const char *bt_get_home_dir(int log_level
)
144 val
= bt_secure_getenv(HOME_ENV_VAR
, log_level
);
148 /* Fallback on password file. */
149 pwd
= getpwuid(getuid());
157 #endif /* __MINGW32__ */
160 char *bt_common_get_home_plugin_path(int log_level
)
163 const char *home_dir
;
166 home_dir
= bt_get_home_dir(log_level
);
171 length
= strlen(home_dir
) + strlen(HOME_PLUGIN_SUBPATH
) + 1;
173 if (length
>= PATH_MAX
) {
174 BT_LOGW("Home directory path is too long: "
175 "length=%zu, max-length=%u", length
, PATH_MAX
);
179 path
= malloc(PATH_MAX
);
184 strcpy(path
, home_dir
);
185 strcat(path
, HOME_PLUGIN_SUBPATH
);
192 int bt_common_append_plugin_path_dirs(const char *paths
, GPtrArray
*dirs
)
197 size_t init_dirs_len
;
200 init_dirs_len
= dirs
->len
;
203 /* Nothing to append */
208 end
= paths
+ strlen(paths
);
212 const char *next_sep
;
214 next_sep
= strchr(at
, G_SEARCHPATH_SEPARATOR
);
215 if (next_sep
== at
) {
217 * Empty path: try next character (supported
218 * to conform to the typical parsing of $PATH).
222 } else if (!next_sep
) {
223 /* No more separator: use the remaining */
224 next_sep
= paths
+ strlen(paths
);
227 path
= g_string_new(NULL
);
232 g_string_append_len(path
, at
, next_sep
- at
);
234 g_ptr_array_add(dirs
, path
);
242 /* Remove the new entries in dirs */
243 while (dirs
->len
> init_dirs_len
) {
244 g_ptr_array_remove_index(dirs
, init_dirs_len
);
252 bool isarealtty(int fd
)
255 struct stat tty_stats
;
262 if (fstat(fd
, &tty_stats
) == 0) {
263 if (!S_ISCHR(tty_stats
.st_mode
)) {
264 /* Not a character device: not a TTY */
276 bool bt_common_colors_supported(void)
278 static bool supports_colors
= false;
279 static bool supports_colors_set
= false;
280 const char *term_env_var
;
281 const char *term_color_env_var
;
283 if (supports_colors_set
) {
287 supports_colors_set
= true;
290 * `BABELTRACE_TERM_COLOR` environment variable always overrides
291 * the automatic color support detection.
293 term_color_env_var
= getenv("BABELTRACE_TERM_COLOR");
294 if (term_color_env_var
) {
295 if (g_ascii_strcasecmp(term_color_env_var
, "always") == 0) {
297 supports_colors
= true;
298 } else if (g_ascii_strcasecmp(term_color_env_var
, "never") == 0) {
299 /* Force no colors */
304 /* We need a compatible, known terminal */
305 term_env_var
= getenv("TERM");
310 if (strncmp(term_env_var
, "xterm", 5) != 0 &&
311 strncmp(term_env_var
, "rxvt", 4) != 0 &&
312 strncmp(term_env_var
, "konsole", 7) != 0 &&
313 strncmp(term_env_var
, "gnome", 5) != 0 &&
314 strncmp(term_env_var
, "screen", 5) != 0 &&
315 strncmp(term_env_var
, "tmux", 4) != 0 &&
316 strncmp(term_env_var
, "putty", 5) != 0) {
320 /* Both standard output and error streams need to be TTYs */
321 if (!isarealtty(STDOUT_FILENO
) || !isarealtty(STDERR_FILENO
)) {
325 supports_colors
= true;
328 return supports_colors
;
332 const char *bt_common_color_reset(void)
334 return bt_common_color_code_reset
;
338 const char *bt_common_color_bold(void)
340 return bt_common_color_code_bold
;
344 const char *bt_common_color_fg_default(void)
346 return bt_common_color_code_fg_default
;
350 const char *bt_common_color_fg_red(void)
352 return bt_common_color_code_fg_red
;
356 const char *bt_common_color_fg_green(void)
358 return bt_common_color_code_fg_green
;
362 const char *bt_common_color_fg_yellow(void)
364 return bt_common_color_code_fg_yellow
;
368 const char *bt_common_color_fg_blue(void)
370 return bt_common_color_code_fg_blue
;
374 const char *bt_common_color_fg_magenta(void)
376 return bt_common_color_code_fg_magenta
;
380 const char *bt_common_color_fg_cyan(void)
382 return bt_common_color_code_fg_cyan
;
386 const char *bt_common_color_fg_light_gray(void)
388 return bt_common_color_code_fg_light_gray
;
392 const char *bt_common_color_bg_default(void)
394 return bt_common_color_code_bg_default
;
398 const char *bt_common_color_bg_red(void)
400 return bt_common_color_code_bg_red
;
404 const char *bt_common_color_bg_green(void)
406 return bt_common_color_code_bg_green
;
410 const char *bt_common_color_bg_yellow(void)
412 return bt_common_color_code_bg_yellow
;
416 const char *bt_common_color_bg_blue(void)
418 return bt_common_color_code_bg_blue
;
422 const char *bt_common_color_bg_magenta(void)
424 return bt_common_color_code_bg_magenta
;
428 const char *bt_common_color_bg_cyan(void)
430 return bt_common_color_code_bg_cyan
;
434 const char *bt_common_color_bg_light_gray(void)
436 return bt_common_color_code_bg_light_gray
;
440 GString
*bt_common_string_until(const char *input
, const char *escapable_chars
,
441 const char *end_chars
, size_t *end_pos
)
443 GString
*output
= g_string_new(NULL
);
446 const char *end_char
;
452 for (ch
= input
; *ch
!= '\0'; ch
++) {
454 bool continue_loop
= false;
457 /* `\` at the end of the string: append `\` */
458 g_string_append_c(output
, *ch
);
463 for (es_char
= escapable_chars
; *es_char
!= '\0'; es_char
++) {
464 if (ch
[1] == *es_char
) {
466 * `\` followed by an escapable
467 * character: append the escaped
470 g_string_append_c(output
, ch
[1]);
472 continue_loop
= true;
482 * `\` followed by a non-escapable character:
483 * append `\` and the character.
485 g_string_append_c(output
, *ch
);
486 g_string_append_c(output
, ch
[1]);
490 for (end_char
= end_chars
; *end_char
!= '\0'; end_char
++) {
491 if (*ch
== *end_char
) {
493 * End character found:
494 * terminate this loop.
500 /* Normal character: append */
501 g_string_append_c(output
, *ch
);
507 *end_pos
= ch
- input
;
514 g_string_free(output
, TRUE
);
522 GString
*bt_common_shell_quote(const char *input
, bool with_single_quotes
)
524 GString
*output
= g_string_new(NULL
);
526 bool no_quote
= true;
532 if (strlen(input
) == 0) {
533 if (with_single_quotes
) {
534 g_string_assign(output
, "''");
540 for (ch
= input
; *ch
!= '\0'; ch
++) {
543 if (!g_ascii_isalpha(c
) && !g_ascii_isdigit(c
) && c
!= '_' &&
544 c
!= '@' && c
!= '%' && c
!= '+' && c
!= '=' &&
545 c
!= ':' && c
!= ',' && c
!= '.' && c
!= '/' &&
553 g_string_assign(output
, input
);
557 if (with_single_quotes
) {
558 g_string_assign(output
, "'");
561 for (ch
= input
; *ch
!= '\0'; ch
++) {
563 g_string_append(output
, "'\"'\"'");
565 g_string_append_c(output
, *ch
);
569 if (with_single_quotes
) {
570 g_string_append_c(output
, '\'');
578 bool bt_common_string_is_printable(const char *input
)
581 bool printable
= true;
584 for (ch
= input
; *ch
!= '\0'; ch
++) {
585 if (!isprint(*ch
) && *ch
!= '\n' && *ch
!= '\r' &&
586 *ch
!= '\t' && *ch
!= '\v') {
597 void bt_common_destroy_lttng_live_url_parts(
598 struct bt_common_lttng_live_url_parts
*parts
)
605 g_string_free(parts
->proto
, TRUE
);
609 if (parts
->hostname
) {
610 g_string_free(parts
->hostname
, TRUE
);
611 parts
->hostname
= NULL
;
614 if (parts
->target_hostname
) {
615 g_string_free(parts
->target_hostname
, TRUE
);
616 parts
->target_hostname
= NULL
;
619 if (parts
->session_name
) {
620 g_string_free(parts
->session_name
, TRUE
);
621 parts
->session_name
= NULL
;
629 struct bt_common_lttng_live_url_parts
bt_common_parse_lttng_live_url(
630 const char *url
, char *error_buf
, size_t error_buf_size
)
632 struct bt_common_lttng_live_url_parts parts
;
633 const char *at
= url
;
637 memset(&parts
, 0, sizeof(parts
));
641 parts
.proto
= bt_common_string_until(at
, "", ":", &end_pos
);
642 if (!parts
.proto
|| parts
.proto
->len
== 0) {
644 snprintf(error_buf
, error_buf_size
, "Missing protocol");
650 if (strcmp(parts
.proto
->str
, "net") == 0) {
651 g_string_assign(parts
.proto
, "net4");
654 if (strcmp(parts
.proto
->str
, "net4") != 0 &&
655 strcmp(parts
.proto
->str
, "net6") != 0) {
657 snprintf(error_buf
, error_buf_size
,
658 "Unknown protocol: `%s`", parts
.proto
->str
);
664 if (at
[end_pos
] != ':') {
666 snprintf(error_buf
, error_buf_size
,
667 "Expecting `:` after `%s`", parts
.proto
->str
);
676 if (strncmp(at
, "://", 3) != 0) {
678 snprintf(error_buf
, error_buf_size
,
679 "Expecting `://` after protocol");
688 parts
.hostname
= bt_common_string_until(at
, "", ":/", &end_pos
);
689 if (!parts
.hostname
|| parts
.hostname
->len
== 0) {
691 snprintf(error_buf
, error_buf_size
, "Missing hostname");
697 if (at
[end_pos
] == ':') {
702 port
= bt_common_string_until(at
, "", "/", &end_pos
);
703 if (!port
|| port
->len
== 0) {
705 snprintf(error_buf
, error_buf_size
, "Missing port");
711 if (sscanf(port
->str
, "%d", &parts
.port
) != 1) {
713 snprintf(error_buf
, error_buf_size
,
714 "Invalid port: `%s`", port
->str
);
717 g_string_free(port
, TRUE
);
721 g_string_free(port
, TRUE
);
723 if (parts
.port
< 0 || parts
.port
>= 65536) {
725 snprintf(error_buf
, error_buf_size
,
726 "Invalid port: %d", parts
.port
);
733 if (at
[end_pos
] == '\0') {
740 if (strncmp(at
, "/host/", 6) != 0) {
742 snprintf(error_buf
, error_buf_size
,
743 "Expecting `/host/` after hostname or port");
751 /* Target hostname */
752 parts
.target_hostname
= bt_common_string_until(at
, "", "/", &end_pos
);
753 if (!parts
.target_hostname
|| parts
.target_hostname
->len
== 0) {
755 snprintf(error_buf
, error_buf_size
,
756 "Missing target hostname");
762 if (at
[end_pos
] == '\0') {
769 parts
.session_name
= bt_common_string_until(at
, "", "/", &end_pos
);
770 if (!parts
.session_name
|| parts
.session_name
->len
== 0) {
772 snprintf(error_buf
, error_buf_size
,
773 "Missing session name");
779 if (at
[end_pos
] == '/') {
781 snprintf(error_buf
, error_buf_size
,
782 "Unexpected `/` after session name (`%s`)",
783 parts
.session_name
->str
);
792 bt_common_destroy_lttng_live_url_parts(&parts
);
799 void bt_common_normalize_star_glob_pattern(char *pattern
)
803 bool got_star
= false;
807 for (p
= pattern
, np
= pattern
; *p
!= '\0'; p
++) {
811 /* Avoid consecutive stars. */
818 /* Copy backslash character. */
833 /* Copy single character. */
843 bool at_end_of_pattern(const char *p
, const char *pattern
, size_t pattern_len
)
845 return (p
- pattern
) == pattern_len
|| *p
== '\0';
849 * Globbing matching function with the star feature only (`?` and
850 * character sets are not supported). This matches `candidate` (plain
851 * string) against `pattern`. A literal star can be escaped with `\` in
854 * `pattern_len` or `candidate_len` can be greater than the actual
855 * string length of `pattern` or `candidate` if the string is
859 bool bt_common_star_glob_match(const char *pattern
, size_t pattern_len
,
860 const char *candidate
, size_t candidate_len
) {
861 const char *retry_c
= candidate
, *retry_p
= pattern
, *c
, *p
;
862 bool got_a_star
= false;
869 * The concept here is to retry a match in the specific case
870 * where we already got a star. The retry position for the
871 * pattern is just after the most recent star, and the retry
872 * position for the candidate is the character following the
873 * last try's first character.
877 * candidate: hi ev every onyx one
879 * pattern: hi*every*one
882 * candidate: hi ev every onyx one
884 * pattern: hi*every*one
887 * candidate: hi ev every onyx one
889 * pattern: hi*every*one
892 * candidate: hi ev every onyx one
894 * pattern: hi*every*one
897 * candidate: hi ev every onyx one
899 * pattern: hi*every*one
902 * candidate: hi ev every onyx one
904 * pattern: hi*every*one
907 * candidate: hi ev every onyx one
909 * pattern: hi*every*one
912 * candidate: hi ev every onyx one
914 * pattern: hi*every*one
917 * candidate: hi ev every onyx one
919 * pattern: hi*every*one
922 * candidate: hi ev every onyx one
924 * pattern: hi*every*one
927 * candidate: hi ev every onyx one
929 * pattern: hi*every*one
932 * candidate: hi ev every onyx one
934 * pattern: hi*every*one
937 * candidate: hi ev every onyx one
939 * pattern: hi*every*one
942 * candidate: hi ev every onyx one
944 * pattern: hi*every*one
947 * candidate: hi ev every onyx one
949 * pattern: hi*every*one
952 * candidate: hi ev every onyx one
954 * pattern: hi*every*one
957 * candidate: hi ev every onyx one
959 * pattern: hi*every*one
962 * candidate: hi ev every onyx one
964 * pattern: hi*every*one
967 * candidate: hi ev every onyx one
969 * pattern: hi*every*one
972 * candidate: hi ev every onyx one
974 * pattern: hi*every*one
977 * candidate: hi ev every onyx one
979 * pattern: hi*every*one
982 * candidate: hi ev every onyx one
984 * pattern: hi*every*one
987 * candidate: hi ev every onyx one
989 * pattern: hi*every*one
992 * candidate: hi ev every onyx one
994 * pattern: hi*every*one
997 * candidate: hi ev every onyx one
999 * pattern: hi*every*one
1002 * candidate: hi ev every onyx one
1004 * pattern: hi*every*one
1007 * candidate: hi ev every onyx one
1009 * pattern: hi*every*one
1012 while ((c
- candidate
) < candidate_len
&& *c
!= '\0') {
1015 if (at_end_of_pattern(p
, pattern
, pattern_len
)) {
1016 goto end_of_pattern
;
1024 * Our first try starts at the current candidate
1025 * character and after the star in the pattern.
1030 if (at_end_of_pattern(retry_p
, pattern
, pattern_len
)) {
1032 * Star at the end of the pattern at
1033 * this point: automatic match.
1040 /* Go to escaped character. */
1044 * Fall through the default case which compares
1045 * the escaped character now.
1049 if (at_end_of_pattern(p
, pattern
, pattern_len
) ||
1052 /* Character mismatch OR end of pattern. */
1055 * We didn't get any star yet,
1056 * so this first mismatch
1057 * automatically makes the whole
1064 * Next try: next candidate character,
1065 * original pattern character (following
1066 * the most recent star).
1074 /* Next pattern and candidate characters. */
1080 * We checked every candidate character and we're still in a
1081 * success state: the only pattern character allowed to remain
1084 if (at_end_of_pattern(p
, pattern
, pattern_len
)) {
1089 return p
[-1] == '*' && at_end_of_pattern(p
, pattern
, pattern_len
);
1094 GString
*bt_common_normalize_path(const char *path
, const char *wd
)
1097 GString
*norm_path
= NULL
;
1101 tmp
= _fullpath(NULL
, path
, PATH_MAX
);
1106 norm_path
= g_string_new(tmp
);
1114 g_string_free(norm_path
, TRUE
);
1123 void append_path_parts(const char *path
, GPtrArray
*parts
)
1125 const char *ch
= path
;
1126 const char *last
= path
;
1129 if (*ch
== G_DIR_SEPARATOR
|| *ch
== '\0') {
1130 if (ch
- last
> 0) {
1131 GString
*part
= g_string_new(NULL
);
1134 g_string_append_len(part
, last
, ch
- last
);
1135 g_ptr_array_add(parts
, part
);
1150 void destroy_gstring(void *gstring
)
1152 (void) g_string_free(gstring
, TRUE
);
1156 GString
*bt_common_normalize_path(const char *path
, const char *wd
)
1160 GPtrArray
*parts
= NULL
;
1163 norm_path
= g_string_new(G_DIR_SEPARATOR_S
);
1168 parts
= g_ptr_array_new_with_free_func(destroy_gstring
);
1173 if (path
[0] != G_DIR_SEPARATOR
) {
1174 /* Relative path: start with working directory */
1176 append_path_parts(wd
, parts
);
1178 gchar
*cd
= g_get_current_dir();
1180 append_path_parts(cd
, parts
);
1185 /* Append parts of the path parameter */
1186 append_path_parts(path
, parts
);
1188 /* Resolve special `..` and `.` parts */
1189 for (i
= 0; i
< parts
->len
; i
++) {
1190 GString
*part
= g_ptr_array_index(parts
, i
);
1192 if (strcmp(part
->str
, "..") == 0) {
1195 * First part of absolute path is `..`:
1201 /* Remove `..` and previous part */
1202 g_ptr_array_remove_index(parts
, i
- 1);
1203 g_ptr_array_remove_index(parts
, i
- 1);
1205 } else if (strcmp(part
->str
, ".") == 0) {
1207 g_ptr_array_remove_index(parts
, i
);
1212 /* Create normalized path with what's left */
1213 for (i
= 0; i
< parts
->len
; i
++) {
1214 GString
*part
= g_ptr_array_index(parts
, i
);
1216 g_string_append(norm_path
, part
->str
);
1218 if (i
< parts
->len
- 1) {
1219 g_string_append_c(norm_path
, G_DIR_SEPARATOR
);
1227 g_string_free(norm_path
, TRUE
);
1233 g_ptr_array_free(parts
, TRUE
);
1241 size_t bt_common_get_page_size(int log_level
)
1245 page_size
= bt_sysconf(_SC_PAGESIZE
);
1246 if (page_size
< 0) {
1247 BT_LOGF("Cannot get system's page size: ret=%d",
1255 #define BUF_STD_APPEND(...) \
1257 char _tmp_fmt[64]; \
1259 size_t _size = buf_size - (size_t) (*buf_ch - buf); \
1260 size_t _tmp_fmt_size = (size_t) (fmt_ch - *out_fmt_ch); \
1261 strncpy(_tmp_fmt, *out_fmt_ch, _tmp_fmt_size); \
1262 _tmp_fmt[_tmp_fmt_size] = '\0'; \
1263 _count = snprintf(*buf_ch, _size, _tmp_fmt, __VA_ARGS__); \
1264 BT_ASSERT(_count >= 0); \
1265 *buf_ch += MIN(_count, _size); \
1268 #define BUF_STD_APPEND_SINGLE_ARG(_type) \
1270 _type _arg = va_arg(*args, _type); \
1271 BUF_STD_APPEND(_arg); \
1274 static inline void handle_conversion_specifier_std(char *buf
, char **buf_ch
,
1275 size_t buf_size
, const char **out_fmt_ch
, va_list *args
)
1277 const char *fmt_ch
= *out_fmt_ch
;
1278 enum LENGTH_MODIFIER
{
1286 } length_mod
= LENGTH_MOD_NONE
;
1291 if (*fmt_ch
== '%') {
1317 if (*fmt_ch
< '0' || *fmt_ch
> '9') {
1325 if (*fmt_ch
== '.') {
1329 if (*fmt_ch
< '0' || *fmt_ch
> '9') {
1337 /* format (PRI*64) */
1338 if (strncmp(fmt_ch
, PRId64
, sizeof(PRId64
) - 1) == 0) {
1339 fmt_ch
+= sizeof(PRId64
) - 1;
1340 BUF_STD_APPEND_SINGLE_ARG(int64_t);
1342 } else if (strncmp(fmt_ch
, PRIu64
, sizeof(PRIu64
) - 1) == 0) {
1343 fmt_ch
+= sizeof(PRIu64
) - 1;
1344 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1346 } else if (strncmp(fmt_ch
, PRIx64
, sizeof(PRIx64
) - 1) == 0) {
1347 fmt_ch
+= sizeof(PRIx64
) - 1;
1348 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1350 } else if (strncmp(fmt_ch
, PRIX64
, sizeof(PRIX64
) - 1) == 0) {
1351 fmt_ch
+= sizeof(PRIX64
) - 1;
1352 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1354 } else if (strncmp(fmt_ch
, PRIo64
, sizeof(PRIo64
) - 1) == 0) {
1355 fmt_ch
+= sizeof(PRIo64
) - 1;
1356 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1358 } else if (strncmp(fmt_ch
, PRIi64
, sizeof(PRIi64
) - 1) == 0) {
1359 fmt_ch
+= sizeof(PRIi64
) - 1;
1360 BUF_STD_APPEND_SINGLE_ARG(int64_t);
1367 length_mod
= LENGTH_MOD_H
;
1370 if (*fmt_ch
== 'h') {
1371 length_mod
= LENGTH_MOD_HH
;
1377 length_mod
= LENGTH_MOD_LOW_L
;
1380 if (*fmt_ch
== 'l') {
1381 length_mod
= LENGTH_MOD_LOW_LL
;
1387 length_mod
= LENGTH_MOD_UP_L
;
1391 length_mod
= LENGTH_MOD_Z
;
1404 switch (length_mod
) {
1405 case LENGTH_MOD_NONE
:
1406 BUF_STD_APPEND_SINGLE_ARG(int);
1408 case LENGTH_MOD_LOW_L
:
1409 BUF_STD_APPEND_SINGLE_ARG(wint_t);
1419 switch (length_mod
) {
1420 case LENGTH_MOD_NONE
:
1421 BUF_STD_APPEND_SINGLE_ARG(char *);
1423 case LENGTH_MOD_LOW_L
:
1424 BUF_STD_APPEND_SINGLE_ARG(wchar_t *);
1434 switch (length_mod
) {
1435 case LENGTH_MOD_NONE
:
1438 BUF_STD_APPEND_SINGLE_ARG(int);
1440 case LENGTH_MOD_LOW_L
:
1441 BUF_STD_APPEND_SINGLE_ARG(long);
1443 case LENGTH_MOD_LOW_LL
:
1444 BUF_STD_APPEND_SINGLE_ARG(long long);
1447 BUF_STD_APPEND_SINGLE_ARG(size_t);
1459 switch (length_mod
) {
1460 case LENGTH_MOD_NONE
:
1463 BUF_STD_APPEND_SINGLE_ARG(unsigned int);
1465 case LENGTH_MOD_LOW_L
:
1466 BUF_STD_APPEND_SINGLE_ARG(unsigned long);
1468 case LENGTH_MOD_LOW_LL
:
1469 BUF_STD_APPEND_SINGLE_ARG(unsigned long long);
1472 BUF_STD_APPEND_SINGLE_ARG(size_t);
1486 switch (length_mod
) {
1487 case LENGTH_MOD_NONE
:
1488 BUF_STD_APPEND_SINGLE_ARG(double);
1490 case LENGTH_MOD_UP_L
:
1491 BUF_STD_APPEND_SINGLE_ARG(long double);
1500 if (length_mod
== LENGTH_MOD_NONE
) {
1501 BUF_STD_APPEND_SINGLE_ARG(void *);
1511 *out_fmt_ch
= fmt_ch
;
1515 void bt_common_custom_vsnprintf(char *buf
, size_t buf_size
,
1517 bt_common_handle_custom_specifier_func handle_specifier
,
1518 void *priv_data
, const char *fmt
, va_list *args
)
1520 const char *fmt_ch
= fmt
;
1526 while (*fmt_ch
!= '\0') {
1529 BT_ASSERT(fmt_ch
[1] != '\0');
1531 if (fmt_ch
[1] == intro
) {
1532 handle_specifier(priv_data
, &buf_ch
,
1533 buf_size
- (size_t) (buf_ch
- buf
),
1536 handle_conversion_specifier_std(buf
, &buf_ch
,
1537 buf_size
, &fmt_ch
, args
);
1540 if (buf_ch
>= buf
+ buf_size
- 1) {
1547 if (buf_ch
>= buf
+ buf_size
- 1) {
1559 void bt_common_custom_snprintf(char *buf
, size_t buf_size
,
1561 bt_common_handle_custom_specifier_func handle_specifier
,
1562 void *priv_data
, const char *fmt
, ...)
1565 va_start(args
, fmt
);
1566 bt_common_custom_vsnprintf(buf
, buf_size
, intro
, handle_specifier
,
1567 priv_data
, fmt
, &args
);
1572 void bt_common_sep_digits(char *str
, unsigned int digits_per_group
, char sep
)
1581 BT_ASSERT(digits_per_group
> 0);
1582 BT_ASSERT(sep
!= '\0');
1584 /* Compute new length of `str` */
1585 orig_len
= strlen(str
);
1586 BT_ASSERT(orig_len
> 0);
1587 sep_count
= (orig_len
- 1) / digits_per_group
;
1588 new_len
= strlen(str
) + sep_count
;
1591 * Do the work in place. Have the reading pointer `rd` start at
1592 * the end of the original string, and the writing pointer `wr`
1593 * start at the end of the new string, making sure to also put a
1594 * null character there.
1596 rd
= str
+ orig_len
- 1;
1602 * Here's what the process looks like (3 digits per group):
1606 * Destination: 12345678#8
1611 * Destination: 1234567878
1616 * Destination: 1234567678
1621 * Destination: 123456,678
1626 * Destination: 123455,678
1631 * Destination: 123445,678
1636 * Destination: 123345,678
1641 * Destination: 12,345,678
1646 * Destination: 12,345,678
1651 * Destination: 12,345,678
1654 while (rd
!= str
- 1) {
1655 if (i
== digits_per_group
) {
1657 * Time to append the separator: decrement `wr`,
1658 * but keep `rd` as is.
1666 /* Copy read-side character to write-side character */
1675 GString
*bt_common_fold(const char *str
, unsigned int total_length
,
1676 unsigned int indent
)
1678 const unsigned int content_length
= total_length
- indent
;
1679 GString
*folded
= g_string_new(NULL
);
1680 GString
*tmp_line
= g_string_new(NULL
);
1681 gchar
**lines
= NULL
;
1682 gchar
**line_words
= NULL
;
1683 gchar
* const *line
;
1687 BT_ASSERT(indent
< total_length
);
1688 BT_ASSERT(tmp_line
);
1691 if (strlen(str
) == 0) {
1692 /* Empty input string: empty output string */
1697 lines
= g_strsplit(str
, "\n", 0);
1700 /* For each source line */
1701 for (line
= lines
; *line
; line
++) {
1702 gchar
* const *word
;
1705 * Append empty line without indenting if source line is
1708 if (strlen(*line
) == 0) {
1709 g_string_append_c(folded
, '\n');
1714 line_words
= g_strsplit(*line
, " ", 0);
1715 BT_ASSERT(line_words
);
1718 * Indent for first line (we know there's at least one
1719 * word at this point).
1721 for (i
= 0; i
< indent
; i
++) {
1722 g_string_append_c(folded
, ' ');
1725 /* Append words, folding when necessary */
1726 g_string_assign(tmp_line
, "");
1728 for (word
= line_words
; *word
; word
++) {
1730 * `tmp_line->len > 0` is in the condition so
1731 * that words that are larger than
1732 * `content_length` are at least written on
1735 * `tmp_line->len - 1` because the temporary
1736 * line always contains a trailing space which
1737 * won't be part of the line if we fold.
1739 if (tmp_line
->len
> 0 &&
1740 tmp_line
->len
- 1 + strlen(*word
) >= content_length
) {
1741 /* Fold (without trailing space) */
1742 g_string_append_len(folded
,
1743 tmp_line
->str
, tmp_line
->len
- 1);
1744 g_string_append_c(folded
, '\n');
1746 /* Indent new line */
1747 for (i
= 0; i
< indent
; i
++) {
1748 g_string_append_c(folded
, ' ');
1751 g_string_assign(tmp_line
, "");
1754 /* Append current word and space to temporary line */
1755 g_string_append(tmp_line
, *word
);
1756 g_string_append_c(tmp_line
, ' ');
1759 /* Append last line if any, without trailing space */
1760 if (tmp_line
->len
> 0) {
1761 g_string_append_len(folded
, tmp_line
->str
,
1765 /* Append source newline */
1766 g_string_append_c(folded
, '\n');
1768 /* Free array of this line's words */
1769 g_strfreev(line_words
);
1773 /* Remove trailing newline if any */
1774 if (folded
->str
[folded
->len
- 1] == '\n') {
1775 g_string_truncate(folded
, folded
->len
- 1);
1784 g_strfreev(line_words
);
1788 g_string_free(tmp_line
, TRUE
);
1796 int bt_common_get_term_size(unsigned int *width
, unsigned int *height
)
1798 /* Not supported on Windows yet */
1801 #else /* __MINGW32__ */
1803 int bt_common_get_term_size(unsigned int *width
, unsigned int *height
)
1806 struct winsize winsize
;
1808 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &winsize
) < 0) {
1814 *width
= (unsigned int) winsize
.ws_col
;
1818 *height
= (unsigned int) winsize
.ws_row
;
1824 #endif /* __MINGW32__ */