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
);
523 GString
*bt_common_shell_quote(const char *input
, bool with_single_quotes
)
525 GString
*output
= g_string_new(NULL
);
527 bool no_quote
= true;
533 if (strlen(input
) == 0) {
534 if (with_single_quotes
) {
535 g_string_assign(output
, "''");
541 for (ch
= input
; *ch
!= '\0'; ch
++) {
544 if (!g_ascii_isalpha(c
) && !g_ascii_isdigit(c
) && c
!= '_' &&
545 c
!= '@' && c
!= '%' && c
!= '+' && c
!= '=' &&
546 c
!= ':' && c
!= ',' && c
!= '.' && c
!= '/' &&
554 g_string_assign(output
, input
);
558 if (with_single_quotes
) {
559 g_string_assign(output
, "'");
562 for (ch
= input
; *ch
!= '\0'; ch
++) {
564 g_string_append(output
, "'\"'\"'");
566 g_string_append_c(output
, *ch
);
570 if (with_single_quotes
) {
571 g_string_append_c(output
, '\'');
579 bool bt_common_string_is_printable(const char *input
)
582 bool printable
= true;
585 for (ch
= input
; *ch
!= '\0'; ch
++) {
586 if (!isprint(*ch
) && *ch
!= '\n' && *ch
!= '\r' &&
587 *ch
!= '\t' && *ch
!= '\v') {
598 void bt_common_destroy_lttng_live_url_parts(
599 struct bt_common_lttng_live_url_parts
*parts
)
606 g_string_free(parts
->proto
, TRUE
);
610 if (parts
->hostname
) {
611 g_string_free(parts
->hostname
, TRUE
);
612 parts
->hostname
= NULL
;
615 if (parts
->target_hostname
) {
616 g_string_free(parts
->target_hostname
, TRUE
);
617 parts
->target_hostname
= NULL
;
620 if (parts
->session_name
) {
621 g_string_free(parts
->session_name
, TRUE
);
622 parts
->session_name
= NULL
;
630 struct bt_common_lttng_live_url_parts
bt_common_parse_lttng_live_url(
631 const char *url
, char *error_buf
, size_t error_buf_size
)
633 struct bt_common_lttng_live_url_parts parts
;
634 const char *at
= url
;
638 memset(&parts
, 0, sizeof(parts
));
642 parts
.proto
= bt_common_string_until(at
, "", ":", &end_pos
);
643 if (!parts
.proto
|| parts
.proto
->len
== 0) {
645 snprintf(error_buf
, error_buf_size
, "Missing protocol");
651 if (strcmp(parts
.proto
->str
, "net") == 0) {
652 g_string_assign(parts
.proto
, "net4");
655 if (strcmp(parts
.proto
->str
, "net4") != 0 &&
656 strcmp(parts
.proto
->str
, "net6") != 0) {
658 snprintf(error_buf
, error_buf_size
,
659 "Unknown protocol: `%s`", parts
.proto
->str
);
665 if (at
[end_pos
] != ':') {
667 snprintf(error_buf
, error_buf_size
,
668 "Expecting `:` after `%s`", parts
.proto
->str
);
677 if (strncmp(at
, "://", 3) != 0) {
679 snprintf(error_buf
, error_buf_size
,
680 "Expecting `://` after protocol");
689 parts
.hostname
= bt_common_string_until(at
, "", ":/", &end_pos
);
690 if (!parts
.hostname
|| parts
.hostname
->len
== 0) {
692 snprintf(error_buf
, error_buf_size
, "Missing hostname");
698 if (at
[end_pos
] == ':') {
703 port
= bt_common_string_until(at
, "", "/", &end_pos
);
704 if (!port
|| port
->len
== 0) {
706 snprintf(error_buf
, error_buf_size
, "Missing port");
712 if (sscanf(port
->str
, "%d", &parts
.port
) != 1) {
714 snprintf(error_buf
, error_buf_size
,
715 "Invalid port: `%s`", port
->str
);
718 g_string_free(port
, TRUE
);
722 g_string_free(port
, TRUE
);
724 if (parts
.port
< 0 || parts
.port
>= 65536) {
726 snprintf(error_buf
, error_buf_size
,
727 "Invalid port: %d", parts
.port
);
734 if (at
[end_pos
] == '\0') {
741 if (strncmp(at
, "/host/", 6) != 0) {
743 snprintf(error_buf
, error_buf_size
,
744 "Expecting `/host/` after hostname or port");
752 /* Target hostname */
753 parts
.target_hostname
= bt_common_string_until(at
, "", "/", &end_pos
);
754 if (!parts
.target_hostname
|| parts
.target_hostname
->len
== 0) {
756 snprintf(error_buf
, error_buf_size
,
757 "Missing target hostname");
763 if (at
[end_pos
] == '\0') {
770 parts
.session_name
= bt_common_string_until(at
, "", "/", &end_pos
);
771 if (!parts
.session_name
|| parts
.session_name
->len
== 0) {
773 snprintf(error_buf
, error_buf_size
,
774 "Missing session name");
780 if (at
[end_pos
] == '/') {
782 snprintf(error_buf
, error_buf_size
,
783 "Unexpected `/` after session name (`%s`)",
784 parts
.session_name
->str
);
793 bt_common_destroy_lttng_live_url_parts(&parts
);
800 void bt_common_normalize_star_glob_pattern(char *pattern
)
804 bool got_star
= false;
808 for (p
= pattern
, np
= pattern
; *p
!= '\0'; p
++) {
812 /* Avoid consecutive stars. */
819 /* Copy backslash character. */
834 /* Copy single character. */
844 bool at_end_of_pattern(const char *p
, const char *pattern
, size_t pattern_len
)
846 return (p
- pattern
) == pattern_len
|| *p
== '\0';
850 * Globbing matching function with the star feature only (`?` and
851 * character sets are not supported). This matches `candidate` (plain
852 * string) against `pattern`. A literal star can be escaped with `\` in
855 * `pattern_len` or `candidate_len` can be greater than the actual
856 * string length of `pattern` or `candidate` if the string is
860 bool bt_common_star_glob_match(const char *pattern
, size_t pattern_len
,
861 const char *candidate
, size_t candidate_len
) {
862 const char *retry_c
= candidate
, *retry_p
= pattern
, *c
, *p
;
863 bool got_a_star
= false;
870 * The concept here is to retry a match in the specific case
871 * where we already got a star. The retry position for the
872 * pattern is just after the most recent star, and the retry
873 * position for the candidate is the character following the
874 * last try's first character.
878 * candidate: hi ev every onyx one
880 * pattern: hi*every*one
883 * candidate: hi ev every onyx one
885 * pattern: hi*every*one
888 * candidate: hi ev every onyx one
890 * pattern: hi*every*one
893 * candidate: hi ev every onyx one
895 * pattern: hi*every*one
898 * candidate: hi ev every onyx one
900 * pattern: hi*every*one
903 * candidate: hi ev every onyx one
905 * pattern: hi*every*one
908 * candidate: hi ev every onyx one
910 * pattern: hi*every*one
913 * candidate: hi ev every onyx one
915 * pattern: hi*every*one
918 * candidate: hi ev every onyx one
920 * pattern: hi*every*one
923 * candidate: hi ev every onyx one
925 * pattern: hi*every*one
928 * candidate: hi ev every onyx one
930 * pattern: hi*every*one
933 * candidate: hi ev every onyx one
935 * pattern: hi*every*one
938 * candidate: hi ev every onyx one
940 * pattern: hi*every*one
943 * candidate: hi ev every onyx one
945 * pattern: hi*every*one
948 * candidate: hi ev every onyx one
950 * pattern: hi*every*one
953 * candidate: hi ev every onyx one
955 * pattern: hi*every*one
958 * candidate: hi ev every onyx one
960 * pattern: hi*every*one
963 * candidate: hi ev every onyx one
965 * pattern: hi*every*one
968 * candidate: hi ev every onyx one
970 * pattern: hi*every*one
973 * candidate: hi ev every onyx one
975 * pattern: hi*every*one
978 * candidate: hi ev every onyx one
980 * pattern: hi*every*one
983 * candidate: hi ev every onyx one
985 * pattern: hi*every*one
988 * candidate: hi ev every onyx one
990 * pattern: hi*every*one
993 * candidate: hi ev every onyx one
995 * pattern: hi*every*one
998 * candidate: hi ev every onyx one
1000 * pattern: hi*every*one
1003 * candidate: hi ev every onyx one
1005 * pattern: hi*every*one
1008 * candidate: hi ev every onyx one
1010 * pattern: hi*every*one
1013 while ((c
- candidate
) < candidate_len
&& *c
!= '\0') {
1016 if (at_end_of_pattern(p
, pattern
, pattern_len
)) {
1017 goto end_of_pattern
;
1025 * Our first try starts at the current candidate
1026 * character and after the star in the pattern.
1031 if (at_end_of_pattern(retry_p
, pattern
, pattern_len
)) {
1033 * Star at the end of the pattern at
1034 * this point: automatic match.
1041 /* Go to escaped character. */
1045 * Fall through the default case which compares
1046 * the escaped character now.
1050 if (at_end_of_pattern(p
, pattern
, pattern_len
) ||
1053 /* Character mismatch OR end of pattern. */
1056 * We didn't get any star yet,
1057 * so this first mismatch
1058 * automatically makes the whole
1065 * Next try: next candidate character,
1066 * original pattern character (following
1067 * the most recent star).
1075 /* Next pattern and candidate characters. */
1081 * We checked every candidate character and we're still in a
1082 * success state: the only pattern character allowed to remain
1085 if (at_end_of_pattern(p
, pattern
, pattern_len
)) {
1090 return p
[-1] == '*' && at_end_of_pattern(p
, pattern
, pattern_len
);
1095 GString
*bt_common_normalize_path(const char *path
, const char *wd
)
1098 GString
*norm_path
= NULL
;
1102 tmp
= _fullpath(NULL
, path
, PATH_MAX
);
1107 norm_path
= g_string_new(tmp
);
1115 g_string_free(norm_path
, TRUE
);
1124 void append_path_parts(const char *path
, GPtrArray
*parts
)
1126 const char *ch
= path
;
1127 const char *last
= path
;
1130 if (*ch
== G_DIR_SEPARATOR
|| *ch
== '\0') {
1131 if (ch
- last
> 0) {
1132 GString
*part
= g_string_new(NULL
);
1135 g_string_append_len(part
, last
, ch
- last
);
1136 g_ptr_array_add(parts
, part
);
1151 void destroy_gstring(void *gstring
)
1153 (void) g_string_free(gstring
, TRUE
);
1157 GString
*bt_common_normalize_path(const char *path
, const char *wd
)
1161 GPtrArray
*parts
= NULL
;
1164 norm_path
= g_string_new(G_DIR_SEPARATOR_S
);
1169 parts
= g_ptr_array_new_with_free_func(destroy_gstring
);
1174 if (path
[0] != G_DIR_SEPARATOR
) {
1175 /* Relative path: start with working directory */
1177 append_path_parts(wd
, parts
);
1179 gchar
*cd
= g_get_current_dir();
1181 append_path_parts(cd
, parts
);
1186 /* Append parts of the path parameter */
1187 append_path_parts(path
, parts
);
1189 /* Resolve special `..` and `.` parts */
1190 for (i
= 0; i
< parts
->len
; i
++) {
1191 GString
*part
= g_ptr_array_index(parts
, i
);
1193 if (strcmp(part
->str
, "..") == 0) {
1196 * First part of absolute path is `..`:
1202 /* Remove `..` and previous part */
1203 g_ptr_array_remove_index(parts
, i
- 1);
1204 g_ptr_array_remove_index(parts
, i
- 1);
1206 } else if (strcmp(part
->str
, ".") == 0) {
1208 g_ptr_array_remove_index(parts
, i
);
1213 /* Create normalized path with what's left */
1214 for (i
= 0; i
< parts
->len
; i
++) {
1215 GString
*part
= g_ptr_array_index(parts
, i
);
1217 g_string_append(norm_path
, part
->str
);
1219 if (i
< parts
->len
- 1) {
1220 g_string_append_c(norm_path
, G_DIR_SEPARATOR
);
1228 g_string_free(norm_path
, TRUE
);
1234 g_ptr_array_free(parts
, TRUE
);
1242 size_t bt_common_get_page_size(int log_level
)
1246 page_size
= bt_sysconf(_SC_PAGESIZE
);
1247 if (page_size
< 0) {
1248 BT_LOGF("Cannot get system's page size: ret=%d",
1256 #define BUF_STD_APPEND(...) \
1258 char _tmp_fmt[64]; \
1260 size_t _size = buf_size - (size_t) (*buf_ch - buf); \
1261 size_t _tmp_fmt_size = (size_t) (fmt_ch - *out_fmt_ch); \
1262 strncpy(_tmp_fmt, *out_fmt_ch, _tmp_fmt_size); \
1263 _tmp_fmt[_tmp_fmt_size] = '\0'; \
1264 _count = snprintf(*buf_ch, _size, _tmp_fmt, __VA_ARGS__); \
1265 BT_ASSERT(_count >= 0); \
1266 *buf_ch += MIN(_count, _size); \
1269 #define BUF_STD_APPEND_SINGLE_ARG(_type) \
1271 _type _arg = va_arg(*args, _type); \
1272 BUF_STD_APPEND(_arg); \
1275 static inline void handle_conversion_specifier_std(char *buf
, char **buf_ch
,
1276 size_t buf_size
, const char **out_fmt_ch
, va_list *args
)
1278 const char *fmt_ch
= *out_fmt_ch
;
1279 enum LENGTH_MODIFIER
{
1287 } length_mod
= LENGTH_MOD_NONE
;
1292 if (*fmt_ch
== '%') {
1318 if (*fmt_ch
< '0' || *fmt_ch
> '9') {
1326 if (*fmt_ch
== '.') {
1330 if (*fmt_ch
< '0' || *fmt_ch
> '9') {
1338 /* format (PRI*64) */
1339 if (strncmp(fmt_ch
, PRId64
, sizeof(PRId64
) - 1) == 0) {
1340 fmt_ch
+= sizeof(PRId64
) - 1;
1341 BUF_STD_APPEND_SINGLE_ARG(int64_t);
1343 } else if (strncmp(fmt_ch
, PRIu64
, sizeof(PRIu64
) - 1) == 0) {
1344 fmt_ch
+= sizeof(PRIu64
) - 1;
1345 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1347 } else if (strncmp(fmt_ch
, PRIx64
, sizeof(PRIx64
) - 1) == 0) {
1348 fmt_ch
+= sizeof(PRIx64
) - 1;
1349 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1351 } else if (strncmp(fmt_ch
, PRIX64
, sizeof(PRIX64
) - 1) == 0) {
1352 fmt_ch
+= sizeof(PRIX64
) - 1;
1353 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1355 } else if (strncmp(fmt_ch
, PRIo64
, sizeof(PRIo64
) - 1) == 0) {
1356 fmt_ch
+= sizeof(PRIo64
) - 1;
1357 BUF_STD_APPEND_SINGLE_ARG(uint64_t);
1359 } else if (strncmp(fmt_ch
, PRIi64
, sizeof(PRIi64
) - 1) == 0) {
1360 fmt_ch
+= sizeof(PRIi64
) - 1;
1361 BUF_STD_APPEND_SINGLE_ARG(int64_t);
1368 length_mod
= LENGTH_MOD_H
;
1371 if (*fmt_ch
== 'h') {
1372 length_mod
= LENGTH_MOD_HH
;
1378 length_mod
= LENGTH_MOD_LOW_L
;
1381 if (*fmt_ch
== 'l') {
1382 length_mod
= LENGTH_MOD_LOW_LL
;
1388 length_mod
= LENGTH_MOD_UP_L
;
1392 length_mod
= LENGTH_MOD_Z
;
1405 switch (length_mod
) {
1406 case LENGTH_MOD_NONE
:
1407 BUF_STD_APPEND_SINGLE_ARG(int);
1409 case LENGTH_MOD_LOW_L
:
1410 BUF_STD_APPEND_SINGLE_ARG(wint_t);
1420 switch (length_mod
) {
1421 case LENGTH_MOD_NONE
:
1422 BUF_STD_APPEND_SINGLE_ARG(char *);
1424 case LENGTH_MOD_LOW_L
:
1425 BUF_STD_APPEND_SINGLE_ARG(wchar_t *);
1435 switch (length_mod
) {
1436 case LENGTH_MOD_NONE
:
1439 BUF_STD_APPEND_SINGLE_ARG(int);
1441 case LENGTH_MOD_LOW_L
:
1442 BUF_STD_APPEND_SINGLE_ARG(long);
1444 case LENGTH_MOD_LOW_LL
:
1445 BUF_STD_APPEND_SINGLE_ARG(long long);
1448 BUF_STD_APPEND_SINGLE_ARG(size_t);
1460 switch (length_mod
) {
1461 case LENGTH_MOD_NONE
:
1464 BUF_STD_APPEND_SINGLE_ARG(unsigned int);
1466 case LENGTH_MOD_LOW_L
:
1467 BUF_STD_APPEND_SINGLE_ARG(unsigned long);
1469 case LENGTH_MOD_LOW_LL
:
1470 BUF_STD_APPEND_SINGLE_ARG(unsigned long long);
1473 BUF_STD_APPEND_SINGLE_ARG(size_t);
1487 switch (length_mod
) {
1488 case LENGTH_MOD_NONE
:
1489 BUF_STD_APPEND_SINGLE_ARG(double);
1491 case LENGTH_MOD_UP_L
:
1492 BUF_STD_APPEND_SINGLE_ARG(long double);
1501 if (length_mod
== LENGTH_MOD_NONE
) {
1502 BUF_STD_APPEND_SINGLE_ARG(void *);
1512 *out_fmt_ch
= fmt_ch
;
1516 void bt_common_custom_vsnprintf(char *buf
, size_t buf_size
,
1518 bt_common_handle_custom_specifier_func handle_specifier
,
1519 void *priv_data
, const char *fmt
, va_list *args
)
1521 const char *fmt_ch
= fmt
;
1527 while (*fmt_ch
!= '\0') {
1530 BT_ASSERT(fmt_ch
[1] != '\0');
1532 if (fmt_ch
[1] == intro
) {
1533 handle_specifier(priv_data
, &buf_ch
,
1534 buf_size
- (size_t) (buf_ch
- buf
),
1537 handle_conversion_specifier_std(buf
, &buf_ch
,
1538 buf_size
, &fmt_ch
, args
);
1541 if (buf_ch
>= buf
+ buf_size
- 1) {
1548 if (buf_ch
>= buf
+ buf_size
- 1) {
1560 void bt_common_custom_snprintf(char *buf
, size_t buf_size
,
1562 bt_common_handle_custom_specifier_func handle_specifier
,
1563 void *priv_data
, const char *fmt
, ...)
1566 va_start(args
, fmt
);
1567 bt_common_custom_vsnprintf(buf
, buf_size
, intro
, handle_specifier
,
1568 priv_data
, fmt
, &args
);
1573 void bt_common_sep_digits(char *str
, unsigned int digits_per_group
, char sep
)
1582 BT_ASSERT(digits_per_group
> 0);
1583 BT_ASSERT(sep
!= '\0');
1585 /* Compute new length of `str` */
1586 orig_len
= strlen(str
);
1587 BT_ASSERT(orig_len
> 0);
1588 sep_count
= (orig_len
- 1) / digits_per_group
;
1589 new_len
= strlen(str
) + sep_count
;
1592 * Do the work in place. Have the reading pointer `rd` start at
1593 * the end of the original string, and the writing pointer `wr`
1594 * start at the end of the new string, making sure to also put a
1595 * null character there.
1597 rd
= str
+ orig_len
- 1;
1603 * Here's what the process looks like (3 digits per group):
1607 * Destination: 12345678#8
1612 * Destination: 1234567878
1617 * Destination: 1234567678
1622 * Destination: 123456,678
1627 * Destination: 123455,678
1632 * Destination: 123445,678
1637 * Destination: 123345,678
1642 * Destination: 12,345,678
1647 * Destination: 12,345,678
1652 * Destination: 12,345,678
1655 while (rd
!= str
- 1) {
1656 if (i
== digits_per_group
) {
1658 * Time to append the separator: decrement `wr`,
1659 * but keep `rd` as is.
1667 /* Copy read-side character to write-side character */
1676 GString
*bt_common_fold(const char *str
, unsigned int total_length
,
1677 unsigned int indent
)
1679 const unsigned int content_length
= total_length
- indent
;
1680 GString
*folded
= g_string_new(NULL
);
1681 GString
*tmp_line
= g_string_new(NULL
);
1682 gchar
**lines
= NULL
;
1683 gchar
**line_words
= NULL
;
1684 gchar
* const *line
;
1688 BT_ASSERT(indent
< total_length
);
1689 BT_ASSERT(tmp_line
);
1692 if (strlen(str
) == 0) {
1693 /* Empty input string: empty output string */
1698 lines
= g_strsplit(str
, "\n", 0);
1701 /* For each source line */
1702 for (line
= lines
; *line
; line
++) {
1703 gchar
* const *word
;
1706 * Append empty line without indenting if source line is
1709 if (strlen(*line
) == 0) {
1710 g_string_append_c(folded
, '\n');
1715 line_words
= g_strsplit(*line
, " ", 0);
1716 BT_ASSERT(line_words
);
1719 * Indent for first line (we know there's at least one
1720 * word at this point).
1722 for (i
= 0; i
< indent
; i
++) {
1723 g_string_append_c(folded
, ' ');
1726 /* Append words, folding when necessary */
1727 g_string_assign(tmp_line
, "");
1729 for (word
= line_words
; *word
; word
++) {
1731 * `tmp_line->len > 0` is in the condition so
1732 * that words that are larger than
1733 * `content_length` are at least written on
1736 * `tmp_line->len - 1` because the temporary
1737 * line always contains a trailing space which
1738 * won't be part of the line if we fold.
1740 if (tmp_line
->len
> 0 &&
1741 tmp_line
->len
- 1 + strlen(*word
) >= content_length
) {
1742 /* Fold (without trailing space) */
1743 g_string_append_len(folded
,
1744 tmp_line
->str
, tmp_line
->len
- 1);
1745 g_string_append_c(folded
, '\n');
1747 /* Indent new line */
1748 for (i
= 0; i
< indent
; i
++) {
1749 g_string_append_c(folded
, ' ');
1752 g_string_assign(tmp_line
, "");
1755 /* Append current word and space to temporary line */
1756 g_string_append(tmp_line
, *word
);
1757 g_string_append_c(tmp_line
, ' ');
1760 /* Append last line if any, without trailing space */
1761 if (tmp_line
->len
> 0) {
1762 g_string_append_len(folded
, tmp_line
->str
,
1766 /* Append source newline */
1767 g_string_append_c(folded
, '\n');
1769 /* Free array of this line's words */
1770 g_strfreev(line_words
);
1774 /* Remove trailing newline if any */
1775 if (folded
->str
[folded
->len
- 1] == '\n') {
1776 g_string_truncate(folded
, folded
->len
- 1);
1784 BT_ASSERT(!line_words
);
1787 g_string_free(tmp_line
, TRUE
);
1795 int bt_common_get_term_size(unsigned int *width
, unsigned int *height
)
1797 /* Not supported on Windows yet */
1800 #else /* __MINGW32__ */
1802 int bt_common_get_term_size(unsigned int *width
, unsigned int *height
)
1805 struct winsize winsize
;
1807 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &winsize
) < 0) {
1813 *width
= (unsigned int) winsize
.ws_col
;
1817 *height
= (unsigned int) winsize
.ws_row
;
1823 #endif /* __MINGW32__ */
1826 int bt_common_g_string_append_printf(GString
*str
, const char *fmt
, ...)
1829 gsize len
, allocated_len
, available_len
;
1832 /* str->len excludes \0. */
1834 /* Explicitly exclude \0. */
1835 allocated_len
= str
->allocated_len
- 1;
1836 available_len
= allocated_len
- len
;
1838 str
->len
= allocated_len
;
1840 print_len
= vsnprintf(str
->str
+ len
, available_len
+ 1, fmt
, ap
);
1842 if (print_len
< 0) {
1845 if (G_UNLIKELY(available_len
< print_len
)) {
1847 g_string_set_size(str
, len
+ print_len
);
1849 print_len
= vsprintf(str
->str
+ len
, fmt
, ap
);
1852 str
->len
= len
+ print_len
;