diff options
99 files changed, 687 insertions, 955 deletions
diff --git a/meson.build b/meson.build index 366f2c5607..5735cfc7ad 100644 --- a/meson.build +++ b/meson.build @@ -322,7 +322,6 @@ basic_disabled_warnings = [ '-Wno-format-signedness', '-Wno-missing-field-initializers', '-Wno-unused-parameter', - '-Wno-unused-result', ] possible_common_cc_flags = [ @@ -366,6 +365,12 @@ if cc.get_id() == 'gcc' and (not '02'.contains(get_option('optimization')) or possible_common_cc_flags += '-Wno-maybe-uninitialized' endif +# Disable -Wno-unused-result with gcc, see +# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425. +if cc.get_id() == 'gcc' + possible_common_cc_flags += '-Wno-unused-result' +endif + # --as-needed and --no-undefined are provided by meson by default, # run mesonconf to see what is enabled possible_link_flags = [ diff --git a/src/analyze/analyze-security.c b/src/analyze/analyze-security.c index f20606c17c..4d41834c3f 100644 --- a/src/analyze/analyze-security.c +++ b/src/analyze/analyze-security.c @@ -583,11 +583,12 @@ static int assess_system_call_filter( assert(a->parameter < _SYSCALL_FILTER_SET_MAX); const SyscallFilterSet *f = syscall_filter_sets + a->parameter; - char *d = NULL; + _cleanup_free_ char *d = NULL; uint64_t b; + int r; if (!info->system_call_filter_allow_list && set_isempty(info->system_call_filter)) { - d = strdup("Service does not filter system calls"); + r = free_and_strdup(&d, "Service does not filter system calls"); b = 10; } else { bool bad; @@ -599,34 +600,33 @@ static int assess_system_call_filter( if (info->system_call_filter_allow_list) { if (bad) { - (void) asprintf(&d, "System call allow list defined for service, and %s is included " - "(e.g. %s is allowed)", - f->name, offender); + r = asprintf(&d, "System call allow list defined for service, and %s is included " + "(e.g. %s is allowed)", + f->name, offender); b = 9; } else { - (void) asprintf(&d, "System call allow list defined for service, and %s is not included", - f->name); + r = asprintf(&d, "System call allow list defined for service, and %s is not included", + f->name); b = 0; } } else { if (bad) { - (void) asprintf(&d, "System call deny list defined for service, and %s is not included " - "(e.g. %s is allowed)", - f->name, offender); + r = asprintf(&d, "System call deny list defined for service, and %s is not included " + "(e.g. %s is allowed)", + f->name, offender); b = 10; } else { - (void) asprintf(&d, "System call deny list defined for service, and %s is included", - f->name); + r = asprintf(&d, "System call deny list defined for service, and %s is included", + f->name); b = 0; } } } - - if (!d) + if (r < 0) return log_oom(); *ret_badness = b; - *ret_description = d; + *ret_description = TAKE_PTR(d); return 0; } diff --git a/src/analyze/analyze.c b/src/analyze/analyze.c index 62c0ccbdfe..c4685752f6 100644 --- a/src/analyze/analyze.c +++ b/src/analyze/analyze.c @@ -479,7 +479,6 @@ manager: } static int pretty_boot_time(sd_bus *bus, char **_buf) { - char ts[FORMAT_TIMESPAN_MAX]; BootTimes *t; static char buf[4096]; size_t size; @@ -524,23 +523,23 @@ static int pretty_boot_time(sd_bus *bus, char **_buf) { size = strpcpyf(&ptr, size, "Startup finished in "); if (t->firmware_time > 0) - size = strpcpyf(&ptr, size, "%s (firmware) + ", format_timespan(ts, sizeof(ts), t->firmware_time - t->loader_time, USEC_PER_MSEC)); + size = strpcpyf(&ptr, size, "%s (firmware) + ", FORMAT_TIMESPAN(t->firmware_time - t->loader_time, USEC_PER_MSEC)); if (t->loader_time > 0) - size = strpcpyf(&ptr, size, "%s (loader) + ", format_timespan(ts, sizeof(ts), t->loader_time, USEC_PER_MSEC)); + size = strpcpyf(&ptr, size, "%s (loader) + ", FORMAT_TIMESPAN(t->loader_time, USEC_PER_MSEC)); if (t->kernel_done_time > 0) - size = strpcpyf(&ptr, size, "%s (kernel) + ", format_timespan(ts, sizeof(ts), t->kernel_done_time, USEC_PER_MSEC)); + size = strpcpyf(&ptr, size, "%s (kernel) + ", FORMAT_TIMESPAN(t->kernel_done_time, USEC_PER_MSEC)); if (t->initrd_time > 0) - size = strpcpyf(&ptr, size, "%s (initrd) + ", format_timespan(ts, sizeof(ts), t->userspace_time - t->initrd_time, USEC_PER_MSEC)); + size = strpcpyf(&ptr, size, "%s (initrd) + ", FORMAT_TIMESPAN(t->userspace_time - t->initrd_time, USEC_PER_MSEC)); - size = strpcpyf(&ptr, size, "%s (userspace) ", format_timespan(ts, sizeof(ts), t->finish_time - t->userspace_time, USEC_PER_MSEC)); + size = strpcpyf(&ptr, size, "%s (userspace) ", FORMAT_TIMESPAN(t->finish_time - t->userspace_time, USEC_PER_MSEC)); if (t->kernel_done_time > 0) - strpcpyf(&ptr, size, "= %s ", format_timespan(ts, sizeof(ts), t->firmware_time + t->finish_time, USEC_PER_MSEC)); + strpcpyf(&ptr, size, "= %s ", FORMAT_TIMESPAN(t->firmware_time + t->finish_time, USEC_PER_MSEC)); if (unit_id && timestamp_is_set(activated_time)) { usec_t base = t->userspace_time > 0 ? t->userspace_time : t->reverse_offset; size = strpcpyf(&ptr, size, "\n%s reached after %s in userspace", unit_id, - format_timespan(ts, sizeof(ts), activated_time - base, USEC_PER_MSEC)); + FORMAT_TIMESPAN(activated_time - base, USEC_PER_MSEC)); } else if (unit_id && activated_time == 0) size = strpcpyf(&ptr, size, "\n%s was never reached", unit_id); else if (unit_id && activated_time == USEC_INFINITY) @@ -591,7 +590,6 @@ static void svg_graph_box(double height, double begin, double end) { } static int plot_unit_times(UnitTimes *u, double width, int y) { - char ts[FORMAT_TIMESPAN_MAX]; bool b; if (!u->name) @@ -605,7 +603,7 @@ static int plot_unit_times(UnitTimes *u, double width, int y) { b = u->activating * SCALE_X < width / 2; if (u->time) svg_text(b, u->activating, y, "%s (%s)", - u->name, format_timespan(ts, sizeof(ts), u->time, USEC_PER_MSEC)); + u->name, FORMAT_TIMESPAN(u->time, USEC_PER_MSEC)); else svg_text(b, u->activating, y, "%s", u->name); @@ -836,8 +834,6 @@ static int list_dependencies_print( UnitTimes *times, BootTimes *boot) { - char ts[FORMAT_TIMESPAN_MAX], ts2[FORMAT_TIMESPAN_MAX]; - for (unsigned i = level; i != 0; i--) printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE)); @@ -846,10 +842,10 @@ static int list_dependencies_print( if (times) { if (times->time > 0) printf("%s%s @%s +%s%s", ansi_highlight_red(), name, - format_timespan(ts, sizeof(ts), times->activating - boot->userspace_time, USEC_PER_MSEC), - format_timespan(ts2, sizeof(ts2), times->time, USEC_PER_MSEC), ansi_normal()); + FORMAT_TIMESPAN(times->activating - boot->userspace_time, USEC_PER_MSEC), + FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal()); else if (times->activated > boot->userspace_time) - printf("%s @%s", name, format_timespan(ts, sizeof(ts), times->activated - boot->userspace_time, USEC_PER_MSEC)); + printf("%s @%s", name, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC)); else printf("%s", name); } else @@ -964,7 +960,6 @@ static int list_dependencies_one(sd_bus *bus, const char *name, unsigned level, static int list_dependencies(sd_bus *bus, const char *name) { _cleanup_strv_free_ char **units = NULL; - char ts[FORMAT_TIMESPAN_MAX]; UnitTimes *times; int r; const char *id; @@ -1004,9 +999,10 @@ static int list_dependencies(sd_bus *bus, const char *name) { if (times) { if (times->time) printf("%s%s +%s%s\n", ansi_highlight_red(), id, - format_timespan(ts, sizeof(ts), times->time, USEC_PER_MSEC), ansi_normal()); + FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal()); else if (times->activated > boot->userspace_time) - printf("%s @%s\n", id, format_timespan(ts, sizeof(ts), times->activated - boot->userspace_time, USEC_PER_MSEC)); + printf("%s @%s\n", id, + FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC)); else printf("%s\n", id); } diff --git a/src/basic/efivars.c b/src/basic/efivars.c index 77d969c635..3e5c5e68dd 100644 --- a/src/basic/efivars.c +++ b/src/basic/efivars.c @@ -120,13 +120,10 @@ int efi_get_variable( n = st.st_size - 4; if (DEBUG_LOGGING) { - char ts[FORMAT_TIMESPAN_MAX]; - usec_t end; - - end = now(CLOCK_MONOTONIC); + usec_t end = now(CLOCK_MONOTONIC); if (end > begin + EFI_RETRY_DELAY) log_debug("Detected slow EFI variable read access on %s: %s", - variable, format_timespan(ts, sizeof(ts), end - begin, 1)); + variable, FORMAT_TIMESPAN(end - begin, 1)); } /* Note that efivarfs interestingly doesn't require ftruncate() to update an existing EFI variable diff --git a/src/basic/ether-addr-util.h b/src/basic/ether-addr-util.h index 63447910c0..794fc55bb8 100644 --- a/src/basic/ether-addr-util.h +++ b/src/basic/ether-addr-util.h @@ -23,7 +23,9 @@ struct hw_addr_data { #define HW_ADDR_TO_STRING_MAX (3*HW_ADDR_MAX_SIZE) char* hw_addr_to_string(const struct hw_addr_data *addr, char buffer[HW_ADDR_TO_STRING_MAX]); -/* Use only as function argument, never stand-alone! */ +/* Note: the lifetime of the compound literal is the immediately surrounding block, + * see C11 §6.5.2.5, and + * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */ #define HW_ADDR_TO_STR(hw_addr) hw_addr_to_string((hw_addr), (char[HW_ADDR_TO_STRING_MAX]){}) #define HW_ADDR_NULL ((const struct hw_addr_data){}) diff --git a/src/basic/format-util.h b/src/basic/format-util.h index b7e18768e3..579f231897 100644 --- a/src/basic/format-util.h +++ b/src/basic/format-util.h @@ -74,16 +74,17 @@ typedef enum { #define FORMAT_BYTES_MAX 16U -char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag); +char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag) _warn_unused_result_; +_warn_unused_result_ static inline char *format_bytes(char *buf, size_t l, uint64_t t) { return format_bytes_full(buf, l, t, FORMAT_BYTES_USE_IEC | FORMAT_BYTES_BELOW_POINT | FORMAT_BYTES_TRAILING_B); } -static inline char *format_bytes_cgroup_protection(char *buf, size_t l, uint64_t t) { - if (t == CGROUP_LIMIT_MAX) { - (void) snprintf(buf, l, "%s", "infinity"); - return buf; - } - return format_bytes(buf, l, t); -} +/* Note: the lifetime of the compound literal is the immediately surrounding block, + * see C11 §6.5.2.5, and + * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */ +#define FORMAT_BYTES(t) format_bytes((char[FORMAT_BYTES_MAX]){}, FORMAT_BYTES_MAX, t) +#define FORMAT_BYTES_FULL(t, flag) format_bytes_full((char[FORMAT_BYTES_MAX]){}, FORMAT_BYTES_MAX, t, flag) + +#define FORMAT_BYTES_CGROUP_PROTECTION(t) (t == CGROUP_LIMIT_MAX ? "infinity" : FORMAT_BYTES(t)) diff --git a/src/basic/macro.h b/src/basic/macro.h index 072fed4378..a8476184c2 100644 --- a/src/basic/macro.h +++ b/src/basic/macro.h @@ -30,6 +30,7 @@ #define _weakref_(x) __attribute__((__weakref__(#x))) #define _alignas_(x) __attribute__((__aligned__(__alignof(x)))) #define _alignptr_ __attribute__((__aligned__(sizeof(void*)))) +#define _warn_unused_result_ __attribute__((__warn_unused_result__)) #if __GNUC__ >= 7 #define _fallthrough_ __attribute__((__fallthrough__)) #else @@ -213,7 +214,7 @@ static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) { * Contrary to strlen(), this is a constant expression. * @x: a string literal. */ -#define STRLEN(x) (sizeof(""x"") - 1) +#define STRLEN(x) ((unsigned) sizeof(""x"") - 1) /* * container_of - cast a member of a structure out to the containing structure @@ -341,10 +342,10 @@ static inline int __coverity_check_and_return__(int condition) { * negative '-' prefix (hence works correctly on signed * types). Includes space for the trailing NUL. */ #define DECIMAL_STR_MAX(type) \ - (2+(sizeof(type) <= 1 ? 3 : \ - sizeof(type) <= 2 ? 5 : \ - sizeof(type) <= 4 ? 10 : \ - sizeof(type) <= 8 ? 20 : sizeof(int[-2*(sizeof(type) > 8)]))) + (2U+(sizeof(type) <= 1 ? 3U : \ + sizeof(type) <= 2 ? 5U : \ + sizeof(type) <= 4 ? 10U : \ + sizeof(type) <= 8 ? 20U : (unsigned) sizeof(int[-2*(sizeof(type) > 8)]))) #define DECIMAL_STR_WIDTH(x) \ ({ \ diff --git a/src/basic/rlimit-util.c b/src/basic/rlimit-util.c index 23d108d5df..1ab41c6974 100644 --- a/src/basic/rlimit-util.c +++ b/src/basic/rlimit-util.c @@ -300,26 +300,26 @@ int rlimit_parse(int resource, const char *val, struct rlimit *ret) { } int rlimit_format(const struct rlimit *rl, char **ret) { - char *s = NULL; + _cleanup_free_ char *s = NULL; + int r; assert(rl); assert(ret); if (rl->rlim_cur >= RLIM_INFINITY && rl->rlim_max >= RLIM_INFINITY) - s = strdup("infinity"); + r = free_and_strdup(&s, "infinity"); else if (rl->rlim_cur >= RLIM_INFINITY) - (void) asprintf(&s, "infinity:" RLIM_FMT, rl->rlim_max); + r = asprintf(&s, "infinity:" RLIM_FMT, rl->rlim_max); else if (rl->rlim_max >= RLIM_INFINITY) - (void) asprintf(&s, RLIM_FMT ":infinity", rl->rlim_cur); + r = asprintf(&s, RLIM_FMT ":infinity", rl->rlim_cur); else if (rl->rlim_cur == rl->rlim_max) - (void) asprintf(&s, RLIM_FMT, rl->rlim_cur); + r = asprintf(&s, RLIM_FMT, rl->rlim_cur); else - (void) asprintf(&s, RLIM_FMT ":" RLIM_FMT, rl->rlim_cur, rl->rlim_max); - - if (!s) + r = asprintf(&s, RLIM_FMT ":" RLIM_FMT, rl->rlim_cur, rl->rlim_max); + if (r < 0) return -ENOMEM; - *ret = s; + *ret = TAKE_PTR(s); return 0; } diff --git a/src/basic/time-util.h b/src/basic/time-util.h index 2bd947d6a8..895af88299 100644 --- a/src/basic/time-util.h +++ b/src/basic/time-util.h @@ -111,20 +111,31 @@ usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock); usec_t timespec_load(const struct timespec *ts) _pure_; nsec_t timespec_load_nsec(const struct timespec *ts) _pure_; -struct timespec *timespec_store(struct timespec *ts, usec_t u); -struct timespec *timespec_store_nsec(struct timespec *ts, nsec_t n); +struct timespec* timespec_store(struct timespec *ts, usec_t u); +struct timespec* timespec_store_nsec(struct timespec *ts, nsec_t n); usec_t timeval_load(const struct timeval *tv) _pure_; -struct timeval *timeval_store(struct timeval *tv, usec_t u); +struct timeval* timeval_store(struct timeval *tv, usec_t u); -char *format_timestamp_style(char *buf, size_t l, usec_t t, TimestampStyle style); -char *format_timestamp_relative(char *buf, size_t l, usec_t t); -char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy); +char* format_timestamp_style(char *buf, size_t l, usec_t t, TimestampStyle style) _warn_unused_result_; +char* format_timestamp_relative(char *buf, size_t l, usec_t t) _warn_unused_result_; +char* format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) _warn_unused_result_; -static inline char *format_timestamp(char *buf, size_t l, usec_t t) { +_warn_unused_result_ +static inline char* format_timestamp(char *buf, size_t l, usec_t t) { return format_timestamp_style(buf, l, t, TIMESTAMP_PRETTY); } +/* Note: the lifetime of the compound literal is the immediately surrounding block, + * see C11 §6.5.2.5, and + * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */ +#define FORMAT_TIMESTAMP(t) format_timestamp((char[FORMAT_TIMESTAMP_MAX]){}, FORMAT_TIMESTAMP_MAX, t) +#define FORMAT_TIMESTAMP_RELATIVE(t) \ + format_timestamp_relative((char[FORMAT_TIMESTAMP_RELATIVE_MAX]){}, FORMAT_TIMESTAMP_RELATIVE_MAX, t) +#define FORMAT_TIMESPAN(t, accuracy) format_timespan((char[FORMAT_TIMESPAN_MAX]){}, FORMAT_TIMESPAN_MAX, t, accuracy) +#define FORMAT_TIMESTAMP_STYLE(t, style) \ + format_timestamp_style((char[FORMAT_TIMESTAMP_MAX]){}, FORMAT_TIMESTAMP_MAX, t, style) + int parse_timestamp(const char *t, usec_t *usec); int parse_sec(const char *t, usec_t *usec); @@ -156,9 +167,8 @@ usec_t jiffies_to_usec(uint32_t jiffies); bool in_utc_timezone(void); static inline usec_t usec_add(usec_t a, usec_t b) { - - /* Adds two time values, and makes sure USEC_INFINITY as input results as USEC_INFINITY in output, and doesn't - * overflow. */ + /* Adds two time values, and makes sure USEC_INFINITY as input results as USEC_INFINITY in output, + * and doesn't overflow. */ if (a > USEC_INFINITY - b) /* overflow check */ return USEC_INFINITY; @@ -167,7 +177,6 @@ static inline usec_t usec_add(usec_t a, usec_t b) { } static inline usec_t usec_sub_unsigned(usec_t timestamp, usec_t delta) { - if (timestamp == USEC_INFINITY) /* Make sure infinity doesn't degrade */ return USEC_INFINITY; if (timestamp < delta) @@ -184,14 +193,14 @@ static inline usec_t usec_sub_signed(usec_t timestamp, int64_t delta) { } #if SIZEOF_TIME_T == 8 -/* The last second we can format is 31. Dec 9999, 1s before midnight, because otherwise we'd enter 5 digit year - * territory. However, since we want to stay away from this in all timezones we take one day off. */ -#define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 253402214399000000) + /* The last second we can format is 31. Dec 9999, 1s before midnight, because otherwise we'd enter 5 digit + * year territory. However, since we want to stay away from this in all timezones we take one day off. */ +# define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 253402214399000000) #elif SIZEOF_TIME_T == 4 /* With a 32bit time_t we can't go beyond 2038... */ -#define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 2147483647000000) +# define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 2147483647000000) #else -#error "Yuck, time_t is neither 4 nor 8 bytes wide?" +# error "Yuck, time_t is neither 4 nor 8 bytes wide?" #endif int time_change_fd(void); diff --git a/src/cgtop/cgtop.c b/src/cgtop/cgtop.c index 9cc2f27591..50b0f63552 100644 --- a/src/cgtop/cgtop.c +++ b/src/cgtop/cgtop.c @@ -101,6 +101,10 @@ static const char *maybe_format_timespan(char *buf, size_t l, usec_t t, usec_t a return format_timespan(buf, l, t, accuracy); } +#define BUFSIZE1 CONST_MAX(FORMAT_TIMESPAN_MAX, DECIMAL_STR_MAX(usec_t)) +#define MAYBE_FORMAT_TIMESPAN(t, accuracy) \ + maybe_format_timespan((char[BUFSIZE1]){}, BUFSIZE1, t, accuracy) + static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64_t t) { if (!is_valid) return "-"; @@ -111,6 +115,10 @@ static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64 return format_bytes(buf, l, t); } +#define BUFSIZE2 CONST_MAX(FORMAT_BYTES_MAX, DECIMAL_STR_MAX(uint64_t)) +#define MAYBE_FORMAT_BYTES(is_valid, t) \ + maybe_format_bytes((char[BUFSIZE2]){}, BUFSIZE2, is_valid, t) + static bool is_root_cgroup(const char *path) { /* Returns true if the specified path belongs to the root cgroup. The root cgroup is special on cgroup v2 as it @@ -595,8 +603,7 @@ static void display(Hashmap *a) { Group *g; Group **array; signed path_columns; - unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */ - char buffer[MAX4(21U, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX, DECIMAL_STR_MAX(usec_t))]; + unsigned rows, n = 0, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */ assert(a); @@ -612,43 +619,38 @@ static void display(Hashmap *a) { typesafe_qsort(array, n, group_compare); /* Find the longest names in one run */ - for (j = 0; j < n; j++) { - unsigned cputlen, pathtlen; - - maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0); - cputlen = strlen(buffer); - maxtcpu = MAX(maxtcpu, cputlen); - - pathtlen = strlen(array[j]->path); - maxtpath = MAX(maxtpath, pathtlen); + for (unsigned j = 0; j < n; j++) { + maxtcpu = MAX(maxtcpu, + strlen(MAYBE_FORMAT_TIMESPAN((usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0))); + maxtpath = MAX(maxtpath, + strlen(array[j]->path)); } - if (arg_cpu_type == CPU_PERCENT) - xsprintf(buffer, "%6s", "%CPU"); - else - xsprintf(buffer, "%*s", maxtcpu, "CPU Time"); - rows = lines(); if (rows <= 10) rows = 10; if (on_tty()) { const char *on, *off; + unsigned cpu_len = arg_cpu_type == CPU_PERCENT ? 6 : maxtcpu; - path_columns = columns() - 36 - strlen(buffer); + path_columns = columns() - 36 - cpu_len; if (path_columns < 10) path_columns = 10; on = ansi_highlight_underline(); off = ansi_underline(); - printf("%s%s%-*s%s %s%7s%s %s%s%s %s%8s%s %s%8s%s %s%8s%s%s\n", + printf("%s%s%-*s%s %s%7s%s %s%*s%s %s%8s%s %s%8s%s %s%8s%s%s\n", ansi_underline(), arg_order == ORDER_PATH ? on : "", path_columns, "Control Group", arg_order == ORDER_PATH ? off : "", - arg_order == ORDER_TASKS ? on : "", arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+", + arg_order == ORDER_TASKS ? on : "", + arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+", arg_order == ORDER_TASKS ? off : "", - arg_order == ORDER_CPU ? on : "", buffer, + arg_order == ORDER_CPU ? on : "", + cpu_len, + arg_cpu_type == CPU_PERCENT ? "%CPU" : "CPU Time", arg_order == ORDER_CPU ? off : "", arg_order == ORDER_MEMORY ? on : "", "Memory", arg_order == ORDER_MEMORY ? off : "", @@ -660,7 +662,7 @@ static void display(Hashmap *a) { } else path_columns = maxtpath; - for (j = 0; j < n; j++) { + for (unsigned j = 0; j < n; j++) { _cleanup_free_ char *ellipsized = NULL; const char *path; @@ -684,11 +686,11 @@ static void display(Hashmap *a) { else fputs(" -", stdout); } else - printf(" %*s", maxtcpu, maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (g->cpu_usage / NSEC_PER_USEC), 0)); + printf(" %*s", maxtcpu, MAYBE_FORMAT_TIMESPAN((usec_t) (g->cpu_usage / NSEC_PER_USEC), 0)); - printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->memory_valid, g->memory)); - printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_input_bps)); - printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_output_bps)); + printf(" %8s", MAYBE_FORMAT_BYTES(g->memory_valid, g->memory)); + printf(" %8s", MAYBE_FORMAT_BYTES(g->io_valid, g->io_input_bps)); + printf(" %8s", MAYBE_FORMAT_BYTES(g->io_valid, g->io_output_bps)); putchar('\n'); } @@ -949,7 +951,6 @@ static int run(int argc, char *argv[]) { while (!quit) { usec_t t; char key; - char h[FORMAT_TIMESPAN_MAX]; t = now(CLOCK_MONOTONIC); @@ -1055,7 +1056,7 @@ static int run(int argc, char *argv[]) { case '+': arg_delay = usec_add(arg_delay, arg_delay < USEC_PER_SEC ? USEC_PER_MSEC * 250 : USEC_PER_SEC); - fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0)); + fprintf(stdout, "\nIncreased delay to %s.", FORMAT_TIMESPAN(arg_delay, 0)); fflush(stdout); sleep(1); break; @@ -1066,7 +1067,7 @@ static int run(int argc, char *argv[]) { else arg_delay = usec_sub_unsigned(arg_delay, arg_delay < USEC_PER_MSEC * 1250 ? USEC_PER_MSEC * 250 : USEC_PER_SEC); - fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0)); + fprintf(stdout, "\nDecreased delay to %s.", FORMAT_TIMESPAN(arg_delay, 0)); fflush(stdout); sleep(1); break; diff --git a/src/core/automount.c b/src/core/automount.c index edc9588165..68e794ac2e 100644 --- a/src/core/automount.c +++ b/src/core/automount.c @@ -305,7 +305,6 @@ static int automount_coldplug(Unit *u) { } static void automount_dump(Unit *u, FILE *f, const char *prefix) { - char time_string[FORMAT_TIMESPAN_MAX]; Automount *a = AUTOMOUNT(u); assert(a); @@ -320,7 +319,7 @@ static void automount_dump(Unit *u, FILE *f, const char *prefix) { prefix, automount_result_to_string(a->result), prefix, a->where, prefix, a->directory_mode, - prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, a->timeout_idle_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(a->timeout_idle_usec, USEC_PER_SEC)); } static void automount_enter_dead(Automount *a, AutomountResult f) { diff --git a/src/core/cgroup.c b/src/core/cgroup.c index 2cbb789978..e5fd6672bb 100644 --- a/src/core/cgroup.c +++ b/src/core/cgroup.c @@ -394,8 +394,6 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) { CGroupSocketBindItem *bi; IPAddressAccessItem *iaai; char **path; - char q[FORMAT_TIMESPAN_MAX]; - char v[FORMAT_TIMESPAN_MAX]; char cda[FORMAT_CGROUP_DIFF_MAX]; char cdb[FORMAT_CGROUP_DIFF_MAX]; @@ -460,8 +458,8 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) { prefix, c->startup_cpu_weight, prefix, c->cpu_shares, prefix, c->startup_cpu_shares, - prefix, format_timespan(q, sizeof(q), c->cpu_quota_per_sec_usec, 1), - prefix, format_timespan(v, sizeof(v), c->cpu_quota_period_usec, 1), + prefix, FORMAT_TIMESPAN(c->cpu_quota_per_sec_usec, 1), + prefix, FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1), prefix, strempty(cpuset_cpus), prefix, strempty(cpuset_mems), prefix, c->io_weight, @@ -514,11 +512,9 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) { "%sIODeviceLatencyTargetSec: %s %s\n", prefix, l->path, - format_timespan(q, sizeof(q), l->target_usec, 1)); - - LIST_FOREACH(device_limits, il, c->io_device_limits) { - char buf[FORMAT_BYTES_MAX]; + FORMAT_TIMESPAN(l->target_usec, 1)); + LIST_FOREACH(device_limits, il, c->io_device_limits) for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) if (il->limits[type] != cgroup_io_limit_defaults[type]) fprintf(f, @@ -526,8 +522,7 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) { prefix, cgroup_io_limit_type_to_string(type), il->path, - format_bytes(buf, sizeof(buf), il->limits[type])); - } + FORMAT_BYTES(il->limits[type])); LIST_FOREACH(device_weights, w, c->blockio_device_weights) fprintf(f, @@ -537,20 +532,18 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) { w->weight); LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) { - char buf[FORMAT_BYTES_MAX]; - if (b->rbps != CGROUP_LIMIT_MAX) fprintf(f, "%sBlockIOReadBandwidth: %s %s\n", prefix, b->path, - format_bytes(buf, sizeof(buf), b->rbps)); + FORMAT_BYTES(b->rbps)); if (b->wbps != CGROUP_LIMIT_MAX) fprintf(f, "%sBlockIOWriteBandwidth: %s %s\n", prefix, b->path, - format_bytes(buf, sizeof(buf), b->wbps)); + FORMAT_BYTES(b->wbps)); } LIST_FOREACH(items, iaai, c->ip_address_allow) { @@ -869,10 +862,9 @@ static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t qu new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC); if (new_period != period) { - char v[FORMAT_TIMESPAN_MAX]; log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING, "Clamping CPU interval for cpu.max: period is now %s", - format_timespan(v, sizeof(v), new_period, 1)); + FORMAT_TIMESPAN(new_period, 1)); u->warned_clamping_cpu_quota_period = true; } diff --git a/src/core/dbus-cgroup.c b/src/core/dbus-cgroup.c index 84c3caf3a5..77fbca8389 100644 --- a/src/core/dbus-cgroup.c +++ b/src/core/dbus-cgroup.c @@ -1114,12 +1114,10 @@ int bus_cgroup_set_property( unit_invalidate_cgroup(u, CGROUP_MASK_CPU); if (c->cpu_quota_period_usec == USEC_INFINITY) unit_write_setting(u, flags, "CPUQuotaPeriodSec", "CPUQuotaPeriodSec="); - else { - char v[FORMAT_TIMESPAN_MAX]; + else unit_write_settingf(u, flags, "CPUQuotaPeriodSec", "CPUQuotaPeriodSec=%s", - format_timespan(v, sizeof(v), c->cpu_quota_period_usec, 1)); - } + FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1)); } return 1; @@ -1374,7 +1372,6 @@ int bus_cgroup_set_property( if (!UNIT_WRITE_FLAGS_NOOP(flags)) { _cleanup_free_ char *buf = NULL; _cleanup_fclose_ FILE *f = NULL; - char ts[FORMAT_TIMESPAN_MAX]; CGroupIODeviceLatency *a; size_t size = 0; @@ -1392,7 +1389,7 @@ int bus_cgroup_set_property( fputs("IODeviceLatencyTargetSec=\n", f); LIST_FOREACH(device_latencies, a, c->io_device_latencies) fprintf(f, "IODeviceLatencyTargetSec=%s %s\n", - a->path, format_timespan(ts, sizeof(ts), a->target_usec, 1)); + a->path, FORMAT_TIMESPAN(a->target_usec, 1)); r = fflush_and_check(f); if (r < 0) diff --git a/src/core/dbus-manager.c b/src/core/dbus-manager.c index de057a0245..1f2ac8152c 100644 --- a/src/core/dbus-manager.c +++ b/src/core/dbus-manager.c @@ -1324,16 +1324,14 @@ static int verify_run_space(const char *message, sd_bus_error *error) { available = (uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize; - if (available < RELOAD_DISK_SPACE_MIN) { - char fb_available[FORMAT_BYTES_MAX], fb_need[FORMAT_BYTES_MAX]; + if (available < RELOAD_DISK_SPACE_MIN) return sd_bus_error_setf(error, BUS_ERROR_DISK_FULL, "%s, not enough space available on /run/systemd. " "Currently, %s are free, but a safety buffer of %s is enforced.", message, - format_bytes(fb_available, sizeof(fb_available), available), - format_bytes(fb_need, sizeof(fb_need), RELOAD_DISK_SPACE_MIN)); - } + FORMAT_BYTES(available), + FORMAT_BYTES(RELOAD_DISK_SPACE_MIN)); return 0; } @@ -1530,13 +1528,11 @@ static int method_switch_root(sd_bus_message *message, void *userdata, sd_bus_er available = (uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize; - if (available < RELOAD_DISK_SPACE_MIN) { - char fb_available[FORMAT_BYTES_MAX], fb_need[FORMAT_BYTES_MAX]; + if (available < RELOAD_DISK_SPACE_MIN) log_warning("Dangerously low amount of free space on /run/systemd, root switching might fail.\n" "Currently, %s are free, but %s are suggested. Proceeding anyway.", - format_bytes(fb_available, sizeof(fb_available), available), - format_bytes(fb_need, sizeof(fb_need), RELOAD_DISK_SPACE_MIN)); - } + FORMAT_BYTES(available), + FORMAT_BYTES(RELOAD_DISK_SPACE_MIN)); r = mac_selinux_access_check(message, "reboot", error); if (r < 0) diff --git a/src/core/dbus-timer.c b/src/core/dbus-timer.c index e54c473d11..9d823279dd 100644 --- a/src/core/dbus-timer.c +++ b/src/core/dbus-timer.c @@ -147,13 +147,12 @@ static int timer_add_one_monotonic_spec( sd_bus_error *error) { if (!UNIT_WRITE_FLAGS_NOOP(flags)) { - char ts[FORMAT_TIMESPAN_MAX]; TimerValue *v; unit_write_settingf(UNIT(t), flags|UNIT_ESCAPE_SPECIFIERS, name, "%s=%s", timer_base_to_string(base), - format_timespan(ts, sizeof ts, usec, USEC_PER_MSEC)); + FORMAT_TIMESPAN(usec, USEC_PER_MSEC)); v = new(TimerValue, 1); if (!v) diff --git a/src/core/dbus-util.c b/src/core/dbus-util.c index ca9b399d8c..f0e75d5bc2 100644 --- a/src/core/dbus-util.c +++ b/src/core/dbus-util.c @@ -112,16 +112,13 @@ int bus_set_transient_usec_internal( return r; if (!UNIT_WRITE_FLAGS_NOOP(flags)) { - char *n, ts[FORMAT_TIMESPAN_MAX]; - if (fix_0) *p = v != 0 ? v: USEC_INFINITY; else *p = v; - n = strndupa(name, strlen(name) - 4); - unit_write_settingf(u, flags, name, "%sSec=%s", n, - format_timespan(ts, sizeof(ts), v, USEC_PER_MSEC)); + char *n = strndupa(name, strlen(name) - 4); + unit_write_settingf(u, flags, name, "%sSec=%s", n, FORMAT_TIMESPAN(v, USEC_PER_MSEC)); } return 1; diff --git a/src/core/execute.c b/src/core/execute.c index 0535170abf..2b49e32474 100644 --- a/src/core/execute.c +++ b/src/core/execute.c @@ -5288,7 +5288,7 @@ static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv } void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) { - char **e, **d, buf_clean[FORMAT_TIMESPAN_MAX]; + char **e, **d; int r; assert(c); @@ -5406,24 +5406,16 @@ void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) { fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d); } - fprintf(f, - "%sTimeoutCleanSec: %s\n", - prefix, format_timespan(buf_clean, sizeof(buf_clean), c->timeout_clean_usec, USEC_PER_SEC)); + fprintf(f, "%sTimeoutCleanSec: %s\n", prefix, FORMAT_TIMESPAN(c->timeout_clean_usec, USEC_PER_SEC)); if (c->nice_set) - fprintf(f, - "%sNice: %i\n", - prefix, c->nice); + fprintf(f, "%sNice: %i\n", prefix, c->nice); if (c->oom_score_adjust_set) - fprintf(f, - "%sOOMScoreAdjust: %i\n", - prefix, c->oom_score_adjust); + fprintf(f, "%sOOMScoreAdjust: %i\n", prefix, c->oom_score_adjust); if (c->coredump_filter_set) - fprintf(f, - "%sCoredumpFilter: 0x%"PRIx64"\n", - prefix, c->coredump_filter); + fprintf(f, "%sCoredumpFilter: 0x%"PRIx64"\n", prefix, c->coredump_filter); for (unsigned i = 0; i < RLIM_NLIMITS; i++) if (c->rlimit[i]) { @@ -5546,13 +5538,10 @@ void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) { fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t)); } - if (c->log_ratelimit_interval_usec > 0) { - char buf_timespan[FORMAT_TIMESPAN_MAX]; - + if (c->log_ratelimit_interval_usec > 0) fprintf(f, "%sLogRateLimitIntervalSec: %s\n", - prefix, format_timespan(buf_timespan, sizeof(buf_timespan), c->log_ratelimit_interval_usec, USEC_PER_SEC)); - } + prefix, FORMAT_TIMESPAN(c->log_ratelimit_interval_usec, USEC_PER_SEC)); if (c->log_ratelimit_burst > 0) fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst); @@ -5965,8 +5954,6 @@ void exec_status_reset(ExecStatus *s) { } void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) { - char buf[FORMAT_TIMESTAMP_MAX]; - assert(s); assert(f); @@ -5982,14 +5969,14 @@ void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) { if (dual_timestamp_is_set(&s->start_timestamp)) fprintf(f, "%sStart Timestamp: %s\n", - prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime)); + prefix, FORMAT_TIMESTAMP(s->start_timestamp.realtime)); if (dual_timestamp_is_set(&s->exit_timestamp)) fprintf(f, "%sExit Timestamp: %s\n" "%sExit Code: %s\n" "%sExit Status: %i\n", - prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime), + prefix, FORMAT_TIMESTAMP(s->exit_timestamp.realtime), prefix, sigchld_code_to_string(s->code), prefix, s->status); } diff --git a/src/core/main.c b/src/core/main.c index da6c50a1c4..72d7c6b116 100644 --- a/src/core/main.c +++ b/src/core/main.c @@ -1616,12 +1616,9 @@ static void apply_clock_update(void) { if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, arg_clock_usec)) < 0) log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m"); - else { - char buf[FORMAT_TIMESTAMP_MAX]; - + else log_info("Set system clock to %s, as specified on the kernel command line.", - format_timestamp(buf, sizeof(buf), arg_clock_usec)); - } + FORMAT_TIMESTAMP(arg_clock_usec)); } static void cmdline_take_random_seed(void) { @@ -2578,7 +2575,6 @@ int main(int argc, char *argv[]) { char *switch_root_dir = NULL, *switch_root_init = NULL; usec_t before_startup, after_startup; static char systemd[] = "systemd"; - char timespan[FORMAT_TIMESPAN_MAX]; const char *shutdown_verb = NULL, *error_message = NULL; int r, retval = EXIT_FAILURE; Manager *m = NULL; @@ -2870,7 +2866,7 @@ int main(int argc, char *argv[]) { log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG, "Loaded units and determined initial transaction in %s.", - format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC)); + FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC)); if (arg_action == ACTION_TEST) { manager_test_summary(m); diff --git a/src/core/manager-dump.c b/src/core/manager-dump.c index dba32464e2..789c552723 100644 --- a/src/core/manager-dump.c +++ b/src/core/manager-dump.c @@ -38,14 +38,13 @@ void manager_dump(Manager *m, FILE *f, const char *prefix) { for (ManagerTimestamp q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) { const dual_timestamp *t = m->timestamps + q; - char buf[CONST_MAX(FORMAT_TIMESPAN_MAX, FORMAT_TIMESTAMP_MAX)]; if (dual_timestamp_is_set(t)) fprintf(f, "%sTimestamp %s: %s\n", strempty(prefix), manager_timestamp_to_string(q), - timestamp_is_set(t->realtime) ? format_timestamp(buf, sizeof buf, t->realtime) : - format_timespan(buf, sizeof buf, t->monotonic, 1)); + timestamp_is_set(t->realtime) ? FORMAT_TIMESTAMP(t->realtime) : + FORMAT_TIMESPAN(t->monotonic, 1)); } manager_dump_units(m, f, prefix); diff --git a/src/core/manager.c b/src/core/manager.c index 8884437347..18bdd83342 100644 --- a/src/core/manager.c +++ b/src/core/manager.c @@ -205,7 +205,6 @@ static void manager_print_jobs_in_progress(Manager *m) { unsigned counter = 0, print_nr; char cylon[6 + CYLON_BUFFER_EXTRA + 1]; unsigned cylon_pos; - char time[FORMAT_TIMESPAN_MAX], limit[FORMAT_TIMESPAN_MAX] = "no limit"; uint64_t x; assert(m); @@ -231,14 +230,11 @@ static void manager_print_jobs_in_progress(Manager *m) { m->jobs_in_progress_iteration++; - if (m->n_running_jobs > 1) { + if (m->n_running_jobs > 1) if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0) job_of_n = NULL; - } - format_timespan(time, sizeof(time), now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC); - if (job_get_timeout(j, &x) > 0) - format_timespan(limit, sizeof(limit), x - j->begin_usec, 1*USEC_PER_SEC); + bool have_timeout = job_get_timeout(j, &x) > 0; /* We want to use enough information for the user to identify previous lines talking about the same * unit, but keep the message as short as possible. So if 'Starting foo.service' or 'Starting @@ -252,7 +248,8 @@ static void manager_print_jobs_in_progress(Manager *m) { strempty(job_of_n), job_type_to_string(j->type), ident, - time, limit); + FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC), + have_timeout ? FORMAT_TIMESPAN(x - j->begin_usec, 1*USEC_PER_SEC) : "no limit"); } static int have_ask_password(void) { @@ -3905,14 +3902,12 @@ static void log_taint_string(Manager *m) { } static void manager_notify_finished(Manager *m) { - char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX]; usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec; if (MANAGER_IS_TEST_RUN(m)) return; if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) { - char ts[FORMAT_TIMESPAN_MAX]; char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")] = {}; char *p = buf; @@ -3928,9 +3923,9 @@ static void manager_notify_finished(Manager *m) { total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic; if (firmware_usec > 0) - size = strpcpyf(&p, size, "%s (firmware) + ", format_timespan(ts, sizeof(ts), firmware_usec, USEC_PER_MSEC)); + size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC)); if (loader_usec > 0) - size = strpcpyf(&p, size, "%s (loader) + ", format_timespan(ts, sizeof(ts), loader_usec, USEC_PER_MSEC)); + size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC)); if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) { @@ -3945,10 +3940,10 @@ static void manager_notify_finished(Manager *m) { "USERSPACE_USEC="USEC_FMT, userspace_usec, LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.", buf, - format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC), - format_timespan(initrd, sizeof(initrd), initrd_usec, USEC_PER_MSEC), - format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC), - format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC))); + FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC), + FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC), + FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC), + FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC))); } else { /* The initrd-less case on bare-metal */ @@ -3961,9 +3956,9 @@ static void manager_notify_finished(Manager *m) { "USERSPACE_USEC="USEC_FMT, userspace_usec, LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.", buf, - format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC), - format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC), - format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC))); + FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC), + FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC), + FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC))); } } else { /* The container and --user case */ @@ -3974,7 +3969,7 @@ static void manager_notify_finished(Manager *m) { "MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR, "USERSPACE_USEC="USEC_FMT, userspace_usec, LOG_MESSAGE("Startup finished in %s.", - format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC))); + FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC))); } bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec); @@ -3983,7 +3978,7 @@ static void manager_notify_finished(Manager *m) { m->ready_sent ? "STATUS=Startup finished in %s." : "READY=1\n" "STATUS=Startup finished in %s.", - format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)); + FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)); m->ready_sent = true; log_taint_string(m); diff --git a/src/core/mount.c b/src/core/mount.c index 053deac14d..fe0cb2b965 100644 --- a/src/core/mount.c +++ b/src/core/mount.c @@ -770,7 +770,6 @@ static int mount_coldplug(Unit *u) { } static void mount_dump(Unit *u, FILE *f, const char *prefix) { - char buf[FORMAT_TIMESPAN_MAX]; Mount *m = MOUNT(u); MountParameters *p; @@ -811,7 +810,7 @@ static void mount_dump(Unit *u, FILE *f, const char *prefix) { prefix, yes_no(m->lazy_unmount), prefix, yes_no(m->force_unmount), prefix, yes_no(m->read_write_only), - prefix, format_timespan(buf, sizeof(buf), m->timeout_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(m->timeout_usec, USEC_PER_SEC)); if (m->control_pid > 0) fprintf(f, diff --git a/src/core/scope.c b/src/core/scope.c index af6311bb5f..b7848a0a5d 100644 --- a/src/core/scope.c +++ b/src/core/scope.c @@ -255,7 +255,6 @@ static int scope_coldplug(Unit *u) { static void scope_dump(Unit *u, FILE *f, const char *prefix) { Scope *s = SCOPE(u); - char buf_runtime[FORMAT_TIMESPAN_MAX]; assert(s); assert(f); @@ -266,7 +265,7 @@ static void scope_dump(Unit *u, FILE *f, const char *prefix) { "%sRuntimeMaxSec: %s\n", prefix, scope_state_to_string(s->state), prefix, scope_result_to_string(s->result), - prefix, format_timespan(buf_runtime, sizeof(buf_runtime), s->runtime_max_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC)); cgroup_context_dump(UNIT(s), f, prefix); kill_context_dump(&s->kill_context, f, prefix); diff --git a/src/core/selinux-setup.c b/src/core/selinux-setup.c index 2bafbee3eb..3f873baa91 100644 --- a/src/core/selinux-setup.c +++ b/src/core/selinux-setup.c @@ -64,7 +64,6 @@ int mac_selinux_setup(bool *loaded_policy) { r = selinux_init_load_policy(&enforce); if (r == 0) { _cleanup_(mac_selinux_freep) char *label = NULL; - char timespan[FORMAT_TIMESPAN_MAX]; mac_selinux_retest(); @@ -84,7 +83,7 @@ int mac_selinux_setup(bool *loaded_policy) { after_load = now(CLOCK_MONOTONIC); log_info("Successfully loaded SELinux policy in %s.", - format_timespan(timespan, sizeof(timespan), after_load - before_load, 0)); + FORMAT_TIMESPAN(after_load - before_load, 0)); *loaded_policy = true; diff --git a/src/core/service.c b/src/core/service.c index 34aac18dd8..a015df83f4 100644 --- a/src/core/service.c +++ b/src/core/service.c @@ -768,8 +768,6 @@ static int service_load(Unit *u) { } static void service_dump(Unit *u, FILE *f, const char *prefix) { - char buf_restart[FORMAT_TIMESPAN_MAX], buf_start[FORMAT_TIMESPAN_MAX], buf_stop[FORMAT_TIMESPAN_MAX], - buf_runtime[FORMAT_TIMESPAN_MAX], buf_watchdog[FORMAT_TIMESPAN_MAX], buf_abort[FORMAT_TIMESPAN_MAX]; ServiceExecCommand c; Service *s = SERVICE(u); const char *prefix2; @@ -844,22 +842,22 @@ static void service_dump(Unit *u, FILE *f, const char *prefix) { "%sTimeoutStopSec: %s\n" "%sTimeoutStartFailureMode: %s\n" "%sTimeoutStopFailureMode: %s\n", - prefix, format_timespan(buf_restart, sizeof(buf_restart), s->restart_usec, USEC_PER_SEC), - prefix, format_timespan(buf_start, sizeof(buf_start), s->timeout_start_usec, USEC_PER_SEC), - prefix, format_timespan(buf_stop, sizeof(buf_stop), s->timeout_stop_usec, USEC_PER_SEC), + prefix, FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC), + prefix, FORMAT_TIMESPAN(s->timeout_start_usec, USEC_PER_SEC), + prefix, FORMAT_TIMESPAN(s->timeout_stop_usec, USEC_PER_SEC), prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode), prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode)); if (s->timeout_abort_set) fprintf(f, "%sTimeoutAbortSec: %s\n", - prefix, format_timespan(buf_abort, sizeof(buf_abort), s->timeout_abort_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->timeout_abort_usec, USEC_PER_SEC)); fprintf(f, "%sRuntimeMaxSec: %s\n" "%sWatchdogSec: %s\n", - prefix, format_timespan(buf_runtime, sizeof(buf_runtime), s->runtime_max_usec, USEC_PER_SEC), - prefix, format_timespan(buf_watchdog, sizeof(buf_watchdog), s->watchdog_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC), + prefix, FORMAT_TIMESPAN(s->watchdog_usec, USEC_PER_SEC)); kill_context_dump(&s->kill_context, f, prefix); exec_context_dump(&s->exec_context, f, prefix); @@ -3893,12 +3891,11 @@ static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *us break; case SERVICE_AUTO_RESTART: - if (s->restart_usec > 0) { - char buf_restart[FORMAT_TIMESPAN_MAX]; + if (s->restart_usec > 0) log_unit_debug(UNIT(s), "Service RestartSec=%s expired, scheduling restart.", - format_timespan(buf_restart, sizeof buf_restart, s->restart_usec, USEC_PER_SEC)); - } else + FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC)); + else log_unit_debug(UNIT(s), "Service has no hold-off time (RestartSec=0), scheduling restart."); @@ -3923,7 +3920,6 @@ static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *us static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) { Service *s = SERVICE(userdata); - char t[FORMAT_TIMESPAN_MAX]; usec_t watchdog_usec; assert(s); @@ -3933,12 +3929,12 @@ static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void if (UNIT(s)->manager->service_watchdogs) { log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!", - format_timespan(t, sizeof(t), watchdog_usec, 1)); + FORMAT_TIMESPAN(watchdog_usec, 1)); service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG); } else log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!", - format_timespan(t, sizeof(t), watchdog_usec, 1)); + FORMAT_TIMESPAN(watchdog_usec, 1)); return 0; } diff --git a/src/core/socket.c b/src/core/socket.c index 8144780bf8..0ae53e7336 100644 --- a/src/core/socket.c +++ b/src/core/socket.c @@ -563,8 +563,6 @@ _const_ static const char* listen_lookup(int family, int type) { } static void socket_dump(Unit *u, FILE *f, const char *prefix) { - char time_string[FORMAT_TIMESPAN_MAX]; - SocketExecCommand c; Socket *s = SOCKET(u); SocketPort *p; const char *prefix2, *str; @@ -723,12 +721,12 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) { if (s->keep_alive_time > 0) fprintf(f, "%sKeepAliveTimeSec: %s\n", - prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_time, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->keep_alive_time, USEC_PER_SEC)); if (s->keep_alive_interval > 0) fprintf(f, "%sKeepAliveIntervalSec: %s\n", - prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_interval, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->keep_alive_interval, USEC_PER_SEC)); if (s->keep_alive_cnt > 0) fprintf(f, @@ -738,7 +736,7 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) { if (s->defer_accept > 0) fprintf(f, "%sDeferAcceptSec: %s\n", - prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->defer_accept, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->defer_accept, USEC_PER_SEC)); LIST_FOREACH(port, p, s->ports) { @@ -774,7 +772,7 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) { fprintf(f, "%sTriggerLimitIntervalSec: %s\n" "%sTriggerLimitBurst: %u\n", - prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->trigger_limit.interval, USEC_PER_SEC), + prefix, FORMAT_TIMESPAN(s->trigger_limit.interval, USEC_PER_SEC), prefix, s->trigger_limit.burst); str = ip_protocol_to_name(s->socket_protocol); @@ -793,12 +791,12 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) { fprintf(f, "%sTimeoutSec: %s\n", - prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->timeout_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC)); exec_context_dump(&s->exec_context, f, prefix); kill_context_dump(&s->kill_context, f, prefix); - for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) { + for (SocketExecCommand c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) { if (!s->exec_command[c]) continue; @@ -3260,11 +3258,9 @@ int socket_collect_fds(Socket *s, int **fds) { return -ENOMEM; LIST_FOREACH(port, p, s->ports) { - size_t i; - if (p->fd >= 0) rfds[k++] = p->fd; - for (i = 0; i < p->n_auxiliary_fds; ++i) + for (size_t i = 0; i < p->n_auxiliary_fds; ++i) rfds[k++] = p->auxiliary_fds[i]; } diff --git a/src/core/swap.c b/src/core/swap.c index fabee3c1f3..81fb3bb2de 100644 --- a/src/core/swap.c +++ b/src/core/swap.c @@ -609,7 +609,6 @@ static int swap_coldplug(Unit *u) { } static void swap_dump(Unit *u, FILE *f, const char *prefix) { - char buf[FORMAT_TIMESPAN_MAX]; Swap *s = SWAP(u); SwapParameters *p; @@ -651,7 +650,7 @@ static void swap_dump(Unit *u, FILE *f, const char *prefix) { fprintf(f, "%sTimeoutSec: %s\n", - prefix, format_timespan(buf, sizeof(buf), s->timeout_usec, USEC_PER_SEC)); + prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC)); if (s->control_pid > 0) fprintf(f, diff --git a/src/core/timer.c b/src/core/timer.c index e064ad9a2d..3b03f4672e 100644 --- a/src/core/timer.c +++ b/src/core/timer.c @@ -234,7 +234,6 @@ static int timer_load(Unit *u) { } static void timer_dump(Unit *u, FILE *f, const char *prefix) { - char buf[FORMAT_TIMESPAN_MAX]; Timer *t = TIMER(u); Unit *trigger; TimerValue *v; @@ -257,7 +256,7 @@ static void timer_dump(Unit *u, FILE *f, const char *prefix) { prefix, trigger ? trigger->id : "n/a", prefix, yes_no(t->persistent), prefix, yes_no(t->wake_system), - prefix, format_timespan(buf, sizeof(buf), t->accuracy_usec, 1), + prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1), prefix, yes_no(t->remain_after_elapse), prefix, yes_no(t->fixed_random_delay), prefix, yes_no(t->on_clock_change), @@ -274,15 +273,12 @@ static void timer_dump(Unit *u, FILE *f, const char *prefix) { prefix, timer_base_to_string(v->base), strna(p)); - } else { - char timespan1[FORMAT_TIMESPAN_MAX]; - + } else fprintf(f, "%s%s: %s\n", prefix, timer_base_to_string(v->base), - format_timespan(timespan1, sizeof(timespan1), v->value, 0)); - } + FORMAT_TIMESPAN(v->value, 0)); } static void timer_set_state(Timer *t, TimerState state) { @@ -355,7 +351,6 @@ static void timer_enter_elapsed(Timer *t, bool leave_around) { } static void add_random(Timer *t, usec_t *v) { - char s[FORMAT_TIMESPAN_MAX]; usec_t add; assert(t); @@ -373,7 +368,7 @@ static void add_random(Timer *t, usec_t *v) { else *v += add; - log_unit_debug(UNIT(t), "Adding %s random time.", format_timespan(s, sizeof(s), add, 0)); + log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0)); } static void timer_enter_waiting(Timer *t, bool time_change) { @@ -508,13 +503,12 @@ static void timer_enter_waiting(Timer *t, bool time_change) { } if (found_monotonic) { - char buf[FORMAT_TIMESPAN_MAX]; usec_t left; add_random(t, &t->next_elapse_monotonic_or_boottime); left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t))); - log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", format_timespan(buf, sizeof(buf), left, 0)); + log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0)); if (t->monotonic_event_source) { r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime); @@ -546,11 +540,9 @@ static void timer_enter_waiting(Timer *t, bool time_change) { } if (found_realtime) { - char buf[FORMAT_TIMESTAMP_MAX]; - add_random(t, &t->next_elapse_realtime); - log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", format_timestamp(buf, sizeof(buf), t->next_elapse_realtime)); + log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime)); if (t->realtime_event_source) { r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime); @@ -664,12 +656,9 @@ static int timer_start(Unit *u) { ft = timespec_load(&st.st_mtim); if (ft < now(CLOCK_REALTIME)) t->last_trigger.realtime = ft; - else { - char z[FORMAT_TIMESTAMP_MAX]; - + else log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.", - format_timestamp(z, sizeof(z), ft)); - } + FORMAT_TIMESTAMP(ft)); } else if (errno == ENOENT) /* The timer has never run before, make sure a stamp file exists. */ diff --git a/src/core/unit-serialize.c b/src/core/unit-serialize.c index 689a536549..ab0f03a0ca 100644 --- a/src/core/unit-serialize.c +++ b/src/core/unit-serialize.c @@ -602,7 +602,6 @@ static void print_unit_dependency_mask(FILE *f, const char *kind, UnitDependency void unit_dump(Unit *u, FILE *f, const char *prefix) { char *t, **j; const char *prefix2; - char timestamp[5][FORMAT_TIMESTAMP_MAX], timespan[FORMAT_TIMESPAN_MAX]; Unit *following; _cleanup_set_free_ Set *following_set = NULL; CGroupMask m; @@ -640,11 +639,11 @@ void unit_dump(Unit *u, FILE *f, const char *prefix) { prefix, strna(u->instance), prefix, unit_load_state_to_string(u->load_state), prefix, unit_active_state_to_string(unit_active_state(u)), - prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->state_change_timestamp.realtime)), - prefix, strna(format_timestamp(timestamp[1], sizeof(timestamp[1]), u->inactive_exit_timestamp.realtime)), - prefix, strna(format_timestamp(timestamp[2], sizeof(timestamp[2]), u->active_enter_timestamp.realtime)), - prefix, strna(format_timestamp(timestamp[3], sizeof(timestamp[3]), u->active_exit_timestamp.realtime)), - prefix, strna(format_timestamp(timestamp[4], sizeof(timestamp[4]), u->inactive_enter_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->state_change_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->inactive_exit_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->active_enter_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->active_exit_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->inactive_enter_timestamp.realtime)), prefix, yes_no(unit_may_gc(u)), prefix, yes_no(unit_need_daemon_reload(u)), prefix, yes_no(u->transient), @@ -741,7 +740,7 @@ void unit_dump(Unit *u, FILE *f, const char *prefix) { fprintf(f, "%s\tSuccess Action Exit Status: %i\n", prefix, u->success_action_exit_status); if (u->job_timeout != USEC_INFINITY) - fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0)); + fprintf(f, "%s\tJob Timeout: %s\n", prefix, FORMAT_TIMESPAN(u->job_timeout, 0)); if (u->job_timeout_action != EMERGENCY_ACTION_NONE) fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, emergency_action_to_string(u->job_timeout_action)); @@ -756,14 +755,14 @@ void unit_dump(Unit *u, FILE *f, const char *prefix) { fprintf(f, "%s\tCondition Timestamp: %s\n" "%s\tCondition Result: %s\n", - prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->condition_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->condition_timestamp.realtime)), prefix, yes_no(u->condition_result)); if (dual_timestamp_is_set(&u->assert_timestamp)) fprintf(f, "%s\tAssert Timestamp: %s\n" "%s\tAssert Result: %s\n", - prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->assert_timestamp.realtime)), + prefix, strna(FORMAT_TIMESTAMP(u->assert_timestamp.realtime)), prefix, yes_no(u->assert_result)); for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) { diff --git a/src/core/unit.c b/src/core/unit.c index 30afd5a776..c32317c863 100644 --- a/src/core/unit.c +++ b/src/core/unit.c @@ -2273,8 +2273,6 @@ static int unit_log_resources(Unit *u) { (void) unit_get_cpu_usage(u, &nsec); if (nsec != NSEC_INFINITY) { - char buf[FORMAT_TIMESPAN_MAX] = ""; - /* Format the CPU time for inclusion in the structured log message */ if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) { r = log_oom(); @@ -2283,8 +2281,7 @@ static int unit_log_resources(Unit *u) { iovec[n_iovec++] = IOVEC_MAKE_STRING(t); /* Format the CPU time for inclusion in the human language message string */ - format_timespan(buf, sizeof(buf), nsec / NSEC_PER_USEC, USEC_PER_MSEC); - t = strjoin("consumed ", buf, " CPU time"); + t = strjoin("consumed ", FORMAT_TIMESPAN(nsec / NSEC_PER_USEC, USEC_PER_MSEC), " CPU time"); if (!t) { r = log_oom(); goto finish; @@ -2298,7 +2295,6 @@ static int unit_log_resources(Unit *u) { } for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) { - char buf[FORMAT_BYTES_MAX] = ""; uint64_t value = UINT64_MAX; assert(io_fields[k]); @@ -2322,14 +2318,14 @@ static int unit_log_resources(Unit *u) { * for the bytes counters (and not for the operations counters) */ if (k == CGROUP_IO_READ_BYTES) { assert(!rr); - rr = strjoin("read ", format_bytes(buf, sizeof(buf), value), " from disk"); + rr = strjoin("read ", strna(FORMAT_BYTES(value)), " from disk"); if (!rr) { r = log_oom(); goto finish; } } else if (k == CGROUP_IO_WRITE_BYTES) { assert(!wr); - wr = strjoin("written ", format_bytes(buf, sizeof(buf), value), " to disk"); + wr = strjoin("written ", strna(FORMAT_BYTES(value)), " to disk"); if (!wr) { r = log_oom(); goto finish; @@ -2363,7 +2359,6 @@ static int unit_log_resources(Unit *u) { } for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) { - char buf[FORMAT_BYTES_MAX] = ""; uint64_t value = UINT64_MAX; assert(ip_fields[m]); @@ -2387,14 +2382,14 @@ static int unit_log_resources(Unit *u) { * bytes counters (and not for the packets counters) */ if (m == CGROUP_IP_INGRESS_BYTES) { assert(!igress); - igress = strjoin("received ", format_bytes(buf, sizeof(buf), value), " IP traffic"); + igress = strjoin("received ", strna(FORMAT_BYTES(value)), " IP traffic"); if (!igress) { r = log_oom(); goto finish; } } else if (m == CGROUP_IP_EGRESS_BYTES) { assert(!egress); - egress = strjoin("sent ", format_bytes(buf, sizeof(buf), value), " IP traffic"); + egress = strjoin("sent ", strna(FORMAT_BYTES(value)), " IP traffic"); if (!egress) { r = log_oom(); goto finish; diff --git a/src/coredump/coredumpctl.c b/src/coredump/coredumpctl.c index def3650bb4..8261bff213 100644 --- a/src/coredump/coredumpctl.c +++ b/src/coredump/coredumpctl.c @@ -645,15 +645,11 @@ static int print_info(FILE *file, sd_journal *j, bool need_space) { usec_t u; r = safe_atou64(timestamp, &u); - if (r >= 0) { - char absolute[FORMAT_TIMESTAMP_MAX], relative[FORMAT_TIMESPAN_MAX]; + if (r >= 0) + fprintf(file, " Timestamp: %s (%s)\n", + FORMAT_TIMESTAMP(u), FORMAT_TIMESTAMP_RELATIVE(u)); - fprintf(file, - " Timestamp: %s (%s)\n", - format_timestamp(absolute, sizeof(absolute), u), - format_timestamp_relative(relative, sizeof(relative), u)); - - } else + else fprintf(file, " Timestamp: %s\n", timestamp); } @@ -697,7 +693,6 @@ static int print_info(FILE *file, sd_journal *j, bool need_space) { if (filename) { const char *state = NULL, *color = NULL; uint64_t size = UINT64_MAX; - char buf[FORMAT_BYTES_MAX]; analyze_coredump_file(filename, &state, &color, &size); @@ -712,9 +707,8 @@ static int print_info(FILE *file, sd_journal *j, bool need_space) { ansi_normal()); if (size != UINT64_MAX) - fprintf(file, - " Disk Size: %s\n", - format_bytes(buf, sizeof(buf), size)); + fprintf(file, " Disk Size: %s\n", FORMAT_BYTES(size)); + } else if (coredump) fprintf(file, " Storage: journal\n"); else diff --git a/src/dissect/dissect.c b/src/dissect/dissect.c index 47feba3d62..88bb3de40f 100644 --- a/src/dissect/dissect.c +++ b/src/dissect/dissect.c @@ -385,10 +385,8 @@ static int action_dissect(DissectedImage *m, LoopDevice *d) { if (ioctl(d->fd, BLKGETSIZE64, &size) < 0) log_debug_errno(errno, "Failed to query size of loopback device: %m"); - else if (arg_json_format_flags & JSON_FORMAT_OFF) { - char s[FORMAT_BYTES_MAX]; - printf(" Size: %s\n", format_bytes(s, sizeof(s), size)); - } + else if (arg_json_format_flags & JSON_FORMAT_OFF) + printf(" Size: %s\n", FORMAT_BYTES(size)); if (arg_json_format_flags & JSON_FORMAT_OFF) putc('\n', stdout); diff --git a/src/fstab-generator/fstab-generator.c b/src/fstab-generator/fstab-generator.c index a4e3ea5311..bafc7b8f96 100644 --- a/src/fstab-generator/fstab-generator.c +++ b/src/fstab-generator/fstab-generator.c @@ -196,7 +196,6 @@ static int write_timeout( const char *variable) { _cleanup_free_ char *timeout = NULL; - char timespan[FORMAT_TIMESPAN_MAX]; usec_t u; int r; @@ -212,7 +211,7 @@ static int write_timeout( return 0; } - fprintf(f, "%s=%s\n", variable, format_timespan(timespan, sizeof(timespan), u, 0)); + fprintf(f, "%s=%s\n", variable, FORMAT_TIMESPAN(u, 0)); return 0; } diff --git a/src/home/homed-home.c b/src/home/homed-home.c index 104427dabe..ef11c72b74 100644 --- a/src/home/homed-home.c +++ b/src/home/homed-home.c @@ -1097,15 +1097,15 @@ static int home_ratelimit(Home *h, sd_bus_error *error) { } if (ret == 0) { - char buf[FORMAT_TIMESPAN_MAX]; usec_t t, n; n = now(CLOCK_REALTIME); t = user_record_ratelimit_next_try(h->record); if (t != USEC_INFINITY && t > n) - return sd_bus_error_setf(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again in %s!", - format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC)); + return sd_bus_error_setf(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, + "Too many login attempts, please try again in %s!", + FORMAT_TIMESPAN(t - n, USEC_PER_SEC)); return sd_bus_error_set(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again later."); } diff --git a/src/home/homework-luks.c b/src/home/homework-luks.c index 6448883fe0..3d4361c4ec 100644 --- a/src/home/homework-luks.c +++ b/src/home/homework-luks.c @@ -949,7 +949,6 @@ int home_store_header_identity_luks( } int run_fitrim(int root_fd) { - char buf[FORMAT_BYTES_MAX]; struct fstrim_range range = { .len = UINT64_MAX, }; @@ -968,8 +967,7 @@ int run_fitrim(int root_fd) { return log_warning_errno(errno, "Failed to invoke FITRIM, ignoring: %m"); } - log_info("Discarded unused %s.", - format_bytes(buf, sizeof(buf), range.len)); + log_info("Discarded unused %s.", FORMAT_BYTES(range.len)); return 1; } @@ -984,7 +982,6 @@ int run_fitrim_by_path(const char *root_path) { } int run_fallocate(int backing_fd, const struct stat *st) { - char buf[FORMAT_BYTES_MAX]; struct stat stbuf; assert(backing_fd >= 0); @@ -1023,7 +1020,7 @@ int run_fallocate(int backing_fd, const struct stat *st) { } log_info("Allocated additional %s.", - format_bytes(buf, sizeof(buf), (DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512)); + FORMAT_BYTES((DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512)); return 1; } @@ -1278,15 +1275,13 @@ fail: } static void print_size_summary(uint64_t host_size, uint64_t encrypted_size, struct statfs *sfs) { - char buffer1[FORMAT_BYTES_MAX], buffer2[FORMAT_BYTES_MAX], buffer3[FORMAT_BYTES_MAX], buffer4[FORMAT_BYTES_MAX]; - assert(sfs); log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.", - format_bytes(buffer1, sizeof(buffer1), host_size), - format_bytes(buffer2, sizeof(buffer2), encrypted_size), - format_bytes(buffer3, sizeof(buffer3), (uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize), - format_bytes(buffer4, sizeof(buffer4), (uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize)); + FORMAT_BYTES(host_size), + FORMAT_BYTES(encrypted_size), + FORMAT_BYTES((uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize), + FORMAT_BYTES((uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize)); } int home_activate_luks( @@ -1793,7 +1788,6 @@ static int wait_for_devlink(const char *path) { } static int calculate_disk_size(UserRecord *h, const char *parent_dir, uint64_t *ret) { - char buf[FORMAT_BYTES_MAX]; struct statfs sfs; uint64_t m; @@ -1820,14 +1814,14 @@ static int calculate_disk_size(UserRecord *h, const char *parent_dir, uint64_t * log_info("Sizing home to %u%% of available disk space, which is %s.", USER_DISK_SIZE_DEFAULT_PERCENT, - format_bytes(buf, sizeof(buf), *ret)); + FORMAT_BYTES(*ret)); } else { *ret = DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m * (double) h->disk_size_relative / (double) UINT32_MAX)); log_info("Sizing home to %" PRIu64 ".%01" PRIu64 "%% of available disk space, which is %s.", (h->disk_size_relative * 100) / UINT32_MAX, ((h->disk_size_relative * 1000) / UINT32_MAX) % 10, - format_bytes(buf, sizeof(buf), *ret)); + FORMAT_BYTES(*ret)); } if (*ret < USER_DISK_SIZE_MIN) @@ -2631,8 +2625,6 @@ int home_resize_luks( HomeSetup *setup, UserRecord **ret_home) { - char buffer1[FORMAT_BYTES_MAX], buffer2[FORMAT_BYTES_MAX], buffer3[FORMAT_BYTES_MAX], - buffer4[FORMAT_BYTES_MAX], buffer5[FORMAT_BYTES_MAX], buffer6[FORMAT_BYTES_MAX]; uint64_t old_image_size, new_image_size, old_fs_size, new_fs_size, crypto_offset, new_partition_size; _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL; _cleanup_(fdisk_unref_tablep) struct fdisk_table *table = NULL; @@ -2770,12 +2762,12 @@ int home_resize_luks( return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY), "File systems of this type can only be resized offline, but is currently online."); log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.", - format_bytes(buffer1, sizeof(buffer1), old_image_size), - format_bytes(buffer2, sizeof(buffer2), new_image_size), - format_bytes(buffer3, sizeof(buffer3), setup->partition_size), - format_bytes(buffer4, sizeof(buffer4), new_partition_size), - format_bytes(buffer5, sizeof(buffer5), old_fs_size), - format_bytes(buffer6, sizeof(buffer6), new_fs_size)); + FORMAT_BYTES(old_image_size), + FORMAT_BYTES(new_image_size), + FORMAT_BYTES(setup->partition_size), + FORMAT_BYTES(new_partition_size), + FORMAT_BYTES(old_fs_size), + FORMAT_BYTES(new_fs_size)); r = prepare_resize_partition( image_fd, diff --git a/src/home/pam_systemd_home.c b/src/home/pam_systemd_home.c index b7db39dab9..836ed0d5e9 100644 --- a/src/home/pam_systemd_home.c +++ b/src/home/pam_systemd_home.c @@ -892,9 +892,8 @@ _public_ PAM_EXTERN int pam_sm_acct_mgmt( usec_t n = now(CLOCK_REALTIME); if (t > n) { - char buf[FORMAT_TIMESPAN_MAX]; (void) pam_prompt(handle, PAM_ERROR_MSG, NULL, "Too many logins, try again in %s.", - format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC)); + FORMAT_TIMESPAN(t - n, USEC_PER_SEC)); return PAM_MAXTRIES; } diff --git a/src/import/import-fs.c b/src/import/import-fs.c index a12ee77ef9..e8c3740879 100644 --- a/src/import/import-fs.c +++ b/src/import/import-fs.c @@ -62,11 +62,8 @@ static void progress_show(ProgressInfo *p) { if (p->size == 0) log_info("Copying tree, currently at '%s'...", p->path); - else { - char buffer[FORMAT_BYTES_MAX]; - - log_info("Copying tree, currently at '%s' (@%s)...", p->path, format_bytes(buffer, sizeof(buffer), p->size)); - } + else + log_info("Copying tree, currently at '%s' (@%s)...", p->path, FORMAT_BYTES(p->size)); } static int progress_path(const char *path, const struct stat *st, void *userdata) { diff --git a/src/import/pull-job.c b/src/import/pull-job.c index 9ab3776e50..038fa2be8b 100644 --- a/src/import/pull-job.c +++ b/src/import/pull-job.c @@ -501,15 +501,12 @@ static size_t pull_job_header_callback(void *contents, size_t size, size_t nmemb (void) safe_atou64(length, &j->content_length); if (j->content_length != UINT64_MAX) { - char bytes[FORMAT_BYTES_MAX]; - if (j->content_length > j->compressed_max) { - log_error("Content too large."); - r = -EFBIG; + r = log_error_errno(SYNTHETIC_ERRNO(EFBIG), "Content too large."); goto fail; } - log_info("Downloading %s for %s.", format_bytes(bytes, sizeof(bytes), j->content_length), j->url); + log_info("Downloading %s for %s.", FORMAT_BYTES(j->content_length), j->url); } return sz; @@ -554,10 +551,8 @@ static int pull_job_progress_callback(void *userdata, curl_off_t dltotal, curl_o if (n > j->last_status_usec + USEC_PER_SEC && percent != j->progress_percent && dlnow < dltotal) { - char buf[FORMAT_TIMESPAN_MAX]; if (n - j->start_usec > USEC_PER_SEC && dlnow > 0) { - char y[FORMAT_BYTES_MAX]; usec_t left, done; done = n - j->start_usec; @@ -566,8 +561,8 @@ static int pull_job_progress_callback(void *userdata, curl_off_t dltotal, curl_o log_info("Got %u%% of %s. %s left at %s/s.", percent, j->url, - format_timespan(buf, sizeof(buf), left, USEC_PER_SEC), - format_bytes(y, sizeof(y), (uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC)))); + FORMAT_TIMESPAN(left, USEC_PER_SEC), + FORMAT_BYTES((uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC)))); } else log_info("Got %u%% of %s.", percent, j->url); diff --git a/src/journal/journalctl.c b/src/journal/journalctl.c index 17fc493b22..fe98aecf51 100644 --- a/src/journal/journalctl.c +++ b/src/journal/journalctl.c @@ -1942,7 +1942,6 @@ static int setup_keys(void) { if (hn) hostname_cleanup(hn); - char tsb[FORMAT_TIMESPAN_MAX]; fprintf(stderr, "\nNew keys have been generated for host %s%s" SD_ID128_FORMAT_STR ".\n" "\n" @@ -1961,7 +1960,7 @@ static int setup_keys(void) { SD_ID128_FORMAT_VAL(machine), ansi_highlight(), ansi_normal(), p, - format_timespan(tsb, sizeof(tsb), arg_interval, 0), + FORMAT_TIMESPAN(arg_interval, 0), ansi_highlight(), ansi_normal(), ansi_highlight_red()); fflush(stderr); @@ -2014,7 +2013,7 @@ static int verify(sd_journal *j) { else if (k < 0) r = log_warning_errno(k, "FAIL: %s (%m)", f->path); else { - char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX], c[FORMAT_TIMESPAN_MAX]; + char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX]; log_info("PASS: %s", f->path); if (arg_verify_key && JOURNAL_HEADER_SEALED(f->header)) { @@ -2022,10 +2021,10 @@ static int verify(sd_journal *j) { log_info("=> Validated from %s to %s, final %s entries not sealed.", format_timestamp_maybe_utc(a, sizeof(a), first), format_timestamp_maybe_utc(b, sizeof(b), validated), - format_timespan(c, sizeof(c), last > validated ? last - validated : 0, 0)); + FORMAT_TIMESPAN(last > validated ? last - validated : 0, 0)); } else if (last > 0) log_info("=> No sealing yet, %s of entries not sealed.", - format_timespan(c, sizeof(c), last - first, 0)); + FORMAT_TIMESPAN(last - first, 0)); else log_info("=> No sealing yet, no entries in file."); } @@ -2328,14 +2327,13 @@ int main(int argc, char *argv[]) { case ACTION_DISK_USAGE: { uint64_t bytes = 0; - char sbytes[FORMAT_BYTES_MAX]; r = sd_journal_get_usage(j, &bytes); if (r < 0) goto finish; printf("Archived and active journals take up %s in the file system.\n", - format_bytes(sbytes, sizeof(sbytes), bytes)); + FORMAT_BYTES(bytes)); goto finish; } diff --git a/src/journal/journald-server.c b/src/journal/journald-server.c index 30f04f5383..7770df41f1 100644 --- a/src/journal/journald-server.c +++ b/src/journal/journald-server.c @@ -199,10 +199,6 @@ static int determine_space(Server *s, uint64_t *available, uint64_t *limit) { } void server_space_usage_message(Server *s, JournalStorage *storage) { - char fb1[FORMAT_BYTES_MAX], fb2[FORMAT_BYTES_MAX], fb3[FORMAT_BYTES_MAX], - fb4[FORMAT_BYTES_MAX], fb5[FORMAT_BYTES_MAX], fb6[FORMAT_BYTES_MAX]; - JournalMetrics *metrics; - assert(s); if (!storage) @@ -211,32 +207,31 @@ void server_space_usage_message(Server *s, JournalStorage *storage) { if (cache_space_refresh(s, storage) < 0) return; - metrics = &storage->metrics; - format_bytes(fb1, sizeof(fb1), storage->space.vfs_used); - format_bytes(fb2, sizeof(fb2), metrics->max_use); - format_bytes(fb3, sizeof(fb3), metrics->keep_free); - format_bytes(fb4, sizeof(fb4), storage->space.vfs_available); - format_bytes(fb5, sizeof(fb5), storage->space.limit); - format_bytes(fb6, sizeof(fb6), storage->space.available); + const JournalMetrics *metrics = &storage->metrics; + + const char + *vfs_used = FORMAT_BYTES(storage->space.vfs_used), + *limit = FORMAT_BYTES(storage->space.limit), + *available = FORMAT_BYTES(storage->space.available); server_driver_message(s, 0, "MESSAGE_ID=" SD_MESSAGE_JOURNAL_USAGE_STR, LOG_MESSAGE("%s (%s) is %s, max %s, %s free.", - storage->name, storage->path, fb1, fb5, fb6), + storage->name, storage->path, vfs_used, limit, available), "JOURNAL_NAME=%s", storage->name, "JOURNAL_PATH=%s", storage->path, "CURRENT_USE=%"PRIu64, storage->space.vfs_used, - "CURRENT_USE_PRETTY=%s", fb1, + "CURRENT_USE_PRETTY=%s", vfs_used, "MAX_USE=%"PRIu64, metrics->max_use, - "MAX_USE_PRETTY=%s", fb2, + "MAX_USE_PRETTY=%s", FORMAT_BYTES(metrics->max_use), "DISK_KEEP_FREE=%"PRIu64, metrics->keep_free, - "DISK_KEEP_FREE_PRETTY=%s", fb3, + "DISK_KEEP_FREE_PRETTY=%s", FORMAT_BYTES(metrics->keep_free), "DISK_AVAILABLE=%"PRIu64, storage->space.vfs_available, - "DISK_AVAILABLE_PRETTY=%s", fb4, + "DISK_AVAILABLE_PRETTY=%s", FORMAT_BYTES(storage->space.vfs_available), "LIMIT=%"PRIu64, storage->space.limit, - "LIMIT_PRETTY=%s", fb5, + "LIMIT_PRETTY=%s", limit, "AVAILABLE=%"PRIu64, storage->space.available, - "AVAILABLE_PRETTY=%s", fb6, + "AVAILABLE_PRETTY=%s", available, NULL); } @@ -1113,7 +1108,6 @@ void server_dispatch_message( } int server_flush_to_var(Server *s, bool require_flag_file) { - char ts[FORMAT_TIMESPAN_MAX]; sd_journal *j = NULL; const char *fn; unsigned n = 0; @@ -1206,7 +1200,7 @@ finish: server_driver_message(s, 0, NULL, LOG_MESSAGE("Time spent on flushing to %s is %s for %u entries.", s->system_storage.path, - format_timespan(ts, sizeof(ts), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0), + FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0), n), NULL); diff --git a/src/libsystemd-network/sd-dhcp-client.c b/src/libsystemd-network/sd-dhcp-client.c index 3c8c440771..7fe660466f 100644 --- a/src/libsystemd-network/sd-dhcp-client.c +++ b/src/libsystemd-network/sd-dhcp-client.c @@ -1686,7 +1686,6 @@ static int client_handle_ack(sd_dhcp_client *client, DHCPMessage *ack, size_t le static int client_set_lease_timeouts(sd_dhcp_client *client) { usec_t time_now; - char time_string[FORMAT_TIMESPAN_MAX]; int r; assert(client); @@ -1748,7 +1747,7 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) { return 0; log_dhcp_client(client, "lease expires in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->expire_time - time_now, USEC_PER_SEC)); + FORMAT_TIMESPAN(client->expire_time - time_now, USEC_PER_SEC)); /* arm T2 timeout */ r = event_reset_time(client->event, &client->timeout_t2, @@ -1764,7 +1763,7 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) { return 0; log_dhcp_client(client, "T2 expires in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->t2_time - time_now, USEC_PER_SEC)); + FORMAT_TIMESPAN(client->t2_time - time_now, USEC_PER_SEC)); /* arm T1 timeout */ r = event_reset_time(client->event, &client->timeout_t1, @@ -1777,14 +1776,13 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) { if (client->t1_time > time_now) log_dhcp_client(client, "T1 expires in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->t1_time - time_now, USEC_PER_SEC)); + FORMAT_TIMESPAN(client->t1_time - time_now, USEC_PER_SEC)); return 0; } static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, int len) { DHCP_CLIENT_DONT_DESTROY(client); - char time_string[FORMAT_TIMESPAN_MAX]; int r, notify_event; assert(client); @@ -1830,8 +1828,7 @@ static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, i if (r < 0) goto error; - log_dhcp_client(client, "REBOOT in %s", format_timespan(time_string, FORMAT_TIMESPAN_MAX, - client->start_delay, USEC_PER_SEC)); + log_dhcp_client(client, "REBOOT in %s", FORMAT_TIMESPAN(client->start_delay, USEC_PER_SEC)); client->start_delay = CLAMP(client->start_delay * 2, RESTART_AFTER_NAK_MIN_USEC, RESTART_AFTER_NAK_MAX_USEC); diff --git a/src/libsystemd-network/sd-dhcp6-client.c b/src/libsystemd-network/sd-dhcp6-client.c index e8c47f429a..079f154acd 100644 --- a/src/libsystemd-network/sd-dhcp6-client.c +++ b/src/libsystemd-network/sd-dhcp6-client.c @@ -946,7 +946,6 @@ static int client_timeout_resend(sd_event_source *s, uint64_t usec, void *userda usec_t time_now, init_retransmit_time = 0, max_retransmit_time = 0; usec_t max_retransmit_duration = 0; uint8_t max_retransmit_count = 0; - char time_string[FORMAT_TIMESPAN_MAX]; assert(s); assert(client); @@ -1042,7 +1041,7 @@ static int client_timeout_resend(sd_event_source *s, uint64_t usec, void *userda } log_dhcp6_client(client, "Next retransmission in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->retransmit_time, USEC_PER_SEC)); + FORMAT_TIMESPAN(client->retransmit_time, USEC_PER_SEC)); r = event_reset_time(client->event, &client->timeout_resend, clock_boottime_or_monotonic(), @@ -1566,7 +1565,6 @@ static int client_get_lifetime(sd_dhcp6_client *client, uint32_t *lifetime_t1, static int client_start(sd_dhcp6_client *client, enum DHCP6State state) { int r; usec_t timeout, time_now; - char time_string[FORMAT_TIMESPAN_MAX]; uint32_t lifetime_t1, lifetime_t2; assert_return(client, -EINVAL); @@ -1639,8 +1637,7 @@ static int client_start(sd_dhcp6_client *client, enum DHCP6State state) { timeout = client_timeout_compute_random(lifetime_t1 * USEC_PER_SEC); - log_dhcp6_client(client, "T1 expires in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, timeout, USEC_PER_SEC)); + log_dhcp6_client(client, "T1 expires in %s", FORMAT_TIMESPAN(timeout, USEC_PER_SEC)); r = event_reset_time(client->event, &client->timeout_t1, clock_boottime_or_monotonic(), @@ -1652,8 +1649,7 @@ static int client_start(sd_dhcp6_client *client, enum DHCP6State state) { timeout = client_timeout_compute_random(lifetime_t2 * USEC_PER_SEC); - log_dhcp6_client(client, "T2 expires in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, timeout, USEC_PER_SEC)); + log_dhcp6_client(client, "T2 expires in %s", FORMAT_TIMESPAN(timeout, USEC_PER_SEC)); r = event_reset_time(client->event, &client->timeout_t2, clock_boottime_or_monotonic(), diff --git a/src/libsystemd-network/sd-ipv4acd.c b/src/libsystemd-network/sd-ipv4acd.c index 9a77a33317..c6aa9aa11a 100644 --- a/src/libsystemd-network/sd-ipv4acd.c +++ b/src/libsystemd-network/sd-ipv4acd.c @@ -225,10 +225,8 @@ static int ipv4acd_on_timeout(sd_event_source *s, uint64_t usec, void *userdata) ipv4acd_set_state(acd, IPV4ACD_STATE_WAITING_PROBE, true); if (acd->n_conflict >= MAX_CONFLICTS) { - char ts[FORMAT_TIMESPAN_MAX]; - log_ipv4acd(acd, "Max conflicts reached, delaying by %s", - format_timespan(ts, sizeof(ts), RATE_LIMIT_INTERVAL_USEC, 0)); + FORMAT_TIMESPAN(RATE_LIMIT_INTERVAL_USEC, 0)); r = ipv4acd_set_next_wakeup(acd, RATE_LIMIT_INTERVAL_USEC, PROBE_WAIT_USEC); } else r = ipv4acd_set_next_wakeup(acd, 0, PROBE_WAIT_USEC); diff --git a/src/libsystemd-network/sd-ndisc.c b/src/libsystemd-network/sd-ndisc.c index 4d5f1b54cd..9fff9929f7 100644 --- a/src/libsystemd-network/sd-ndisc.c +++ b/src/libsystemd-network/sd-ndisc.c @@ -279,7 +279,6 @@ static usec_t ndisc_timeout_compute_random(usec_t val) { } static int ndisc_timeout(sd_event_source *s, uint64_t usec, void *userdata) { - char time_string[FORMAT_TIMESPAN_MAX]; sd_ndisc *nd = userdata; usec_t time_now; int r; @@ -314,8 +313,7 @@ static int ndisc_timeout(sd_event_source *s, uint64_t usec, void *userdata) { } log_ndisc(nd, "Sent Router Solicitation, next solicitation in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, - nd->retransmit_time, USEC_PER_SEC)); + FORMAT_TIMESPAN(nd->retransmit_time, USEC_PER_SEC)); return 0; diff --git a/src/libsystemd-network/sd-radv.c b/src/libsystemd-network/sd-radv.c index 857401bf6e..79acfa3add 100644 --- a/src/libsystemd-network/sd-radv.c +++ b/src/libsystemd-network/sd-radv.c @@ -301,7 +301,6 @@ static int radv_timeout(sd_event_source *s, uint64_t usec, void *userdata) { usec_t min_timeout = SD_RADV_DEFAULT_MIN_TIMEOUT_USEC; usec_t max_timeout = SD_RADV_DEFAULT_MAX_TIMEOUT_USEC; usec_t time_now, timeout; - char time_string[FORMAT_TIMESPAN_MAX]; assert(s); assert(ra); @@ -329,10 +328,7 @@ static int radv_timeout(sd_event_source *s, uint64_t usec, void *userdata) { } timeout = radv_compute_timeout(min_timeout, max_timeout); - - log_radv(ra, "Next Router Advertisement in %s", - format_timespan(time_string, FORMAT_TIMESPAN_MAX, - timeout, USEC_PER_SEC)); + log_radv(ra, "Next Router Advertisement in %s", FORMAT_TIMESPAN(timeout, USEC_PER_SEC)); r = event_reset_time(ra->event, &ra->timeout_event_source, clock_boottime_or_monotonic(), @@ -545,8 +541,6 @@ _public_ int sd_radv_add_prefix(sd_radv *ra, sd_radv_prefix *p, int dynamic) { sd_radv_prefix *cur; int r; _cleanup_free_ char *addr_p = NULL; - char time_string_preferred[FORMAT_TIMESPAN_MAX]; - char time_string_valid[FORMAT_TIMESPAN_MAX]; usec_t time_now, valid, preferred, valid_until, preferred_until; assert_return(ra, -EINVAL); @@ -628,10 +622,8 @@ _public_ int sd_radv_add_prefix(sd_radv *ra, sd_radv_prefix *p, int dynamic) { log_radv(ra, "Updated prefix %s preferred %s valid %s", strna(addr_p), - format_timespan(time_string_preferred, FORMAT_TIMESPAN_MAX, - preferred, USEC_PER_SEC), - format_timespan(time_string_valid, FORMAT_TIMESPAN_MAX, - valid, USEC_PER_SEC)); + FORMAT_TIMESPAN(preferred, USEC_PER_SEC), + FORMAT_TIMESPAN(valid, USEC_PER_SEC)); return 0; } @@ -662,7 +654,6 @@ _public_ sd_radv_prefix *sd_radv_remove_prefix(sd_radv *ra, } _public_ int sd_radv_add_route_prefix(sd_radv *ra, sd_radv_route_prefix *p, int dynamic) { - char time_string_valid[FORMAT_TIMESPAN_MAX]; usec_t time_now, valid, valid_until; _cleanup_free_ char *pretty = NULL; sd_radv_route_prefix *cur; @@ -732,7 +723,7 @@ _public_ int sd_radv_add_route_prefix(sd_radv *ra, sd_radv_route_prefix *p, int log_radv(ra, "Updated route prefix %s valid %s", strna(pretty), - format_timespan(time_string_valid, FORMAT_TIMESPAN_MAX, valid, USEC_PER_SEC)); + FORMAT_TIMESPAN(valid, USEC_PER_SEC)); return 0; } diff --git a/src/libsystemd-network/test-ndisc-rs.c b/src/libsystemd-network/test-ndisc-rs.c index ce596bb96a..5e50453c35 100644 --- a/src/libsystemd-network/test-ndisc-rs.c +++ b/src/libsystemd-network/test-ndisc-rs.c @@ -31,7 +31,6 @@ static send_ra_t send_ra_function; static void router_dump(sd_ndisc_router *rt) { struct in6_addr addr; - char buf[FORMAT_TIMESTAMP_MAX]; uint8_t hop_limit; uint64_t t, flags; uint32_t mtu; @@ -45,7 +44,7 @@ static void router_dump(sd_ndisc_router *rt) { assert_se(sd_ndisc_router_get_address(rt, &addr) == -ENODATA); assert_se(sd_ndisc_router_get_timestamp(rt, CLOCK_REALTIME, &t) >= 0); - log_info("Timestamp: %s", format_timestamp(buf, sizeof(buf), t)); + log_info("Timestamp: %s", FORMAT_TIMESTAMP(t)); assert_se(sd_ndisc_router_get_timestamp(rt, CLOCK_MONOTONIC, &t) >= 0); log_info("Monotonic: %" PRIu64, t); @@ -318,9 +317,6 @@ static int test_timeout_value(uint8_t flags) { static usec_t last = 0; sd_ndisc *nd = test_timeout_nd; usec_t min, max; - char time_string_min[FORMAT_TIMESPAN_MAX]; - char time_string_nd[FORMAT_TIMESPAN_MAX]; - char time_string_max[FORMAT_TIMESPAN_MAX]; assert_se(nd); assert_se(nd->event); @@ -348,17 +344,12 @@ static int test_timeout_value(uint8_t flags) { NDISC_MAX_ROUTER_SOLICITATION_INTERVAL / 10; } - format_timespan(time_string_min, FORMAT_TIMESPAN_MAX, - min, USEC_PER_MSEC); - format_timespan(time_string_nd, FORMAT_TIMESPAN_MAX, - nd->retransmit_time, USEC_PER_MSEC); - format_timespan(time_string_max, FORMAT_TIMESPAN_MAX, - max, USEC_PER_MSEC); - log_info("backoff timeout interval %2d %s%s <= %s <= %s", count, - (last * 2 > NDISC_MAX_ROUTER_SOLICITATION_INTERVAL)? "(max) ": "", - time_string_min, time_string_nd, time_string_max); + last * 2 > NDISC_MAX_ROUTER_SOLICITATION_INTERVAL ? "(max) ": "", + FORMAT_TIMESPAN(min, USEC_PER_MSEC), + FORMAT_TIMESPAN(nd->retransmit_time, USEC_PER_MSEC), + FORMAT_TIMESPAN(max, USEC_PER_MSEC)); assert_se(min <= nd->retransmit_time); assert_se(max >= nd->retransmit_time); diff --git a/src/libsystemd/sd-bus/bus-dump.c b/src/libsystemd/sd-bus/bus-dump.c index d5d22b0d8c..65b188e88e 100644 --- a/src/libsystemd/sd-bus/bus-dump.c +++ b/src/libsystemd/sd-bus/bus-dump.c @@ -55,15 +55,11 @@ _public_ int sd_bus_message_dump(sd_bus_message *m, FILE *f, uint64_t flags) { f = stdout; if (flags & SD_BUS_MESSAGE_DUMP_WITH_HEADER) { - char buf[FORMAT_TIMESTAMP_MAX]; - const char *p; usec_t ts = m->realtime; if (ts == 0) ts = now(CLOCK_REALTIME); - p = format_timestamp_style(buf, sizeof(buf), ts, TIMESTAMP_US_UTC); - fprintf(f, "%s%s%s Type=%s%s%s Endian=%c Flags=%u Version=%u", m->header->type == SD_BUS_MESSAGE_METHOD_ERROR ? ansi_highlight_red() : @@ -90,9 +86,7 @@ _public_ int sd_bus_message_dump(sd_bus_message *m, FILE *f, uint64_t flags) { if (m->reply_cookie != 0) fprintf(f, " ReplyCookie=%" PRIu64, m->reply_cookie); - fprintf(f, " Timestamp=\"%s\"", strna(p)); - - fputs("\n", f); + fprintf(f, " Timestamp=\"%s\"\n", strna(FORMAT_TIMESTAMP_STYLE(ts, TIMESTAMP_US_UTC))); if (m->sender) fprintf(f, " Sender=%s%s%s", ansi_highlight(), m->sender, ansi_normal()); @@ -395,10 +389,8 @@ int bus_creds_dump(sd_bus_creds *c, FILE *f, bool terse) { fprintf(f, "%sFSGID=%s"GID_FMT"%s", prefix, color, c->fsgid, suffix); if (c->mask & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) { - unsigned i; - fprintf(f, "%sSupplementaryGIDs=%s", prefix, color); - for (i = 0; i < c->n_supplementary_gids; i++) + for (unsigned i = 0; i < c->n_supplementary_gids; i++) fprintf(f, "%s" GID_FMT, i > 0 ? " " : "", c->supplementary_gids[i]); fprintf(f, "%s", suffix); } diff --git a/src/libsystemd/sd-bus/bus-error.c b/src/libsystemd/sd-bus/bus-error.c index 7483b46a11..bdfa145ab7 100644 --- a/src/libsystemd/sd-bus/bus-error.c +++ b/src/libsystemd/sd-bus/bus-error.c @@ -252,10 +252,15 @@ int bus_error_setfv(sd_bus_error *e, const char *name, const char *format, va_li return -ENOMEM; } - /* If we hit OOM on formatting the pretty message, we ignore - * this, since we at least managed to write the error name */ - if (format) - (void) vasprintf((char**) &e->message, format, ap); + if (format) { + _cleanup_free_ char *mesg = NULL; + + /* If we hit OOM on formatting the pretty message, we ignore + * this, since we at least managed to write the error name */ + + if (vasprintf(&mesg, format, ap) >= 0) + e->message = TAKE_PTR(mesg); + } e->_need_free = 1; } diff --git a/src/libsystemd/sd-journal/journal-file.c b/src/libsystemd/sd-journal/journal-file.c index 2c17435de2..abbe35c33b 100644 --- a/src/libsystemd/sd-journal/journal-file.c +++ b/src/libsystemd/sd-journal/journal-file.c @@ -3269,20 +3269,12 @@ fail: log_error("File corrupt"); } -static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) { - const char *x; - - x = format_timestamp(buf, l, t); - if (x) - return x; - return " --- "; -} +/* Note: the lifetime of the compound literal is the immediately surrounding block. */ +#define FORMAT_TIMESTAMP_SAFE(t) (FORMAT_TIMESTAMP(t) ?: " --- ") void journal_file_print_header(JournalFile *f) { char a[SD_ID128_STRING_MAX], b[SD_ID128_STRING_MAX], c[SD_ID128_STRING_MAX], d[SD_ID128_STRING_MAX]; - char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX], z[FORMAT_TIMESTAMP_MAX]; struct stat st; - char bytes[FORMAT_BYTES_MAX]; assert(f); assert(f->header); @@ -3329,9 +3321,9 @@ void journal_file_print_header(JournalFile *f) { yes_no(journal_file_rotate_suggested(f, 0)), le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum), le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum), - format_timestamp_safe(x, sizeof(x), le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime), - format_timestamp_safe(y, sizeof(y), le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime), - format_timespan(z, sizeof(z), le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic), + FORMAT_TIMESTAMP_SAFE(le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime), + FORMAT_TIMESTAMP_SAFE(le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime), + FORMAT_TIMESPAN(le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic), le64toh(f->header->n_objects), le64toh(f->header->n_entries)); @@ -3363,7 +3355,7 @@ void journal_file_print_header(JournalFile *f) { f->header->data_hash_chain_depth); if (fstat(f->fd, &st) >= 0) - printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL)); + printf("Disk usage: %s\n", FORMAT_BYTES((uint64_t) st.st_blocks * 512ULL)); } static int journal_file_warn_btrfs(JournalFile *f) { @@ -3468,7 +3460,6 @@ int journal_file_open( if (DEBUG_LOGGING) { static int last_seal = -1, last_compress = -1, last_keyed_hash = -1; static uint64_t last_bytes = UINT64_MAX; - char bytes[FORMAT_BYTES_MAX]; if (last_seal != f->seal || last_keyed_hash != f->keyed_hash || @@ -3477,7 +3468,7 @@ int journal_file_open( log_debug("Journal effective settings seal=%s keyed_hash=%s compress=%s compress_threshold_bytes=%s", yes_no(f->seal), yes_no(f->keyed_hash), yes_no(JOURNAL_FILE_COMPRESS(f)), - format_bytes(bytes, sizeof bytes, f->compress_threshold_bytes)); + FORMAT_BYTES(f->compress_threshold_bytes)); last_seal = f->seal; last_keyed_hash = f->keyed_hash; last_compress = JOURNAL_FILE_COMPRESS(f); @@ -3977,7 +3968,6 @@ void journal_reset_metrics(JournalMetrics *m) { } void journal_default_metrics(JournalMetrics *m, int fd) { - char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX], e[FORMAT_BYTES_MAX]; struct statvfs ss; uint64_t fs_size = 0; @@ -4047,11 +4037,11 @@ void journal_default_metrics(JournalMetrics *m, int fd) { m->n_max_files = DEFAULT_N_MAX_FILES; log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64, - format_bytes(a, sizeof(a), m->min_use), - format_bytes(b, sizeof(b), m->max_use), - format_bytes(c, sizeof(c), m->max_size), - format_bytes(d, sizeof(d), m->min_size), - format_bytes(e, sizeof(e), m->keep_free), + FORMAT_BYTES(m->min_use), + FORMAT_BYTES(m->max_use), + FORMAT_BYTES(m->max_size), + FORMAT_BYTES(m->min_size), + FORMAT_BYTES(m->keep_free), m->n_max_files); } diff --git a/src/libsystemd/sd-journal/journal-vacuum.c b/src/libsystemd/sd-journal/journal-vacuum.c index 494a54d33b..6d761b78eb 100644 --- a/src/libsystemd/sd-journal/journal-vacuum.c +++ b/src/libsystemd/sd-journal/journal-vacuum.c @@ -131,7 +131,6 @@ int journal_directory_vacuum( _cleanup_closedir_ DIR *d = NULL; struct vacuum_info *list = NULL; usec_t retention_limit = 0; - char sbytes[FORMAT_BYTES_MAX]; struct dirent *de; int r; @@ -148,7 +147,6 @@ int journal_directory_vacuum( return -errno; FOREACH_DIRENT_ALL(de, d, r = -errno; goto finish) { - unsigned long long seqnum = 0, realtime; _cleanup_free_ char *p = NULL; sd_id128_t seqnum_id; @@ -254,7 +252,7 @@ int journal_directory_vacuum( if (r >= 0) { log_full(verbose ? LOG_INFO : LOG_DEBUG, - "Deleted empty archived journal %s/%s (%s).", directory, p, format_bytes(sbytes, sizeof(sbytes), size)); + "Deleted empty archived journal %s/%s (%s).", directory, p, FORMAT_BYTES(size)); freed += size; } else if (r != -ENOENT) @@ -296,7 +294,8 @@ int journal_directory_vacuum( r = unlinkat_deallocate(dirfd(d), list[i].filename, 0); if (r >= 0) { - log_full(verbose ? LOG_INFO : LOG_DEBUG, "Deleted archived journal %s/%s (%s).", directory, list[i].filename, format_bytes(sbytes, sizeof(sbytes), list[i].usage)); + log_full(verbose ? LOG_INFO : LOG_DEBUG, "Deleted archived journal %s/%s (%s).", + directory, list[i].filename, FORMAT_BYTES(list[i].usage)); freed += list[i].usage; if (list[i].usage < sum) @@ -318,7 +317,8 @@ finish: free(list[i].filename); free(list); - log_full(verbose ? LOG_INFO : LOG_DEBUG, "Vacuuming done, freed %s of archived journals from %s.", format_bytes(sbytes, sizeof(sbytes), freed), directory); + log_full(verbose ? LOG_INFO : LOG_DEBUG, "Vacuuming done, freed %s of archived journals from %s.", + FORMAT_BYTES(freed), directory); return r; } diff --git a/src/libsystemd/sd-journal/test-journal-verify.c b/src/libsystemd/sd-journal/test-journal-verify.c index e9abfef0fc..8eb9ca88f7 100644 --- a/src/libsystemd/sd-journal/test-journal-verify.c +++ b/src/libsystemd/sd-journal/test-journal-verify.c @@ -57,9 +57,6 @@ int main(int argc, char *argv[]) { JournalFile *f; const char *verification_key = argv[1]; usec_t from = 0, to = 0, total = 0; - char a[FORMAT_TIMESTAMP_MAX]; - char b[FORMAT_TIMESTAMP_MAX]; - char c[FORMAT_TIMESPAN_MAX]; struct stat st; uint64_t p; @@ -105,9 +102,9 @@ int main(int argc, char *argv[]) { if (verification_key && JOURNAL_HEADER_SEALED(f->header)) log_info("=> Validated from %s to %s, %s missing", - format_timestamp(a, sizeof(a), from), - format_timestamp(b, sizeof(b), to), - format_timespan(c, sizeof(c), total > to ? total - to : 0, 0)); + FORMAT_TIMESTAMP(from), + FORMAT_TIMESTAMP(to), + FORMAT_TIMESPAN(total > to ? total - to : 0, 0)); (void) journal_file_close(f); diff --git a/src/login/loginctl.c b/src/login/loginctl.c index cbb6518f4d..318d71a28a 100644 --- a/src/login/loginctl.c +++ b/src/login/loginctl.c @@ -450,8 +450,6 @@ static int print_session_status_info(sd_bus *bus, const char *path, bool *new_li _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; - char since1[FORMAT_TIMESTAMP_RELATIVE_MAX]; - char since2[FORMAT_TIMESTAMP_MAX]; const char *s1, *s2; SessionStatusInfo i = {}; int r; @@ -472,8 +470,8 @@ static int print_session_status_info(sd_bus *bus, const char *path, bool *new_li else printf("%"PRIu32"\n", i.uid); - s1 = format_timestamp_relative(since1, sizeof(since1), i.timestamp.realtime); - s2 = format_timestamp(since2, sizeof(since2), i.timestamp.realtime); + s1 = FORMAT_TIMESTAMP_RELATIVE(i.timestamp.realtime); + s2 = FORMAT_TIMESTAMP(i.timestamp.realtime); if (s1) printf("\t Since: %s; %s\n", s2, s1); @@ -581,8 +579,6 @@ static int print_user_status_info(sd_bus *bus, const char *path, bool *new_line) _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; - char since1[FORMAT_TIMESTAMP_RELATIVE_MAX]; - char since2[FORMAT_TIMESTAMP_MAX]; const char *s1, *s2; _cleanup_(user_status_info_clear) UserStatusInfo i = {}; int r; @@ -601,8 +597,8 @@ static int print_user_status_info(sd_bus *bus, const char *path, bool *new_line) else printf("%"PRIu32"\n", i.uid); - s1 = format_timestamp_relative(since1, sizeof(since1), i.timestamp.realtime); - s2 = format_timestamp(since2, sizeof(since2), i.timestamp.realtime); + s1 = FORMAT_TIMESTAMP_RELATIVE(i.timestamp.realtime); + s2 = FORMAT_TIMESTAMP(i.timestamp.realtime); if (s1) printf("\t Since: %s; %s\n", s2, s1); diff --git a/src/login/logind-user.c b/src/login/logind-user.c index a2c468e8dd..1c8d84329f 100644 --- a/src/login/logind-user.c +++ b/src/login/logind-user.c @@ -867,13 +867,10 @@ void user_update_last_session_timer(User *u) { if (r < 0) log_warning_errno(r, "Failed to enqueue user stop event source, ignoring: %m"); - if (DEBUG_LOGGING) { - char s[FORMAT_TIMESPAN_MAX]; - + if (DEBUG_LOGGING) log_debug("Last session of user '%s' logged out, terminating user context in %s.", u->user_record->user_name, - format_timespan(s, sizeof(s), user_stop_delay, USEC_PER_MSEC)); - } + FORMAT_TIMESPAN(user_stop_delay, USEC_PER_MSEC)); } static const char* const user_state_table[_USER_STATE_MAX] = { diff --git a/src/login/logind-utmp.c b/src/login/logind-utmp.c index dfbbb641f3..5533836473 100644 --- a/src/login/logind-utmp.c +++ b/src/login/logind-utmp.c @@ -58,7 +58,6 @@ bool logind_wall_tty_filter(const char *tty, void *userdata) { } static int warn_wall(Manager *m, usec_t n) { - char date[FORMAT_TIMESTAMP_MAX] = {}; _cleanup_free_ char *l = NULL, *username = NULL; usec_t left; int r; @@ -75,7 +74,7 @@ static int warn_wall(Manager *m, usec_t n) { isempty(m->wall_message) ? "" : "\n", m->scheduled_shutdown_type, left ? "at " : "NOW", - left ? format_timestamp(date, sizeof(date), m->scheduled_shutdown_timeout) : ""); + left ? FORMAT_TIMESTAMP(m->scheduled_shutdown_timeout) : ""); if (r < 0) { log_oom(); return 0; diff --git a/src/machine/machinectl.c b/src/machine/machinectl.c index beab50e315..06ca335cff 100644 --- a/src/machine/machinectl.c +++ b/src/machine/machinectl.c @@ -507,8 +507,6 @@ static void machine_status_info_clear(MachineStatusInfo *info) { } static void print_machine_status_info(sd_bus *bus, MachineStatusInfo *i) { - char since1[FORMAT_TIMESTAMP_RELATIVE_MAX]; - char since2[FORMAT_TIMESTAMP_MAX]; _cleanup_free_ char *addresses = NULL; const char *s1, *s2; int ifi = -1; @@ -523,8 +521,8 @@ static void print_machine_status_info(sd_bus *bus, MachineStatusInfo *i) { else putchar('\n'); - s1 = format_timestamp_relative(since1, sizeof(since1), i->timestamp.realtime); - s2 = format_timestamp(since2, sizeof(since2), i->timestamp.realtime); + s1 = FORMAT_TIMESTAMP_RELATIVE(i->timestamp.realtime); + s2 = FORMAT_TIMESTAMP(i->timestamp.realtime); if (s1) printf("\t Since: %s; %s\n", s2, s1); @@ -828,10 +826,6 @@ typedef struct ImageStatusInfo { } ImageStatusInfo; static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) { - char ts_relative[FORMAT_TIMESTAMP_RELATIVE_MAX]; - char ts_absolute[FORMAT_TIMESTAMP_MAX]; - char bs[FORMAT_BYTES_MAX]; - char bs_exclusive[FORMAT_BYTES_MAX]; const char *s1, *s2, *s3, *s4; assert(bus); @@ -859,29 +853,29 @@ static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) { i->read_only ? "read-only" : "writable", i->read_only ? ansi_normal() : ""); - s1 = format_timestamp_relative(ts_relative, sizeof(ts_relative), i->crtime); - s2 = format_timestamp(ts_absolute, sizeof(ts_absolute), i->crtime); + s1 = FORMAT_TIMESTAMP_RELATIVE(i->crtime); + s2 = FORMAT_TIMESTAMP(i->crtime); if (s1 && s2) printf("\t Created: %s; %s\n", s2, s1); else if (s2) printf("\t Created: %s\n", s2); - s1 = format_timestamp_relative(ts_relative, sizeof(ts_relative), i->mtime); - s2 = format_timestamp(ts_absolute, sizeof(ts_absolute), i->mtime); + s1 = FORMAT_TIMESTAMP_RELATIVE(i->mtime); + s2 = FORMAT_TIMESTAMP(i->mtime); if (s1 && s2) printf("\tModified: %s; %s\n", s2, s1); else if (s2) printf("\tModified: %s\n", s2); - s3 = format_bytes(bs, sizeof(bs), i->usage); - s4 = i->usage_exclusive != i->usage ? format_bytes(bs_exclusive, sizeof(bs_exclusive), i->usage_exclusive) : NULL; + s3 = FORMAT_BYTES(i->usage); + s4 = i->usage_exclusive != i->usage ? FORMAT_BYTES(i->usage_exclusive) : NULL; if (s3 && s4) printf("\t Usage: %s (exclusive: %s)\n", s3, s4); else if (s3) printf("\t Usage: %s\n", s3); - s3 = format_bytes(bs, sizeof(bs), i->limit); - s4 = i->limit_exclusive != i->limit ? format_bytes(bs_exclusive, sizeof(bs_exclusive), i->limit_exclusive) : NULL; + s3 = FORMAT_BYTES(i->limit); + s4 = i->limit_exclusive != i->limit ? FORMAT_BYTES(i->limit_exclusive) : NULL; if (s3 && s4) printf("\t Limit: %s (exclusive: %s)\n", s3, s4); else if (s3) @@ -940,16 +934,16 @@ typedef struct PoolStatusInfo { } PoolStatusInfo; static void print_pool_status_info(sd_bus *bus, PoolStatusInfo *i) { - char bs[FORMAT_BYTES_MAX], *s; + char *s; if (i->path) printf("\t Path: %s\n", i->path); - s = format_bytes(bs, sizeof(bs), i->usage); + s = FORMAT_BYTES(i->usage); if (s) printf("\t Usage: %s\n", s); - s = format_bytes(bs, sizeof(bs), i->limit); + s = FORMAT_BYTES(i->limit); if (s) printf("\t Limit: %s\n", s); } @@ -2409,7 +2403,6 @@ static int clean_images(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; uint64_t usage, total = 0; - char fb[FORMAT_BYTES_MAX]; sd_bus *bus = userdata; const char *name; unsigned c = 0; @@ -2440,7 +2433,7 @@ static int clean_images(int argc, char *argv[], void *userdata) { total = UINT64_MAX; } else { log_info("Removed image '%s'. Freed exclusive disk space: %s", - name, format_bytes(fb, sizeof(fb), usage)); + name, FORMAT_BYTES(usage)); if (total != UINT64_MAX) total += usage; } @@ -2455,7 +2448,7 @@ static int clean_images(int argc, char *argv[], void *userdata) { log_info("Removed %u images in total.", c); else log_info("Removed %u images in total. Total freed exclusive disk space: %s.", - c, format_bytes(fb, sizeof(fb), total)); + c, FORMAT_BYTES(total)); return 0; } diff --git a/src/network/networkctl.c b/src/network/networkctl.c index 9bbfe177b1..0ebb11cefa 100644 --- a/src/network/networkctl.c +++ b/src/network/networkctl.c @@ -2121,16 +2121,14 @@ static int link_status_one( } if (info->has_bitrates) { - char tx[FORMAT_BYTES_MAX], rx[FORMAT_BYTES_MAX]; - r = table_add_many(table, TABLE_EMPTY, TABLE_STRING, "Bit Rate (Tx/Rx):"); if (r < 0) return table_log_add_error(r); r = table_add_cell_stringf(table, NULL, "%sbps/%sbps", - format_bytes_full(tx, sizeof tx, info->tx_bitrate, 0), - format_bytes_full(rx, sizeof rx, info->rx_bitrate, 0)); + FORMAT_BYTES_FULL(info->tx_bitrate, 0), + FORMAT_BYTES_FULL(info->rx_bitrate, 0)); if (r < 0) return table_log_add_error(r); } diff --git a/src/network/networkd-address.c b/src/network/networkd-address.c index 35305aff99..3a4ab629f8 100644 --- a/src/network/networkd-address.c +++ b/src/network/networkd-address.c @@ -622,7 +622,6 @@ int manager_has_address(Manager *manager, int family, const union in_addr_union static void log_address_debug(const Address *address, const char *str, const Link *link) { _cleanup_free_ char *addr = NULL, *peer = NULL, *flags_str = NULL; - char valid_buf[FORMAT_TIMESPAN_MAX], preferred_buf[FORMAT_TIMESPAN_MAX]; const char *valid_str = NULL, *preferred_str = NULL; bool has_peer; @@ -639,14 +638,10 @@ static void log_address_debug(const Address *address, const char *str, const Lin (void) in_addr_to_string(address->family, &address->in_addr_peer, &peer); if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME) - valid_str = format_timespan(valid_buf, FORMAT_TIMESPAN_MAX, - address->cinfo.ifa_valid * USEC_PER_SEC, - USEC_PER_SEC); + valid_str = FORMAT_TIMESPAN(address->cinfo.ifa_valid * USEC_PER_SEC, USEC_PER_SEC); if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME) - preferred_str = format_timespan(preferred_buf, FORMAT_TIMESPAN_MAX, - address->cinfo.ifa_prefered * USEC_PER_SEC, - USEC_PER_SEC); + preferred_str = FORMAT_TIMESPAN(address->cinfo.ifa_prefered * USEC_PER_SEC, USEC_PER_SEC); (void) address_flags_to_string_alloc(address->flags, address->family, &flags_str); diff --git a/src/network/networkd-can.c b/src/network/networkd-can.c index 1fa37a0584..950b4134dd 100644 --- a/src/network/networkd-can.c +++ b/src/network/networkd-can.c @@ -107,7 +107,6 @@ int can_set_netlink_message(Link *link, sd_netlink_message *m) { } if (link->network->can_restart_us > 0) { - char time_string[FORMAT_TIMESPAN_MAX]; uint64_t restart_ms; if (link->network->can_restart_us == USEC_INFINITY) @@ -115,12 +114,11 @@ int can_set_netlink_message(Link *link, sd_netlink_message *m) { else restart_ms = DIV_ROUND_UP(link->network->can_restart_us, USEC_PER_MSEC); - format_timespan(time_string, FORMAT_TIMESPAN_MAX, restart_ms * 1000, MSEC_PER_SEC); - if (restart_ms > UINT32_MAX) - return log_link_debug_errno(link, SYNTHETIC_ERRNO(ERANGE), "restart timeout (%s) too big.", time_string); + return log_link_debug_errno(link, SYNTHETIC_ERRNO(ERANGE), "restart timeout (%s) too big.", + FORMAT_TIMESPAN(restart_ms * 1000, MSEC_PER_SEC)); - log_link_debug(link, "Setting restart = %s", time_string); + log_link_debug(link, "Setting restart = %s", FORMAT_TIMESPAN(restart_ms * 1000, MSEC_PER_SEC)); r = sd_netlink_message_append_u32(m, IFLA_CAN_RESTART_MS, restart_ms); if (r < 0) diff --git a/src/network/networkd-conf.c b/src/network/networkd-conf.c index 0b55ef29a2..9190dbfc53 100644 --- a/src/network/networkd-conf.c +++ b/src/network/networkd-conf.c @@ -29,10 +29,8 @@ int manager_parse_config_file(Manager *m) { return r; if (m->use_speed_meter && m->speed_meter_interval_usec < SPEED_METER_MINIMUM_TIME_INTERVAL) { - char buf[FORMAT_TIMESPAN_MAX]; - log_warning("SpeedMeterIntervalSec= is too small, using %s.", - format_timespan(buf, sizeof buf, SPEED_METER_MINIMUM_TIME_INTERVAL, USEC_PER_SEC)); + FORMAT_TIMESPAN(SPEED_METER_MINIMUM_TIME_INTERVAL, USEC_PER_SEC)); m->speed_meter_interval_usec = SPEED_METER_MINIMUM_TIME_INTERVAL; } diff --git a/src/network/networkd-dhcp6.c b/src/network/networkd-dhcp6.c index 367be0a756..ccf2ec5b3f 100644 --- a/src/network/networkd-dhcp6.c +++ b/src/network/networkd-dhcp6.c @@ -373,7 +373,6 @@ static int dhcp6_pd_address_handler(sd_netlink *rtnl, sd_netlink_message *m, Lin } static void log_dhcp6_pd_address(Link *link, const Address *address) { - char valid_buf[FORMAT_TIMESPAN_MAX], preferred_buf[FORMAT_TIMESPAN_MAX]; const char *valid_str = NULL, *preferred_str = NULL; _cleanup_free_ char *buffer = NULL; int log_level; @@ -388,13 +387,9 @@ static void log_dhcp6_pd_address(Link *link, const Address *address) { (void) in6_addr_prefix_to_string(&address->in_addr.in6, address->prefixlen, &buffer); if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME) - valid_str = format_timespan(valid_buf, FORMAT_TIMESPAN_MAX, - address->cinfo.ifa_valid * USEC_PER_SEC, - USEC_PER_SEC); + valid_str = FORMAT_TIMESPAN(address->cinfo.ifa_valid * USEC_PER_SEC, USEC_PER_SEC); if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME) - preferred_str = format_timespan(preferred_buf, FORMAT_TIMESPAN_MAX, - address->cinfo.ifa_prefered * USEC_PER_SEC, - USEC_PER_SEC); + preferred_str = FORMAT_TIMESPAN(address->cinfo.ifa_prefered * USEC_PER_SEC, USEC_PER_SEC); log_link_full(link, log_level, "DHCPv6-PD address %s (valid %s%s, preferred %s%s)", strna(buffer), @@ -1061,8 +1056,6 @@ static int dhcp6_address_handler(sd_netlink *rtnl, sd_netlink_message *m, Link * } static void log_dhcp6_address(Link *link, const Address *address, char **ret) { - char valid_buf[FORMAT_TIMESPAN_MAX], preferred_buf[FORMAT_TIMESPAN_MAX]; - const char *valid_str = NULL, *preferred_str = NULL; _cleanup_free_ char *buffer = NULL; bool by_ndisc = false; Address *existing; @@ -1074,14 +1067,11 @@ static void log_dhcp6_address(Link *link, const Address *address, char **ret) { assert(address->family == AF_INET6); (void) in6_addr_prefix_to_string(&address->in_addr.in6, address->prefixlen, &buffer); - if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME) - valid_str = format_timespan(valid_buf, FORMAT_TIMESPAN_MAX, - address->cinfo.ifa_valid * USEC_PER_SEC, - USEC_PER_SEC); - if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME) - preferred_str = format_timespan(preferred_buf, FORMAT_TIMESPAN_MAX, - address->cinfo.ifa_prefered * USEC_PER_SEC, - USEC_PER_SEC); + + const char *valid_str = address->cinfo.ifa_valid == CACHE_INFO_INFINITY_LIFE_TIME ? NULL : + FORMAT_TIMESPAN(address->cinfo.ifa_valid * USEC_PER_SEC, USEC_PER_SEC); + const char *preferred_str = address->cinfo.ifa_prefered == CACHE_INFO_INFINITY_LIFE_TIME ? NULL : + FORMAT_TIMESPAN(address->cinfo.ifa_prefered * USEC_PER_SEC, USEC_PER_SEC); r = address_get(link, address, &existing); if (r < 0) { diff --git a/src/network/networkd-nexthop.c b/src/network/networkd-nexthop.c index a52e5dcb16..87f4ee4b10 100644 --- a/src/network/networkd-nexthop.c +++ b/src/network/networkd-nexthop.c @@ -15,6 +15,7 @@ #include "networkd-route.h" #include "parse-util.h" #include "set.h" +#include "stdio-util.h" #include "string-util.h" NextHop *nexthop_free(NextHop *nexthop) { @@ -368,7 +369,7 @@ set_manager: } static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *str, const Link *link) { - _cleanup_free_ char *gw = NULL, *new_id = NULL, *group = NULL; + _cleanup_free_ char *gw = NULL, *group = NULL; struct nexthop_grp *nhg; assert(nexthop); @@ -379,8 +380,9 @@ static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *s if (!DEBUG_LOGGING) return; + char new_id[STRLEN("→") + DECIMAL_STR_MAX(uint32_t)] = ""; if (nexthop->id != id) - (void) asprintf(&new_id, "→%"PRIu32, id); + xsprintf(new_id, "→%"PRIu32, id); (void) in_addr_to_string(nexthop->family, &nexthop->gw, &gw); @@ -388,7 +390,7 @@ static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *s (void) strextendf_with_separator(&group, ",", "%"PRIu32":%"PRIu32, nhg->id, nhg->weight+1); log_link_debug(link, "%s nexthop: id: %"PRIu32"%s, gw: %s, blackhole: %s, group: %s", - str, nexthop->id, strempty(new_id), strna(gw), yes_no(nexthop->blackhole), strna(group)); + str, nexthop->id, new_id, strna(gw), yes_no(nexthop->blackhole), strna(group)); } static int link_nexthop_remove_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) { diff --git a/src/network/networkd-route.c b/src/network/networkd-route.c index 0ab4419eba..b6c19223b6 100644 --- a/src/network/networkd-route.c +++ b/src/network/networkd-route.c @@ -110,6 +110,7 @@ int manager_get_route_table_from_string(const Manager *m, const char *s, uint32_ int manager_get_route_table_to_string(const Manager *m, uint32_t table, char **ret) { _cleanup_free_ char *str = NULL; const char *s; + int r; assert(m); assert(ret); @@ -121,17 +122,13 @@ int manager_get_route_table_to_string(const Manager *m, uint32_t table, char **r if (!s) s = hashmap_get(m->route_table_names_by_number, UINT32_TO_PTR(table)); - if (s) { + if (s) /* Currently, this is only used in debugging logs. To not confuse any bug * reports, let's include the table number. */ - if (asprintf(&str, "%s(%" PRIu32 ")", s, table) < 0) - return -ENOMEM; - - *ret = TAKE_PTR(str); - return 0; - } - - if (asprintf(&str, "%" PRIu32, table) < 0) + r = asprintf(&str, "%s(%" PRIu32 ")", s, table); + else + r = asprintf(&str, "%" PRIu32, table); + if (r < 0) return -ENOMEM; *ret = TAKE_PTR(str); diff --git a/src/oom/oomd-manager.c b/src/oom/oomd-manager.c index 9cae0c9c8a..4d7c28fe8e 100644 --- a/src/oom/oomd-manager.c +++ b/src/oom/oomd-manager.c @@ -442,7 +442,6 @@ static int monitor_memory_pressure_contexts_handler(sd_event_source *s, uint64_t OomdCGroupContext *t; SET_FOREACH(t, targets) { _cleanup_free_ char *selected = NULL; - char ts[FORMAT_TIMESPAN_MAX]; /* Check if there was reclaim activity in the given interval. The concern is the following case: * Pressure climbed, a lot of high-frequency pages were reclaimed, and we killed the offending @@ -456,9 +455,7 @@ static int monitor_memory_pressure_contexts_handler(sd_event_source *s, uint64_t t->path, LOAD_INT(t->memory_pressure.avg10), LOAD_FRAC(t->memory_pressure.avg10), LOAD_INT(t->mem_pressure_limit), LOAD_FRAC(t->mem_pressure_limit), - format_timespan(ts, sizeof ts, - m->default_mem_pressure_duration_usec, - USEC_PER_SEC)); + FORMAT_TIMESPAN(m->default_mem_pressure_duration_usec, USEC_PER_SEC)); r = update_monitored_cgroup_contexts_candidates( m->monitored_mem_pressure_cgroup_contexts, &m->monitored_mem_pressure_cgroup_contexts_candidates); @@ -483,9 +480,7 @@ static int monitor_memory_pressure_contexts_handler(sd_event_source *s, uint64_t selected, t->path, LOAD_INT(t->memory_pressure.avg10), LOAD_FRAC(t->memory_pressure.avg10), LOAD_INT(t->mem_pressure_limit), LOAD_FRAC(t->mem_pressure_limit), - format_timespan(ts, sizeof ts, - m->default_mem_pressure_duration_usec, - USEC_PER_SEC)); + FORMAT_TIMESPAN(m->default_mem_pressure_duration_usec, USEC_PER_SEC)); return 0; } } @@ -707,7 +702,6 @@ int manager_start( int manager_get_dump_string(Manager *m, char **ret) { _cleanup_free_ char *dump = NULL; _cleanup_fclose_ FILE *f = NULL; - char buf[FORMAT_TIMESPAN_MAX]; OomdCGroupContext *c; size_t size; char *key; @@ -729,7 +723,7 @@ int manager_get_dump_string(Manager *m, char **ret) { yes_no(m->dry_run), PERMYRIAD_AS_PERCENT_FORMAT_VAL(m->swap_used_limit_permyriad), LOAD_INT(m->default_mem_pressure_limit), LOAD_FRAC(m->default_mem_pressure_limit), - format_timespan(buf, sizeof(buf), m->default_mem_pressure_duration_usec, USEC_PER_SEC)); + FORMAT_TIMESPAN(m->default_mem_pressure_duration_usec, USEC_PER_SEC)); oomd_dump_system_context(&m->system_context, f, "\t"); fprintf(f, "Swap Monitored CGroups:\n"); diff --git a/src/oom/oomd-util.c b/src/oom/oomd-util.c index b2a48acb1f..ff0fc13c6f 100644 --- a/src/oom/oomd-util.c +++ b/src/oom/oomd-util.c @@ -503,8 +503,6 @@ void oomd_update_cgroup_contexts_between_hashmaps(Hashmap *old_h, Hashmap *curr_ } void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) { - char swap[FORMAT_BYTES_MAX]; - assert(ctx); assert(f); @@ -513,7 +511,7 @@ void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const "%sPath: %s\n" "%s\tSwap Usage: %s\n", strempty(prefix), ctx->path, - strempty(prefix), format_bytes(swap, sizeof(swap), ctx->swap_usage)); + strempty(prefix), FORMAT_BYTES(ctx->swap_usage)); else fprintf(f, "%sPath: %s\n" @@ -523,9 +521,6 @@ void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const } void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) { - char tbuf[FORMAT_TIMESPAN_MAX], mem_use[FORMAT_BYTES_MAX]; - char mem_min[FORMAT_BYTES_MAX], mem_low[FORMAT_BYTES_MAX]; - assert(ctx); assert(f); @@ -540,8 +535,8 @@ void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE LOAD_INT(ctx->memory_pressure.avg10), LOAD_FRAC(ctx->memory_pressure.avg10), LOAD_INT(ctx->memory_pressure.avg60), LOAD_FRAC(ctx->memory_pressure.avg60), LOAD_INT(ctx->memory_pressure.avg300), LOAD_FRAC(ctx->memory_pressure.avg300), - format_timespan(tbuf, sizeof(tbuf), ctx->memory_pressure.total, USEC_PER_SEC), - strempty(prefix), format_bytes(mem_use, sizeof(mem_use), ctx->current_memory_usage)); + FORMAT_TIMESPAN(ctx->memory_pressure.total, USEC_PER_SEC), + strempty(prefix), FORMAT_BYTES(ctx->current_memory_usage)); if (!empty_or_root(ctx->path)) fprintf(f, @@ -549,16 +544,13 @@ void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE "%s\tMemory Low: %s\n" "%s\tPgscan: %" PRIu64 "\n" "%s\tLast Pgscan: %" PRIu64 "\n", - strempty(prefix), format_bytes_cgroup_protection(mem_min, sizeof(mem_min), ctx->memory_min), - strempty(prefix), format_bytes_cgroup_protection(mem_low, sizeof(mem_low), ctx->memory_low), + strempty(prefix), FORMAT_BYTES_CGROUP_PROTECTION(ctx->memory_min), + strempty(prefix), FORMAT_BYTES_CGROUP_PROTECTION(ctx->memory_low), strempty(prefix), ctx->pgscan, strempty(prefix), ctx->last_pgscan); } void oomd_dump_system_context(const OomdSystemContext *ctx, FILE *f, const char *prefix) { - char mem_used[FORMAT_BYTES_MAX], mem_total[FORMAT_BYTES_MAX]; - char swap_used[FORMAT_BYTES_MAX], swap_total[FORMAT_BYTES_MAX]; - assert(ctx); assert(f); @@ -566,9 +558,9 @@ void oomd_dump_system_context(const OomdSystemContext *ctx, FILE *f, const char "%sMemory: Used: %s Total: %s\n" "%sSwap: Used: %s Total: %s\n", strempty(prefix), - format_bytes(mem_used, sizeof(mem_used), ctx->mem_used), - format_bytes(mem_total, sizeof(mem_total), ctx->mem_total), + FORMAT_BYTES(ctx->mem_used), + FORMAT_BYTES(ctx->mem_total), strempty(prefix), - format_bytes(swap_used, sizeof(swap_used), ctx->swap_used), - format_bytes(swap_total, sizeof(swap_total), ctx->swap_total)); + FORMAT_BYTES(ctx->swap_used), + FORMAT_BYTES(ctx->swap_total)); } diff --git a/src/partition/growfs.c b/src/partition/growfs.c index 15c56d0584..0497c6cfc6 100644 --- a/src/partition/growfs.c +++ b/src/partition/growfs.c @@ -197,7 +197,6 @@ static int run(int argc, char *argv[]) { _cleanup_close_ int mountfd = -1, devfd = -1; _cleanup_free_ char *devpath = NULL; uint64_t size, newsize; - char fb[FORMAT_BYTES_MAX]; dev_t devno; int r; @@ -248,11 +247,11 @@ static int run(int argc, char *argv[]) { if (newsize == size) log_info("Successfully resized \"%s\" to %s bytes.", arg_target, - format_bytes(fb, sizeof fb, newsize)); + FORMAT_BYTES(newsize)); else log_info("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).", arg_target, - format_bytes(fb, sizeof fb, newsize), + FORMAT_BYTES(newsize), size - newsize); return 0; } diff --git a/src/partition/repart.c b/src/partition/repart.c index ac317f6adc..6d535a3bab 100644 --- a/src/partition/repart.c +++ b/src/partition/repart.c @@ -1932,29 +1932,24 @@ static void context_unload_partition_table(Context *context) { } static int format_size_change(uint64_t from, uint64_t to, char **ret) { - char format_buffer1[FORMAT_BYTES_MAX], format_buffer2[FORMAT_BYTES_MAX], *buf; - - if (from != UINT64_MAX) - format_bytes(format_buffer1, sizeof(format_buffer1), from); - if (to != UINT64_MAX) - format_bytes(format_buffer2, sizeof(format_buffer2), to); + char *t; if (from != UINT64_MAX) { if (from == to || to == UINT64_MAX) - buf = strdup(format_buffer1); + t = strdup(FORMAT_BYTES(from)); else - buf = strjoin(format_buffer1, " ", special_glyph(SPECIAL_GLYPH_ARROW), " ", format_buffer2); + t = strjoin(FORMAT_BYTES(from), " ", special_glyph(SPECIAL_GLYPH_ARROW), " ", FORMAT_BYTES(to)); } else if (to != UINT64_MAX) - buf = strjoin(special_glyph(SPECIAL_GLYPH_ARROW), " ", format_buffer2); + t = strjoin(special_glyph(SPECIAL_GLYPH_ARROW), " ", FORMAT_BYTES(to)); else { *ret = NULL; return 0; } - if (!buf) + if (!t) return log_oom(); - *ret = TAKE_PTR(buf); + *ret = t; return 1; } @@ -2051,11 +2046,10 @@ static int context_dump_partitions(Context *context, const char *node) { } if ((arg_json_format_flags & JSON_FORMAT_OFF) && (sum_padding > 0 || sum_size > 0)) { - char s[FORMAT_BYTES_MAX]; const char *a, *b; - a = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", format_bytes(s, sizeof(s), sum_size)); - b = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", format_bytes(s, sizeof(s), sum_padding)); + a = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", FORMAT_BYTES(sum_size)); + b = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", FORMAT_BYTES(sum_padding)); r = table_add_many( t, @@ -2734,7 +2728,6 @@ static int context_copy_blocks(Context *context) { _cleanup_(loop_device_unrefp) LoopDevice *d = NULL; _cleanup_free_ char *encrypted = NULL; _cleanup_close_ int encrypted_dev_fd = -1; - char buf[FORMAT_BYTES_MAX]; int target_fd; if (p->copy_blocks_fd < 0) @@ -2777,7 +2770,8 @@ static int context_copy_blocks(Context *context) { target_fd = whole_fd; } - log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64 ".", p->copy_blocks_path, format_bytes(buf, sizeof(buf), p->copy_blocks_size), p->partno); + log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64 ".", + p->copy_blocks_path, FORMAT_BYTES(p->copy_blocks_size), p->partno); r = copy_bytes_full(p->copy_blocks_fd, target_fd, p->copy_blocks_size, 0, NULL, NULL, NULL, NULL); if (r < 0) @@ -4637,7 +4631,6 @@ static int resize_backing_fd( const char *backing_file, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */ LoopDevice *loop_device) { - char buf1[FORMAT_BYTES_MAX], buf2[FORMAT_BYTES_MAX]; _cleanup_close_ int writable_fd = -1; uint64_t current_size; struct stat st; @@ -4678,11 +4671,9 @@ static int resize_backing_fd( current_size = st.st_size; } - assert_se(format_bytes(buf1, sizeof(buf1), current_size)); - assert_se(format_bytes(buf2, sizeof(buf2), arg_size)); - if (current_size >= arg_size) { - log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", node, buf1, buf2); + log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", + node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size)); return 0; } @@ -4705,7 +4696,8 @@ static int resize_backing_fd( if ((uint64_t) st.st_size != current_size) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), - "Size of backing file '%s' of loopback block device '%s' don't match, refusing.", node, backing_file); + "Size of backing file '%s' of loopback block device '%s' don't match, refusing.", + node, backing_file); } else { assert(S_ISREG(st.st_mode)); assert(!backing_file); @@ -4723,15 +4715,16 @@ static int resize_backing_fd( if (fallocate(writable_fd, 0, 0, arg_size) < 0) { if (!ERRNO_IS_NOT_SUPPORTED(errno)) return log_error_errno(errno, "Failed to grow '%s' from %s to %s by allocation: %m", - node, buf1, buf2); + node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size)); /* Fallback to truncation, if fallocate() is not supported. */ log_debug("Backing file system does not support fallocate(), falling back to ftruncate()."); } else { if (current_size == 0) /* Likely regular file just created by us */ - log_info("Allocated %s for '%s'.", buf2, node); + log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size), node); else - log_info("File '%s' grown from %s to %s by allocation.", node, buf1, buf2); + log_info("File '%s' grown from %s to %s by allocation.", + node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size)); goto done; } @@ -4739,12 +4732,13 @@ static int resize_backing_fd( if (ftruncate(writable_fd, arg_size) < 0) return log_error_errno(errno, "Failed to grow '%s' from %s to %s by truncation: %m", - node, buf1, buf2); + node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size)); if (current_size == 0) /* Likely regular file just created by us */ - log_info("Sized '%s' to %s.", node, buf2); + log_info("Sized '%s' to %s.", node, FORMAT_BYTES(arg_size)); else - log_info("File '%s' grown from %s to %s by truncation.", node, buf1, buf2); + log_info("File '%s' grown from %s to %s by truncation.", + node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size)); done: r = resize_pt(writable_fd); @@ -4762,7 +4756,6 @@ done: static int determine_auto_size(Context *c) { uint64_t sum = round_up_size(GPT_METADATA_SIZE, 4096); - char buf[FORMAT_BYTES_MAX]; Partition *p; assert_se(c); @@ -4780,13 +4773,14 @@ static int determine_auto_size(Context *c) { sum += m; } - assert_se(format_bytes(buf, sizeof(buf), sum)); - if (c->total != UINT64_MAX) { /* Image already allocated? Then show its size */ - char buf2[FORMAT_BYTES_MAX]; - assert_se(format_bytes(buf2, sizeof(buf2), c->total)); - log_info("Automatically determined minimal disk image size as %s, current image size is %s.", buf, buf2); - } else /* If the image is being created right now, then it has no previous size, suppress any comment about it hence */ - log_info("Automatically determined minimal disk image size as %s.", buf); + if (c->total != UINT64_MAX) + /* Image already allocated? Then show its size. */ + log_info("Automatically determined minimal disk image size as %s, current image size is %s.", + FORMAT_BYTES(sum), FORMAT_BYTES(c->total)); + else + /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */ + log_info("Automatically determined minimal disk image size as %s.", + FORMAT_BYTES(sum)); arg_size = sum; return 0; @@ -4962,11 +4956,9 @@ static int run(int argc, char *argv[]) { break; /* Success! */ if (!context_drop_one_priority(context)) { - char buf[FORMAT_BYTES_MAX]; r = log_error_errno(SYNTHETIC_ERRNO(ENOSPC), "Can't fit requested partitions into available free space (%s), refusing.", - format_bytes(buf, sizeof(buf), largest_free_area)); - + FORMAT_BYTES(largest_free_area)); determine_auto_size(context); return r; } diff --git a/src/resolve/resolvectl.c b/src/resolve/resolvectl.c index 7d13ed3905..e9fb8b32fc 100644 --- a/src/resolve/resolvectl.c +++ b/src/resolve/resolvectl.c @@ -150,8 +150,6 @@ int ifname_resolvconf_mangle(const char *s) { } static void print_source(uint64_t flags, usec_t rtt) { - char rtt_str[FORMAT_TIMESTAMP_MAX]; - if (!arg_legend) return; @@ -167,11 +165,10 @@ static void print_source(uint64_t flags, usec_t rtt) { flags & SD_RESOLVED_MDNS_IPV4 ? " mDNS/IPv4" : "", flags & SD_RESOLVED_MDNS_IPV6 ? " mDNS/IPv6" : ""); - assert_se(format_timespan(rtt_str, sizeof(rtt_str), rtt, 100)); - printf(" in %s.%s\n" "%s-- Data is authenticated: %s; Data was acquired via local or encrypted transport: %s%s\n", - rtt_str, ansi_normal(), + FORMAT_TIMESPAN(rtt, 100), + ansi_normal(), ansi_grey(), yes_no(flags & SD_RESOLVED_AUTHENTICATED), yes_no(flags & SD_RESOLVED_CONFIDENTIAL), diff --git a/src/run/run.c b/src/run/run.c index 38de0322e0..344c8f6641 100644 --- a/src/run/run.c +++ b/src/run/run.c @@ -1322,34 +1322,25 @@ static int start_transient_service( if (timestamp_is_set(c.inactive_enter_usec) && timestamp_is_set(c.inactive_exit_usec) && - c.inactive_enter_usec > c.inactive_exit_usec) { - char ts[FORMAT_TIMESPAN_MAX]; + c.inactive_enter_usec > c.inactive_exit_usec) log_info("Service runtime: %s", - format_timespan(ts, sizeof ts, c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC)); - } + FORMAT_TIMESPAN(c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC)); - if (c.cpu_usage_nsec != NSEC_INFINITY) { - char ts[FORMAT_TIMESPAN_MAX]; + if (c.cpu_usage_nsec != NSEC_INFINITY) log_info("CPU time consumed: %s", - format_timespan(ts, sizeof ts, DIV_ROUND_UP(c.cpu_usage_nsec, NSEC_PER_USEC), USEC_PER_MSEC)); - } + FORMAT_TIMESPAN(DIV_ROUND_UP(c.cpu_usage_nsec, NSEC_PER_USEC), USEC_PER_MSEC)); - if (c.ip_ingress_bytes != UINT64_MAX) { - char bytes[FORMAT_BYTES_MAX]; - log_info("IP traffic received: %s", format_bytes(bytes, sizeof bytes, c.ip_ingress_bytes)); - } - if (c.ip_egress_bytes != UINT64_MAX) { - char bytes[FORMAT_BYTES_MAX]; - log_info("IP traffic sent: %s", format_bytes(bytes, sizeof bytes, c.ip_egress_bytes)); - } - if (c.io_read_bytes != UINT64_MAX) { - char bytes[FORMAT_BYTES_MAX]; - log_info("IO bytes read: %s", format_bytes(bytes, sizeof bytes, c.io_read_bytes)); - } - if (c.io_write_bytes != UINT64_MAX) { - char bytes[FORMAT_BYTES_MAX]; - log_info("IO bytes written: %s", format_bytes(bytes, sizeof bytes, c.io_write_bytes)); - } + if (c.ip_ingress_bytes != UINT64_MAX) + log_info("IP traffic received: %s", FORMAT_BYTES(c.ip_ingress_bytes)); + + if (c.ip_egress_bytes != UINT64_MAX) + log_info("IP traffic sent: %s", FORMAT_BYTES(c.ip_egress_bytes)); + + if (c.io_read_bytes != UINT64_MAX) + log_info("IO bytes read: %s", FORMAT_BYTES(c.io_read_bytes)); + + if (c.io_write_bytes != UINT64_MAX) + log_info("IO bytes written: %s", FORMAT_BYTES(c.io_write_bytes)); } /* Try to propagate the service's return value. But if the service defines diff --git a/src/shared/bus-print-properties.c b/src/shared/bus-print-properties.c index b45921943a..4e401180e9 100644 --- a/src/shared/bus-print-properties.c +++ b/src/shared/bus-print-properties.c @@ -105,20 +105,14 @@ static int bus_print_property(const char *name, const char *expected_value, sd_b * should it turn out to not be sufficient */ if (endswith(name, "Timestamp") || - STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) { - char timestamp[FORMAT_TIMESTAMP_MAX]; - const char *t; + STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) - t = format_timestamp(timestamp, sizeof(timestamp), u); - bus_print_property_value(name, expected_value, flags, t); + bus_print_property_value(name, expected_value, flags, FORMAT_TIMESTAMP(u)); - } else if (strstr(name, "USec")) { - char timespan[FORMAT_TIMESPAN_MAX]; + else if (strstr(name, "USec")) + bus_print_property_value(name, expected_value, flags, FORMAT_TIMESPAN(u, 0)); - (void) format_timespan(timespan, sizeof(timespan), u, 0); - bus_print_property_value(name, expected_value, flags, timespan); - - } else if (streq(name, "CoredumpFilter")) + else if (streq(name, "CoredumpFilter")) bus_print_property_valuef(name, expected_value, flags, "0x%"PRIx64, u); else if (streq(name, "RestrictNamespaces")) { diff --git a/src/shared/dissect-image.c b/src/shared/dissect-image.c index c6542cec70..27b9ac9569 100644 --- a/src/shared/dissect-image.c +++ b/src/shared/dissect-image.c @@ -506,12 +506,11 @@ static int device_wait_for_initialization_harder( left = usec_sub_unsigned(deadline, start); if (DEBUG_LOGGING) { - char buf[FORMAT_TIMESPAN_MAX]; const char *sn = NULL; (void) sd_device_get_sysname(device, &sn); log_device_debug(device, - "Waiting for device '%s' to initialize for %s.", strna(sn), format_timespan(buf, sizeof(buf), left, 0)); + "Waiting for device '%s' to initialize for %s.", strna(sn), FORMAT_TIMESPAN(left, 0)); } if (left != USEC_INFINITY) @@ -538,26 +537,22 @@ static int device_wait_for_initialization_harder( r = device_wait_for_initialization(device, subsystem, local_deadline, ret); if (r >= 0 && DEBUG_LOGGING) { - char buf[FORMAT_TIMESPAN_MAX]; const char *sn = NULL; (void) sd_device_get_sysname(device, &sn); log_device_debug(device, "Successfully waited for device '%s' to initialize for %s.", strna(sn), - format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0)); + FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0)); } if (r != -ETIMEDOUT || last_try) return r; - if (DEBUG_LOGGING) { - char buf[FORMAT_TIMESPAN_MAX]; - + if (DEBUG_LOGGING) log_device_debug(device, "Device didn't initialize within %s, assuming lost event. Retriggering device.", - format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0)); - } + FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0)); r = sd_device_trigger(device, SD_DEVICE_CHANGE); if (r < 0) @@ -1497,7 +1492,6 @@ static int run_fsck(const char *node, const char *fstype) { static int fs_grow(const char *node_path, const char *mount_path) { _cleanup_close_ int mount_fd = -1, node_fd = -1; - char fb[FORMAT_BYTES_MAX]; uint64_t size, newsize; int r; @@ -1519,14 +1513,11 @@ static int fs_grow(const char *node_path, const char *mount_path) { if (newsize == size) log_debug("Successfully resized \"%s\" to %s bytes.", - mount_path, - format_bytes(fb, sizeof fb, newsize)); + mount_path, FORMAT_BYTES(newsize)); else { assert(newsize < size); log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).", - mount_path, - format_bytes(fb, sizeof fb, newsize), - size - newsize); + mount_path, FORMAT_BYTES(newsize), size - newsize); } return 0; diff --git a/src/shared/format-table.c b/src/shared/format-table.c index b298019d7c..6dca6661e1 100644 --- a/src/shared/format-table.c +++ b/src/shared/format-table.c @@ -1441,7 +1441,7 @@ static const char *table_data_format(Table *t, TableData *d, bool avoid_uppercas _cleanup_free_ char *p = NULL; char *ret; - p = new(char, FORMAT_TIMESTAMP_MAX); + p = new(char, d->type == TABLE_TIMESTAMP_RELATIVE ? FORMAT_TIMESTAMP_RELATIVE_MAX : FORMAT_TIMESTAMP_MAX); if (!p) return NULL; @@ -1450,7 +1450,7 @@ static const char *table_data_format(Table *t, TableData *d, bool avoid_uppercas else if (d->type == TABLE_TIMESTAMP_UTC) ret = format_timestamp_style(p, FORMAT_TIMESTAMP_MAX, d->timestamp, TIMESTAMP_UTC); else - ret = format_timestamp_relative(p, FORMAT_TIMESTAMP_MAX, d->timestamp); + ret = format_timestamp_relative(p, FORMAT_TIMESTAMP_RELATIVE_MAX, d->timestamp); if (!ret) return "n/a"; diff --git a/src/shared/killall.c b/src/shared/killall.c index d9fcfc21a9..869955a58f 100644 --- a/src/shared/killall.c +++ b/src/shared/killall.c @@ -17,6 +17,7 @@ #include "parse-util.h" #include "process-util.h" #include "set.h" +#include "stdio-util.h" #include "string-util.h" #include "terminal-util.h" #include "util.h" @@ -83,14 +84,13 @@ static void log_children_no_yet_killed(Set *pids) { SET_FOREACH(p, pids) { _cleanup_free_ char *s = NULL; + char fallback[DECIMAL_STR_MAX(pid_t)]; if (get_process_comm(PTR_TO_PID(p), &s) < 0) - (void) asprintf(&s, PID_FMT, PTR_TO_PID(p)); + xsprintf(fallback, PID_FMT, PTR_TO_PID(p)); - if (!strextend(&lst_child, ", ", s)) { - log_oom(); - return; - } + if (!strextend(&lst_child, ", ", s ?: fallback)) + return (void) log_oom(); } if (isempty(lst_child)) diff --git a/src/shared/logs-show.c b/src/shared/logs-show.c index e63c59bd94..3165cf29da 100644 --- a/src/shared/logs-show.c +++ b/src/shared/logs-show.c @@ -579,10 +579,9 @@ static int output_short( } } - if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len)) { - char bytes[FORMAT_BYTES_MAX]; - fprintf(f, "[%s blob data]\n", format_bytes(bytes, sizeof(bytes), message_len)); - } else { + if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len)) + fprintf(f, "[%s blob data]\n", FORMAT_BYTES(message_len)); + else { /* URLify config_file string in message, if the message starts with it. * Skip URLification if the highlighted pattern overlaps. */ @@ -726,16 +725,13 @@ static int output_verbose( p, valuelen, NULL); fputs(off, f); - } else { - char bytes[FORMAT_BYTES_MAX]; - + } else fprintf(f, " %s%.*s=[%s blob data]%s\n", on, (int) (c - (const char*) data), (const char*) data, - format_bytes(bytes, sizeof(bytes), length - (c - (const char *) data) - 1), + FORMAT_BYTES(length - (c - (const char *) data) - 1), off); - } } if (r < 0) diff --git a/src/shared/mount-setup.c b/src/shared/mount-setup.c index ef3527e9a7..3b30982835 100644 --- a/src/shared/mount-setup.c +++ b/src/shared/mount-setup.c @@ -499,7 +499,6 @@ int mount_setup(bool loaded_policy, bool leave_propagation) { * use the same label for all their files. */ if (loaded_policy) { usec_t before_relabel, after_relabel; - char timespan[FORMAT_TIMESPAN_MAX]; const char *i; int n_extra; @@ -516,7 +515,7 @@ int mount_setup(bool loaded_policy, bool leave_propagation) { log_info("Relabelled /dev, /dev/shm, /run, /sys/fs/cgroup%s in %s.", n_extra > 0 ? ", additional files" : "", - format_timespan(timespan, sizeof(timespan), after_relabel - before_relabel, 0)); + FORMAT_TIMESPAN(after_relabel - before_relabel, 0)); } #endif diff --git a/src/shared/selinux-util.c b/src/shared/selinux-util.c index 03cee76f64..e4890e8170 100644 --- a/src/shared/selinux-util.c +++ b/src/shared/selinux-util.c @@ -115,7 +115,6 @@ REENABLE_WARNING static int open_label_db(void) { struct selabel_handle *hnd; usec_t before_timestamp, after_timestamp; - char timespan[FORMAT_TIMESPAN_MAX]; # if HAVE_GENERIC_MALLINFO generic_mallinfo before_mallinfo = generic_mallinfo_get(); @@ -131,11 +130,11 @@ static int open_label_db(void) { generic_mallinfo after_mallinfo = generic_mallinfo_get(); size_t l = LESS_BY((size_t) after_mallinfo.uordblks, (size_t) before_mallinfo.uordblks); log_debug("Successfully loaded SELinux database in %s, size on heap is %zuK.", - format_timespan(timespan, sizeof(timespan), after_timestamp - before_timestamp, 0), + FORMAT_TIMESPAN(after_timestamp - before_timestamp, 0), DIV_ROUND_UP(l, 1024)); # else log_debug("Successfully loaded SELinux database in %s.", - format_timespan(timespan, sizeof(timespan), after_timestamp - before_timestamp, 0)); + FORMAT_TIMESPAN(after_timestamp - before_timestamp, 0)); # endif /* release memory after measurement */ diff --git a/src/shared/tpm2-util.c b/src/shared/tpm2-util.c index df6d2eef58..79e879b482 100644 --- a/src/shared/tpm2-util.c +++ b/src/shared/tpm2-util.c @@ -591,10 +591,8 @@ int tpm2_seal( if (!hash) return log_oom(); - if (DEBUG_LOGGING) { - char buf[FORMAT_TIMESPAN_MAX]; - log_debug("Completed TPM2 key sealing in %s.", format_timespan(buf, sizeof(buf), now(CLOCK_MONOTONIC) - start, 1)); - } + if (DEBUG_LOGGING) + log_debug("Completed TPM2 key sealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1)); *ret_secret = TAKE_PTR(secret); *ret_secret_size = hmac_sensitive.sensitive.data.size; @@ -726,10 +724,8 @@ int tpm2_unseal( goto finish; } - if (DEBUG_LOGGING) { - char buf[FORMAT_TIMESPAN_MAX]; - log_debug("Completed TPM2 key unsealing in %s.", format_timespan(buf, sizeof(buf), now(CLOCK_MONOTONIC) - start, 1)); - } + if (DEBUG_LOGGING) + log_debug("Completed TPM2 key unsealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1)); *ret_secret = TAKE_PTR(secret); *ret_secret_size = unsealed->size; diff --git a/src/shared/user-record-show.c b/src/shared/user-record-show.c index 29790282b4..29aa5c0c7c 100644 --- a/src/shared/user-record-show.c +++ b/src/shared/user-record-show.c @@ -43,8 +43,7 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { printf(" Disposition: %s\n", user_disposition_to_string(user_record_disposition(hr))); if (hr->last_change_usec != USEC_INFINITY) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Last Change: %s\n", format_timestamp(buf, sizeof(buf), hr->last_change_usec)); + printf(" Last Change: %s\n", FORMAT_TIMESTAMP(hr->last_change_usec)); if (hr->last_change_usec > now(CLOCK_REALTIME)) printf(" %sModification time lies in the future, system clock wrong?%s\n", @@ -52,10 +51,8 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { } if (hr->last_password_change_usec != USEC_INFINITY && - hr->last_password_change_usec != hr->last_change_usec) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Last Passw.: %s\n", format_timestamp(buf, sizeof(buf), hr->last_password_change_usec)); - } + hr->last_password_change_usec != hr->last_change_usec) + printf(" Last Passw.: %s\n", FORMAT_TIMESTAMP(hr->last_password_change_usec)); r = user_record_test_blocked(hr); switch (r) { @@ -238,15 +235,11 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { if (hr->locked >= 0) printf(" Locked: %s\n", yes_no(hr->locked)); - if (hr->not_before_usec != UINT64_MAX) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Not Before: %s\n", format_timestamp(buf, sizeof(buf), hr->not_before_usec)); - } + if (hr->not_before_usec != UINT64_MAX) + printf(" Not Before: %s\n", FORMAT_TIMESTAMP(hr->not_before_usec)); - if (hr->not_after_usec != UINT64_MAX) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Not After: %s\n", format_timestamp(buf, sizeof(buf), hr->not_after_usec)); - } + if (hr->not_after_usec != UINT64_MAX) + printf(" Not After: %s\n", FORMAT_TIMESTAMP(hr->not_after_usec)); if (hr->umask != MODE_INVALID) printf(" UMask: 0%03o\n", hr->umask); @@ -263,15 +256,11 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { if (hr->tasks_max != UINT64_MAX) printf(" Tasks Max: %" PRIu64 "\n", hr->tasks_max); - if (hr->memory_high != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - printf(" Memory High: %s\n", format_bytes(buf, sizeof(buf), hr->memory_high)); - } + if (hr->memory_high != UINT64_MAX) + printf(" Memory High: %s\n", FORMAT_BYTES(hr->memory_high)); - if (hr->memory_max != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - printf(" Memory Max: %s\n", format_bytes(buf, sizeof(buf), hr->memory_max)); - } + if (hr->memory_max != UINT64_MAX) + printf(" Memory Max: %s\n", FORMAT_BYTES(hr->memory_max)); if (hr->cpu_weight != UINT64_MAX) printf(" CPU Weight: %" PRIu64 "\n", hr->cpu_weight); @@ -306,14 +295,11 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { printf(" PBKDF Type: %s\n", hr->luks_pbkdf_type); if (hr->luks_pbkdf_hash_algorithm) printf(" PBKDF Hash: %s\n", hr->luks_pbkdf_hash_algorithm); - if (hr->luks_pbkdf_time_cost_usec != UINT64_MAX) { - char buf[FORMAT_TIMESPAN_MAX]; - printf(" PBKDF Time: %s\n", format_timespan(buf, sizeof(buf), hr->luks_pbkdf_time_cost_usec, 0)); - } - if (hr->luks_pbkdf_memory_cost != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - printf(" PBKDF Bytes: %s\n", format_bytes(buf, sizeof(buf), hr->luks_pbkdf_memory_cost)); - } + if (hr->luks_pbkdf_time_cost_usec != UINT64_MAX) + printf(" PBKDF Time: %s\n", FORMAT_TIMESPAN(hr->luks_pbkdf_time_cost_usec, 0)); + if (hr->luks_pbkdf_memory_cost != UINT64_MAX) + printf(" PBKDF Bytes: %s\n", FORMAT_BYTES(hr->luks_pbkdf_memory_cost)); + if (hr->luks_pbkdf_parallel_threads != UINT64_MAX) printf("PBKDF Thread: %" PRIu64 "\n", hr->luks_pbkdf_parallel_threads); @@ -337,28 +323,22 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { if (hr->skeleton_directory) printf(" Skel. Dir.: %s\n", user_record_skeleton_directory(hr)); - if (hr->disk_size != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - printf(" Disk Size: %s\n", format_bytes(buf, sizeof(buf), hr->disk_size)); - } + if (hr->disk_size != UINT64_MAX) + printf(" Disk Size: %s\n", FORMAT_BYTES(hr->disk_size)); if (hr->disk_usage != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - if (hr->disk_size != UINT64_MAX) { unsigned permille; permille = (unsigned) DIV_ROUND_UP(hr->disk_usage * 1000U, hr->disk_size); /* Round up! */ printf(" Disk Usage: %s (= %u.%01u%%)\n", - format_bytes(buf, sizeof(buf), hr->disk_usage), + FORMAT_BYTES(hr->disk_usage), permille / 10, permille % 10); } else - printf(" Disk Usage: %s\n", format_bytes(buf, sizeof(buf), hr->disk_usage)); + printf(" Disk Usage: %s\n", FORMAT_BYTES(hr->disk_usage)); } if (hr->disk_free != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - if (hr->disk_size != UINT64_MAX) { const char *color_on, *color_off; unsigned permille; @@ -381,38 +361,30 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { printf(" Disk Free: %s%s (= %u.%01u%%)%s\n", color_on, - format_bytes(buf, sizeof(buf), hr->disk_free), + FORMAT_BYTES(hr->disk_free), permille / 10, permille % 10, color_off); } else - printf(" Disk Free: %s\n", format_bytes(buf, sizeof(buf), hr->disk_free)); + printf(" Disk Free: %s\n", FORMAT_BYTES(hr->disk_free)); } - if (hr->disk_floor != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - printf(" Disk Floor: %s\n", format_bytes(buf, sizeof(buf), hr->disk_floor)); - } + if (hr->disk_floor != UINT64_MAX) + printf(" Disk Floor: %s\n", FORMAT_BYTES(hr->disk_floor)); - if (hr->disk_ceiling != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - printf("Disk Ceiling: %s\n", format_bytes(buf, sizeof(buf), hr->disk_ceiling)); - } + if (hr->disk_ceiling != UINT64_MAX) + printf("Disk Ceiling: %s\n", FORMAT_BYTES(hr->disk_ceiling)); if (hr->good_authentication_counter != UINT64_MAX) printf(" Good Auth.: %" PRIu64 "\n", hr->good_authentication_counter); - if (hr->last_good_authentication_usec != UINT64_MAX) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Last Good: %s\n", format_timestamp(buf, sizeof(buf), hr->last_good_authentication_usec)); - } + if (hr->last_good_authentication_usec != UINT64_MAX) + printf(" Last Good: %s\n", FORMAT_TIMESTAMP(hr->last_good_authentication_usec)); if (hr->bad_authentication_counter != UINT64_MAX) printf(" Bad Auth.: %" PRIu64 "\n", hr->bad_authentication_counter); - if (hr->last_bad_authentication_usec != UINT64_MAX) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Last Bad: %s\n", format_timestamp(buf, sizeof(buf), hr->last_bad_authentication_usec)); - } + if (hr->last_bad_authentication_usec != UINT64_MAX) + printf(" Last Bad: %s\n", FORMAT_TIMESTAMP(hr->last_bad_authentication_usec)); t = user_record_ratelimit_next_try(hr); if (t != USEC_INFINITY) { @@ -420,20 +392,16 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { if (t <= n) printf(" Next Try: anytime\n"); - else { - char buf[FORMAT_TIMESPAN_MAX]; + else printf(" Next Try: %sin %s%s\n", ansi_highlight_red(), - format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC), + FORMAT_TIMESPAN(t - n, USEC_PER_SEC), ansi_normal()); - } } - if (storage != USER_CLASSIC) { - char buf[FORMAT_TIMESPAN_MAX]; + if (storage != USER_CLASSIC) printf(" Auth. Limit: %" PRIu64 " attempts per %s\n", user_record_ratelimit_burst(hr), - format_timespan(buf, sizeof(buf), user_record_ratelimit_interval_usec(hr), 0)); - } + FORMAT_TIMESPAN(user_record_ratelimit_interval_usec(hr), 0)); if (hr->enforce_password_policy >= 0) printf(" Passwd Pol.: %s\n", yes_no(hr->enforce_password_policy)); @@ -443,24 +411,23 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { hr->password_change_warn_usec != UINT64_MAX || hr->password_change_inactive_usec != UINT64_MAX) { - char buf[FORMAT_TIMESPAN_MAX]; printf(" Passwd Chg.:"); if (hr->password_change_min_usec != UINT64_MAX) { - printf(" min %s", format_timespan(buf, sizeof(buf), hr->password_change_min_usec, 0)); + printf(" min %s", FORMAT_TIMESPAN(hr->password_change_min_usec, 0)); if (hr->password_change_max_usec != UINT64_MAX) printf(" …"); } if (hr->password_change_max_usec != UINT64_MAX) - printf(" max %s", format_timespan(buf, sizeof(buf), hr->password_change_max_usec, 0)); + printf(" max %s", FORMAT_TIMESPAN(hr->password_change_max_usec, 0)); if (hr->password_change_warn_usec != UINT64_MAX) - printf("/warn %s", format_timespan(buf, sizeof(buf), hr->password_change_warn_usec, 0)); + printf("/warn %s", FORMAT_TIMESPAN(hr->password_change_warn_usec, 0)); if (hr->password_change_inactive_usec != UINT64_MAX) - printf("/inactive %s", format_timespan(buf, sizeof(buf), hr->password_change_inactive_usec, 0)); + printf("/inactive %s", FORMAT_TIMESPAN(hr->password_change_inactive_usec, 0)); printf("\n"); } @@ -496,10 +463,8 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) { if (hr->signed_locally >= 0) printf(" Local Sig.: %s\n", yes_no(hr->signed_locally)); - if (hr->stop_delay_usec != UINT64_MAX) { - char buf[FORMAT_TIMESPAN_MAX]; - printf(" Stop Delay: %s\n", format_timespan(buf, sizeof(buf), hr->stop_delay_usec, 0)); - } + if (hr->stop_delay_usec != UINT64_MAX) + printf(" Stop Delay: %s\n", FORMAT_TIMESPAN(hr->stop_delay_usec, 0)); if (hr->auto_login >= 0) printf("Autom. Login: %s\n", yes_no(hr->auto_login)); @@ -519,10 +484,8 @@ void group_record_show(GroupRecord *gr, bool show_full_user_info) { printf(" Disposition: %s\n", user_disposition_to_string(group_record_disposition(gr))); - if (gr->last_change_usec != USEC_INFINITY) { - char buf[FORMAT_TIMESTAMP_MAX]; - printf(" Last Change: %s\n", format_timestamp(buf, sizeof(buf), gr->last_change_usec)); - } + if (gr->last_change_usec != USEC_INFINITY) + printf(" Last Change: %s\n", FORMAT_TIMESTAMP(gr->last_change_usec)); if (gid_is_valid(gr->gid)) printf(" GID: " GID_FMT "\n", gr->gid); diff --git a/src/shared/utmp-wtmp.c b/src/shared/utmp-wtmp.c index 3eeee24693..b31cdd679b 100644 --- a/src/shared/utmp-wtmp.c +++ b/src/shared/utmp-wtmp.c @@ -340,7 +340,6 @@ int utmp_wall( void *userdata) { _cleanup_free_ char *text = NULL, *hn = NULL, *un = NULL, *stdin_tty = NULL; - char date[FORMAT_TIMESTAMP_MAX]; struct utmpx *u; int r; @@ -364,7 +363,7 @@ int utmp_wall( "%s\r\n\r\n", un ?: username, hn, origin_tty ? " on " : "", strempty(origin_tty), - format_timestamp(date, sizeof(date), now(CLOCK_REALTIME)), + FORMAT_TIMESTAMP(now(CLOCK_REALTIME)), message) < 0) return -ENOMEM; diff --git a/src/shared/varlink.c b/src/shared/varlink.c index 6b0b343ae9..3a53c16a72 100644 --- a/src/shared/varlink.c +++ b/src/shared/varlink.c @@ -2145,7 +2145,9 @@ int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) v->ucred_acquired = true; } - (void) asprintf(&v->description, "%s-%i", server->description ?: "varlink", v->fd); + _cleanup_free_ char *desc = NULL; + if (asprintf(&desc, "%s-%i", server->description ?: "varlink", v->fd) >= 0) + v->description = TAKE_PTR(desc); /* Link up the server and the connection, and take reference in both directions. Note that the * reference on the connection is left dangling. It will be dropped when the connection is closed, diff --git a/src/shared/watchdog.c b/src/shared/watchdog.c index d33acafe64..361d5837dc 100644 --- a/src/shared/watchdog.c +++ b/src/shared/watchdog.c @@ -32,7 +32,6 @@ static int update_timeout(void) { if (ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags) < 0) return log_warning_errno(errno, "Failed to disable hardware watchdog: %m"); } else { - char buf[FORMAT_TIMESPAN_MAX]; int sec, flags; usec_t t; @@ -41,8 +40,7 @@ static int update_timeout(void) { if (ioctl(watchdog_fd, WDIOC_SETTIMEOUT, &sec) < 0) return log_warning_errno(errno, "Failed to set timeout to %is: %m", sec); - watchdog_timeout = (usec_t) sec * USEC_PER_SEC; - log_info("Set hardware watchdog to %s.", format_timespan(buf, sizeof(buf), watchdog_timeout, 0)); + log_info("Set hardware watchdog to %s.", FORMAT_TIMESPAN(sec * USEC_PER_SEC, 0)); flags = WDIOS_ENABLECARD; if (ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags) < 0) { diff --git a/src/sleep/sleep.c b/src/sleep/sleep.c index a3aeb24633..19c99db1b4 100644 --- a/src/sleep/sleep.c +++ b/src/sleep/sleep.c @@ -266,7 +266,6 @@ static int execute( static int execute_s2h(const SleepConfig *sleep_config) { _cleanup_close_ int tfd = -1; - char buf[FORMAT_TIMESPAN_MAX]; struct itimerspec ts = {}; int r; @@ -277,7 +276,7 @@ static int execute_s2h(const SleepConfig *sleep_config) { return log_error_errno(errno, "Error creating timerfd: %m"); log_debug("Set timerfd wake alarm for %s", - format_timespan(buf, sizeof(buf), sleep_config->hibernate_delay_sec, USEC_PER_SEC)); + FORMAT_TIMESPAN(sleep_config->hibernate_delay_sec, USEC_PER_SEC)); timespec_store(&ts.it_value, sleep_config->hibernate_delay_sec); @@ -299,7 +298,7 @@ static int execute_s2h(const SleepConfig *sleep_config) { /* If woken up after alarm time, hibernate */ log_debug("Attempting to hibernate after waking from %s timer", - format_timespan(buf, sizeof(buf), sleep_config->hibernate_delay_sec, USEC_PER_SEC)); + FORMAT_TIMESPAN(sleep_config->hibernate_delay_sec, USEC_PER_SEC)); r = execute(sleep_config, SLEEP_HIBERNATE, NULL); if (r < 0) { diff --git a/src/systemctl/systemctl-logind.c b/src/systemctl/systemctl-logind.c index 28dd25b523..b1c0e13f2c 100644 --- a/src/systemctl/systemctl-logind.c +++ b/src/systemctl/systemctl-logind.c @@ -296,7 +296,6 @@ int logind_schedule_shutdown(void) { #if ENABLE_LOGIND _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - char date[FORMAT_TIMESTAMP_MAX]; const char *action; const char *log_action; sd_bus *bus; @@ -340,7 +339,9 @@ int logind_schedule_shutdown(void) { return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r)); if (!arg_quiet) - log_info("%s scheduled for %s, use 'shutdown -c' to cancel.", log_action, format_timestamp_style(date, sizeof(date), arg_when, arg_timestamp_style)); + log_info("%s scheduled for %s, use 'shutdown -c' to cancel.", + log_action, + FORMAT_TIMESTAMP_STYLE(arg_when, arg_timestamp_style)); return 0; #else return log_error_errno(SYNTHETIC_ERRNO(ENOSYS), diff --git a/src/systemctl/systemctl-show.c b/src/systemctl/systemctl-show.c index 1f524626bf..2c60be40c9 100644 --- a/src/systemctl/systemctl-show.c +++ b/src/systemctl/systemctl-show.c @@ -300,7 +300,6 @@ static void print_status_info( UnitStatusInfo *i, bool *ellipsized) { - char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX]; const char *s1, *s2, *active_on, *active_off, *on, *off, *ss, *fs; _cleanup_free_ char *formatted_path = NULL; ExecStatusInfo *p; @@ -419,9 +418,8 @@ static void print_status_info( STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp : i->active_exit_timestamp; - s1 = format_timestamp_relative(since1, sizeof(since1), timestamp); - s2 = format_timestamp_style(since2, sizeof(since2), timestamp, arg_timestamp_style); - + s1 = FORMAT_TIMESTAMP_RELATIVE(timestamp); + s2 = FORMAT_TIMESTAMP_STYLE(timestamp, arg_timestamp_style); if (s1) printf(" since %s; %s\n", s2, s1); else if (s2) @@ -442,24 +440,18 @@ static void print_status_info( } if (endswith(i->id, ".timer")) { - char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX], - tstamp2[FORMAT_TIMESTAMP_MAX]; - const char *next_rel_time, *next_time; - dual_timestamp nw, next = {i->next_elapse_real, - i->next_elapse_monotonic}; + const char *next_time; + dual_timestamp nw, next = {i->next_elapse_real, i->next_elapse_monotonic}; usec_t next_elapse; - printf(" Trigger: "); - dual_timestamp_get(&nw); next_elapse = calc_next_elapse(&nw, &next); - next_rel_time = format_timestamp_relative(tstamp1, sizeof tstamp1, next_elapse); - next_time = format_timestamp_style(tstamp2, sizeof tstamp2, next_elapse, arg_timestamp_style); + next_time = FORMAT_TIMESTAMP_STYLE(next_elapse, arg_timestamp_style); - if (next_time && next_rel_time) - printf("%s; %s\n", next_time, next_rel_time); - else - printf("n/a\n"); + printf(" Trigger: %s%s%s\n", + strna(next_time), + next_time ? "; " : "", + next_time ? strna(FORMAT_TIMESTAMP_RELATIVE(next_elapse)) : ""); } STRV_FOREACH(t, i->triggers) { @@ -477,13 +469,13 @@ static void print_status_info( if (!i->condition_result && i->condition_timestamp > 0) { UnitCondition *c; int n = 0; + const char *rel; - s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp); - s2 = format_timestamp_style(since2, sizeof(since2), i->condition_timestamp, arg_timestamp_style); - + rel = FORMAT_TIMESTAMP_RELATIVE(i->condition_timestamp); printf(" Condition: start %scondition failed%s at %s%s%s\n", ansi_highlight_yellow(), ansi_normal(), - s2, s1 ? "; " : "", strempty(s1)); + FORMAT_TIMESTAMP_STYLE(i->condition_timestamp, arg_timestamp_style), + rel ? "; " : "", strempty(rel)); LIST_FOREACH(conditions, c, i->conditions) if (c->tristate < 0) @@ -500,12 +492,13 @@ static void print_status_info( } if (!i->assert_result && i->assert_timestamp > 0) { - s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp); - s2 = format_timestamp_style(since2, sizeof(since2), i->assert_timestamp, arg_timestamp_style); + const char *rel; + rel = FORMAT_TIMESTAMP_RELATIVE(i->assert_timestamp); printf(" Assert: start %sassertion failed%s at %s%s%s\n", ansi_highlight_red(), ansi_normal(), - s2, s1 ? "; " : "", strempty(s1)); + FORMAT_TIMESTAMP_STYLE(i->assert_timestamp, arg_timestamp_style), + rel ? "; " : "", strempty(rel)); if (i->failed_assert_trigger) printf(" none of the trigger assertions were met\n"); else if (i->failed_assert) @@ -651,21 +644,15 @@ static void print_status_info( if (i->status_errno > 0) printf(" Error: %i (%s)\n", i->status_errno, strerror_safe(i->status_errno)); - if (i->ip_ingress_bytes != UINT64_MAX && i->ip_egress_bytes != UINT64_MAX) { - char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX]; - + if (i->ip_ingress_bytes != UINT64_MAX && i->ip_egress_bytes != UINT64_MAX) printf(" IP: %s in, %s out\n", - format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes), - format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes)); - } - - if (i->io_read_bytes != UINT64_MAX && i->io_write_bytes != UINT64_MAX) { - char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX]; + FORMAT_BYTES(i->ip_ingress_bytes), + FORMAT_BYTES(i->ip_egress_bytes)); + if (i->io_read_bytes != UINT64_MAX && i->io_write_bytes != UINT64_MAX) printf(" IO: %s read, %s written\n", - format_bytes(buf_in, sizeof(buf_in), i->io_read_bytes), - format_bytes(buf_out, sizeof(buf_out), i->io_write_bytes)); - } + FORMAT_BYTES(i->io_read_bytes), + FORMAT_BYTES(i->io_write_bytes)); if (i->tasks_current != UINT64_MAX) { printf(" Tasks: %" PRIu64, i->tasks_current); @@ -677,9 +664,7 @@ static void print_status_info( } if (i->memory_current != UINT64_MAX) { - char buf[FORMAT_BYTES_MAX]; - - printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current)); + printf(" Memory: %s", FORMAT_BYTES(i->memory_current)); if (i->memory_min > 0 || i->memory_low > 0 || i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX || @@ -690,31 +675,31 @@ static void print_status_info( printf(" ("); if (i->memory_min > 0) { - printf("%smin: %s", prefix, format_bytes_cgroup_protection(buf, sizeof(buf), i->memory_min)); + printf("%smin: %s", prefix, FORMAT_BYTES_CGROUP_PROTECTION(i->memory_min)); prefix = " "; } if (i->memory_low > 0) { - printf("%slow: %s", prefix, format_bytes_cgroup_protection(buf, sizeof(buf), i->memory_low)); + printf("%slow: %s", prefix, FORMAT_BYTES_CGROUP_PROTECTION(i->memory_low)); prefix = " "; } if (i->memory_high != CGROUP_LIMIT_MAX) { - printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high)); + printf("%shigh: %s", prefix, FORMAT_BYTES(i->memory_high)); prefix = " "; } if (i->memory_max != CGROUP_LIMIT_MAX) { - printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max)); + printf("%smax: %s", prefix, FORMAT_BYTES(i->memory_max)); prefix = " "; } if (i->memory_swap_max != CGROUP_LIMIT_MAX) { - printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max)); + printf("%sswap max: %s", prefix, FORMAT_BYTES(i->memory_swap_max)); prefix = " "; } if (i->memory_limit != CGROUP_LIMIT_MAX) { - printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit)); + printf("%slimit: %s", prefix, FORMAT_BYTES(i->memory_limit)); prefix = " "; } if (i->memory_available != CGROUP_LIMIT_MAX) { - printf("%savailable: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_available)); + printf("%savailable: %s", prefix, FORMAT_BYTES(i->memory_available)); prefix = " "; } printf(")"); @@ -722,10 +707,8 @@ static void print_status_info( printf("\n"); } - if (i->cpu_usage_nsec != UINT64_MAX) { - char buf[FORMAT_TIMESPAN_MAX]; - printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC)); - } + if (i->cpu_usage_nsec != UINT64_MAX) + printf(" CPU: %s\n", FORMAT_TIMESPAN(i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC)); if (i->control_group) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; @@ -1235,15 +1218,12 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m if (r < 0) return bus_log_parse_error(r); - while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) { - char timespan1[FORMAT_TIMESPAN_MAX] = "n/a", timespan2[FORMAT_TIMESPAN_MAX] = "n/a"; - - (void) format_timespan(timespan1, sizeof timespan1, v, 0); - (void) format_timespan(timespan2, sizeof timespan2, next_elapse, 0); - + while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) bus_print_property_valuef(name, expected_value, flags, - "{ %s=%s ; next_elapse=%s }", base, timespan1, timespan2); - } + "{ %s=%s ; next_elapse=%s }", + base, + strna(FORMAT_TIMESPAN(v, 0)), + strna(FORMAT_TIMESPAN(next_elapse, 0))); if (r < 0) return bus_log_parse_error(r); @@ -1261,13 +1241,10 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m if (r < 0) return bus_log_parse_error(r); - while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) { - char timestamp[FORMAT_TIMESTAMP_MAX] = "n/a"; - - (void) format_timestamp_style(timestamp, sizeof(timestamp), next_elapse, arg_timestamp_style); + while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) bus_print_property_valuef(name, expected_value, flags, - "{ %s=%s ; next_elapse=%s }", base, spec, timestamp); - } + "{ %s=%s ; next_elapse=%s }", base, spec, + FORMAT_TIMESTAMP_STYLE(next_elapse, arg_timestamp_style)); if (r < 0) return bus_log_parse_error(r); @@ -1286,7 +1263,6 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m return bus_log_parse_error(r); while ((r = exec_status_info_deserialize(m, &info, is_ex_prop)) > 0) { - char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX]; _cleanup_strv_free_ char **optv = NULL; _cleanup_free_ char *tt = NULL, *o = NULL; @@ -1304,8 +1280,8 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m strna(info.path), strna(tt), strna(o), - strna(format_timestamp_style(timestamp1, sizeof(timestamp1), info.start_timestamp, arg_timestamp_style)), - strna(format_timestamp_style(timestamp2, sizeof(timestamp2), info.exit_timestamp, arg_timestamp_style)), + strna(FORMAT_TIMESTAMP_STYLE(info.start_timestamp, arg_timestamp_style)), + strna(FORMAT_TIMESTAMP_STYLE(info.exit_timestamp, arg_timestamp_style)), info.pid, sigchld_code_to_string(info.code), info.status, @@ -1317,8 +1293,8 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m strna(info.path), strna(tt), yes_no(info.ignore), - strna(format_timestamp_style(timestamp1, sizeof(timestamp1), info.start_timestamp, arg_timestamp_style)), - strna(format_timestamp_style(timestamp2, sizeof(timestamp2), info.exit_timestamp, arg_timestamp_style)), + strna(FORMAT_TIMESTAMP_STYLE(info.start_timestamp, arg_timestamp_style)), + strna(FORMAT_TIMESTAMP_STYLE(info.exit_timestamp, arg_timestamp_style)), info.pid, sigchld_code_to_string(info.code), info.status, @@ -1397,7 +1373,6 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "IODeviceLatencyTargetUSec")) { - char ts[FORMAT_TIMESPAN_MAX]; const char *path; uint64_t target; @@ -1407,7 +1382,7 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0) bus_print_property_valuef(name, expected_value, flags, "%s %s", strna(path), - format_timespan(ts, sizeof(ts), target, 1)); + FORMAT_TIMESPAN(target, 1)); if (r < 0) return bus_log_parse_error(r); @@ -2021,7 +1996,6 @@ static int show_all( } static int show_system_status(sd_bus *bus) { - char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX]; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(machine_info_clear) struct machine_info mi = {}; _cleanup_free_ char *hn = NULL; @@ -2064,8 +2038,8 @@ static int show_system_status(sd_bus *bus) { printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units); printf(" Since: %s; %s\n", - format_timestamp_style(since2, sizeof(since2), mi.timestamp, arg_timestamp_style), - format_timestamp_relative(since1, sizeof(since1), mi.timestamp)); + FORMAT_TIMESTAMP_STYLE(mi.timestamp, arg_timestamp_style), + FORMAT_TIMESTAMP_RELATIVE(mi.timestamp)); printf(" CGroup: %s\n", mi.control_group ?: "/"); if (IN_SET(arg_transport, diff --git a/src/test/meson.build b/src/test/meson.build index e106059182..14725248ce 100644 --- a/src/test/meson.build +++ b/src/test/meson.build @@ -44,6 +44,8 @@ test_dlopen_c = files('test-dlopen.c') tests += [ [['src/test/test-device-nodes.c']], + [['src/test/test-ether-addr-util.c']], + [['src/test/test-engine.c'], [libcore, libshared], diff --git a/src/test/test-boot-timestamps.c b/src/test/test-boot-timestamps.c index ae5b5821f0..23155b2d98 100644 --- a/src/test/test-boot-timestamps.c +++ b/src/test/test-boot-timestamps.c @@ -11,7 +11,6 @@ #include "util.h" static int test_acpi_fpdt(void) { - char ts_start[FORMAT_TIMESPAN_MAX], ts_exit[FORMAT_TIMESPAN_MAX], ts_span[FORMAT_TIMESPAN_MAX]; usec_t loader_start, loader_exit; int r; @@ -24,14 +23,13 @@ static int test_acpi_fpdt(void) { } log_info("ACPI FPDT: loader start=%s exit=%s duration=%s", - format_timespan(ts_start, sizeof(ts_start), loader_start, USEC_PER_MSEC), - format_timespan(ts_exit, sizeof(ts_exit), loader_exit, USEC_PER_MSEC), - format_timespan(ts_span, sizeof(ts_span), loader_exit - loader_start, USEC_PER_MSEC)); + FORMAT_TIMESPAN(loader_start, USEC_PER_MSEC), + FORMAT_TIMESPAN(loader_exit, USEC_PER_MSEC), + FORMAT_TIMESPAN(loader_exit - loader_start, USEC_PER_MSEC)); return 1; } static int test_efi_loader(void) { - char ts_start[FORMAT_TIMESPAN_MAX], ts_exit[FORMAT_TIMESPAN_MAX], ts_span[FORMAT_TIMESPAN_MAX]; usec_t loader_start, loader_exit; int r; @@ -44,14 +42,13 @@ static int test_efi_loader(void) { } log_info("EFI Loader: start=%s exit=%s duration=%s", - format_timespan(ts_start, sizeof(ts_start), loader_start, USEC_PER_MSEC), - format_timespan(ts_exit, sizeof(ts_exit), loader_exit, USEC_PER_MSEC), - format_timespan(ts_span, sizeof(ts_span), loader_exit - loader_start, USEC_PER_MSEC)); + FORMAT_TIMESPAN(loader_start, USEC_PER_MSEC), + FORMAT_TIMESPAN(loader_exit, USEC_PER_MSEC), + FORMAT_TIMESPAN(loader_exit - loader_start, USEC_PER_MSEC)); return 1; } static int test_boot_timestamps(void) { - char s[MAX(FORMAT_TIMESPAN_MAX, FORMAT_TIMESTAMP_MAX)]; dual_timestamp fw, l, k; int r; @@ -65,11 +62,11 @@ static int test_boot_timestamps(void) { return ok ? 0 : r; } - log_info("Firmware began %s before kernel.", format_timespan(s, sizeof(s), fw.monotonic, 0)); - log_info("Loader began %s before kernel.", format_timespan(s, sizeof(s), l.monotonic, 0)); - log_info("Firmware began %s.", format_timestamp(s, sizeof(s), fw.realtime)); - log_info("Loader began %s.", format_timestamp(s, sizeof(s), l.realtime)); - log_info("Kernel began %s.", format_timestamp(s, sizeof(s), k.realtime)); + log_info("Firmware began %s before kernel.", FORMAT_TIMESPAN(fw.monotonic, 0)); + log_info("Loader began %s before kernel.", FORMAT_TIMESPAN(l.monotonic, 0)); + log_info("Firmware began %s.", FORMAT_TIMESTAMP(fw.realtime)); + log_info("Loader began %s.", FORMAT_TIMESTAMP(l.realtime)); + log_info("Kernel began %s.", FORMAT_TIMESTAMP(k.realtime)); return 1; } diff --git a/src/test/test-btrfs.c b/src/test/test-btrfs.c index e840536d4b..77ec801903 100644 --- a/src/test/test-btrfs.c +++ b/src/test/test-btrfs.c @@ -18,14 +18,13 @@ int main(int argc, char *argv[]) { if (fd < 0) log_error_errno(errno, "Failed to open root directory: %m"); else { - char ts[FORMAT_TIMESTAMP_MAX], bs[FORMAT_BYTES_MAX]; BtrfsSubvolInfo info; r = btrfs_subvol_get_info_fd(fd, 0, &info); if (r < 0) log_error_errno(r, "Failed to get subvolume info: %m"); else { - log_info("otime: %s", format_timestamp(ts, sizeof(ts), info.otime)); + log_info("otime: %s", FORMAT_TIMESTAMP(info.otime)); log_info("read-only (search): %s", yes_no(info.read_only)); } @@ -33,10 +32,10 @@ int main(int argc, char *argv[]) { if (r < 0) log_error_errno(r, "Failed to get quota info: %m"); else { - log_info("referenced: %s", strna(format_bytes(bs, sizeof(bs), quota.referenced))); - log_info("exclusive: %s", strna(format_bytes(bs, sizeof(bs), quota.exclusive))); - log_info("referenced_max: %s", strna(format_bytes(bs, sizeof(bs), quota.referenced_max))); - log_info("exclusive_max: %s", strna(format_bytes(bs, sizeof(bs), quota.exclusive_max))); + log_info("referenced: %s", strna(FORMAT_BYTES(quota.referenced))); + log_info("exclusive: %s", strna(FORMAT_BYTES(quota.exclusive))); + log_info("referenced_max: %s", strna(FORMAT_BYTES(quota.referenced_max))); + log_info("exclusive_max: %s", strna(FORMAT_BYTES(quota.exclusive_max))); } r = btrfs_subvol_get_read_only_fd(fd); diff --git a/src/test/test-calendarspec.c b/src/test/test-calendarspec.c index 4f1d0f64d5..5d680f9b9a 100644 --- a/src/test/test-calendarspec.c +++ b/src/test/test-calendarspec.c @@ -10,7 +10,6 @@ static void _test_one(int line, const char *input, const char *output) { CalendarSpec *c; _cleanup_free_ char *p = NULL, *q = NULL; usec_t u; - char buf[FORMAT_TIMESTAMP_MAX]; int r; assert_se(calendar_spec_from_string(input, &c) >= 0); @@ -22,7 +21,7 @@ static void _test_one(int line, const char *input, const char *output) { u = now(CLOCK_REALTIME); r = calendar_spec_next_usec(c, u, &u); - log_info("Next: %s", r < 0 ? strerror_safe(r) : format_timestamp(buf, sizeof buf, u)); + log_info("Next: %s", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP(u)); calendar_spec_free(c); assert_se(calendar_spec_from_string(p, &c) >= 0); @@ -37,7 +36,6 @@ static void _test_next(int line, const char *input, const char *new_tz, usec_t a CalendarSpec *c; usec_t u; char *old_tz; - char buf[FORMAT_TIMESTAMP_MAX]; int r; old_tz = getenv("TZ"); @@ -56,7 +54,7 @@ static void _test_next(int line, const char *input, const char *new_tz, usec_t a u = after; r = calendar_spec_next_usec(c, after, &u); - log_info("At: %s", r < 0 ? strerror_safe(r) : format_timestamp_style(buf, sizeof buf, u, TIMESTAMP_US)); + log_info("At: %s", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP_STYLE(u, TIMESTAMP_US)); if (expect != USEC_INFINITY) assert_se(r >= 0 && u == expect); else @@ -93,18 +91,17 @@ static void test_timestamp(void) { static void test_hourly_bug_4031(void) { CalendarSpec *c; usec_t n, u, w; - char buf[FORMAT_TIMESTAMP_MAX], zaf[FORMAT_TIMESTAMP_MAX]; int r; assert_se(calendar_spec_from_string("hourly", &c) >= 0); n = now(CLOCK_REALTIME); assert_se((r = calendar_spec_next_usec(c, n, &u)) >= 0); - log_info("Now: %s (%"PRIu64")", format_timestamp_style(buf, sizeof buf, n, TIMESTAMP_US), n); - log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : format_timestamp_style(buf, sizeof buf, u, TIMESTAMP_US), u); + log_info("Now: %s (%"PRIu64")", FORMAT_TIMESTAMP_STYLE(n, TIMESTAMP_US), n); + log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP_STYLE(u, TIMESTAMP_US), u); assert_se((r = calendar_spec_next_usec(c, u, &w)) >= 0); - log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : format_timestamp_style(zaf, sizeof zaf, w, TIMESTAMP_US), w); + log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP_STYLE(w, TIMESTAMP_US), w); assert_se(n < u); assert_se(u <= n + USEC_PER_HOUR); diff --git a/src/test/test-date.c b/src/test/test-date.c index 47b7096738..355f4e17de 100644 --- a/src/test/test-date.c +++ b/src/test/test-date.c @@ -15,12 +15,9 @@ static void test_should_pass(const char *p) { log_info("\"%s\" → \"%s\"", p, buf); assert_se(parse_timestamp(buf, &q) >= 0); - if (q != t) { - char tmp[FORMAT_TIMESTAMP_MAX]; - + if (q != t) log_error("round-trip failed: \"%s\" → \"%s\"", - buf, format_timestamp_style(tmp, sizeof(tmp), q, TIMESTAMP_US)); - } + buf, FORMAT_TIMESTAMP_STYLE(q, TIMESTAMP_US)); assert_se(q == t); assert_se(format_timestamp_relative(buf_relative, sizeof(buf_relative), t)); diff --git a/src/test/test-ether-addr-util.c b/src/test/test-ether-addr-util.c new file mode 100644 index 0000000000..894215844a --- /dev/null +++ b/src/test/test-ether-addr-util.c @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "ether-addr-util.h" +#include "tests.h" + +#define INFINIBAD_ADDR_1 ((const struct hw_addr_data){ .length = 20, .infiniband = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} }) + +static void test_HW_ADDR_TO_STRING(void) { + log_info("/* %s */", __func__); + + const char *s = HW_ADDR_TO_STR(&(const struct hw_addr_data){6}); + log_info("null: %s", s); + + log_info("null×2: %s, %s", + HW_ADDR_TO_STR(&(const struct hw_addr_data){6}), + HW_ADDR_TO_STR(&(const struct hw_addr_data){6})); + log_info("null×3: %s, %s, %s", + HW_ADDR_TO_STR(&(const struct hw_addr_data){6}), + s, + HW_ADDR_TO_STR(&(const struct hw_addr_data){6})); + + log_info("infiniband: %s", HW_ADDR_TO_STR(&INFINIBAD_ADDR_1)); + + /* Let's nest function calls in a stupid way. */ + _cleanup_free_ char *t = NULL; + log_info("infiniband×3: %s\n%14s%s\n%14s%s", + HW_ADDR_TO_STR(&(const struct hw_addr_data){20}), "", + t = strdup(HW_ADDR_TO_STR(&INFINIBAD_ADDR_1)), "", + HW_ADDR_TO_STR(&(const struct hw_addr_data){20})); + + const char *p; + /* Let's use a separate selection statement */ + if ((p = HW_ADDR_TO_STR(&(const struct hw_addr_data){6}))) + log_info("joint: %s, %s", s, p); +} + +int main(int argc, char *argv[]) { + test_setup_logging(LOG_INFO); + + test_HW_ADDR_TO_STRING(); + return 0; +} diff --git a/src/test/test-format-util.c b/src/test/test-format-util.c index 5562ac8761..4e6c90adfa 100644 --- a/src/test/test-format-util.c +++ b/src/test/test-format-util.c @@ -4,6 +4,15 @@ #include "macro.h" #include "string-util.h" +/* Do some basic checks on STRLEN() and DECIMAL_STR_MAX() */ +assert_cc(STRLEN("xxx") == 3); +assert_cc(STRLEN("") == 0); +assert_cc(DECIMAL_STR_MAX(uint8_t) == 5); +assert_cc(DECIMAL_STR_MAX(int8_t) == 5); +assert_cc(DECIMAL_STR_MAX(uint64_t) == 22); +assert_cc(DECIMAL_STR_MAX(char) == 5); +assert_cc(CONST_MAX(DECIMAL_STR_MAX(int8_t), STRLEN("xxx")) == 5); + static void test_format_bytes_one(uint64_t val, bool trailing_B, const char *iec_with_p, const char *iec_without_p, const char *si_with_p, const char *si_without_p) { char buf[FORMAT_BYTES_MAX]; diff --git a/src/test/test-hashmap-plain.c b/src/test/test-hashmap-plain.c index b9f20fbd94..f7bc8a7b2b 100644 --- a/src/test/test-hashmap-plain.c +++ b/src/test/test-hashmap-plain.c @@ -752,7 +752,6 @@ static void test_hashmap_many(void) { for (j = 0; j < ELEMENTSOF(tests); j++) { usec_t ts = now(CLOCK_MONOTONIC), n; - char b[FORMAT_TIMESPAN_MAX]; assert_se(h = hashmap_new(tests[j].ops)); @@ -779,7 +778,7 @@ static void test_hashmap_many(void) { hashmap_free(h); n = now(CLOCK_MONOTONIC); - log_info("test took %s", format_timespan(b, sizeof b, n - ts, 0)); + log_info("test took %s", FORMAT_TIMESPAN(n - ts, 0)); } } @@ -790,7 +789,6 @@ static void test_hashmap_free(void) { Hashmap *h; bool slow = slow_tests_enabled(); usec_t ts, n; - char b[FORMAT_TIMESPAN_MAX]; unsigned n_entries = slow ? 1 << 20 : 240; const struct { @@ -824,7 +822,7 @@ static void test_hashmap_free(void) { hashmap_free(h); n = now(CLOCK_MONOTONIC); - log_info("%s test took %s", tests[j].title, format_timespan(b, sizeof b, n - ts, 0)); + log_info("%s test took %s", tests[j].title, FORMAT_TIMESPAN(n - ts, 0)); assert_se(custom_counter == tests[j].expect_counter); } diff --git a/src/test/test-procfs-util.c b/src/test/test-procfs-util.c index b2679e30fb..a961436b40 100644 --- a/src/test/test-procfs-util.c +++ b/src/test/test-procfs-util.c @@ -9,7 +9,6 @@ #include "tests.h" int main(int argc, char *argv[]) { - char buf[CONST_MAX(FORMAT_TIMESPAN_MAX, FORMAT_BYTES_MAX)]; nsec_t nsec; uint64_t v; int r; @@ -18,10 +17,10 @@ int main(int argc, char *argv[]) { log_open(); assert_se(procfs_cpu_get_usage(&nsec) >= 0); - log_info("Current system CPU time: %s", format_timespan(buf, sizeof(buf), nsec/NSEC_PER_USEC, 1)); + log_info("Current system CPU time: %s", FORMAT_TIMESPAN(nsec/NSEC_PER_USEC, 1)); assert_se(procfs_memory_get_used(&v) >= 0); - log_info("Current memory usage: %s", format_bytes(buf, sizeof(buf), v)); + log_info("Current memory usage: %s", FORMAT_BYTES(v)); assert_se(procfs_tasks_get_current(&v) >= 0); log_info("Current number of tasks: %" PRIu64, v); diff --git a/src/test/test-time-util.c b/src/test/test-time-util.c index 6f4675aaf4..bc23affc81 100644 --- a/src/test/test-time-util.c +++ b/src/test/test-time-util.c @@ -335,8 +335,7 @@ static void test_format_timestamp(void) { char buf[MAX(FORMAT_TIMESTAMP_MAX, FORMAT_TIMESPAN_MAX)]; usec_t x, y; - random_bytes(&x, sizeof(x)); - x = x % (2147483600 * USEC_PER_SEC) + 1; + x = random_u64_range(2147483600 * USEC_PER_SEC) + 1; assert_se(format_timestamp(buf, sizeof(buf), x)); log_debug("%s", buf); @@ -370,6 +369,26 @@ static void test_format_timestamp(void) { } } +static void test_FORMAT_TIMESTAMP(void) { + log_info("/* %s */", __func__); + + for (unsigned i = 0; i < 100; i++) { + _cleanup_free_ char *buf; + usec_t x, y; + + x = random_u64_range(2147483600 * USEC_PER_SEC) + 1; + + /* strbuf() is to test the macro in an argument to a function call. */ + assert_se(buf = strdup(FORMAT_TIMESTAMP(x))); + log_debug("%s", buf); + assert_se(parse_timestamp(buf, &y) >= 0); + assert_se(x / USEC_PER_SEC == y / USEC_PER_SEC); + + char *t = FORMAT_TIMESTAMP(x); + assert_se(streq(t, buf)); + } +} + static void test_format_timestamp_relative(void) { log_info("/* %s */", __func__); @@ -624,6 +643,7 @@ int main(int argc, char *argv[]) { test_usec_sub_signed(); test_usec_sub_unsigned(); test_format_timestamp(); + test_FORMAT_TIMESTAMP(); test_format_timestamp_relative(); test_format_timestamp_utc(); test_deserialize_dual_timestamp(); diff --git a/src/test/test-util.c b/src/test/test-util.c index 3eef2c3019..fa36f54fcb 100644 --- a/src/test/test-util.c +++ b/src/test/test-util.c @@ -321,7 +321,6 @@ static void test_raw_clone(void) { static void test_physical_memory(void) { uint64_t p; - char buf[FORMAT_BYTES_MAX]; log_info("/* %s */", __func__); @@ -330,7 +329,7 @@ static void test_physical_memory(void) { assert_se(p < UINT64_MAX); assert_se(p % page_size() == 0); - log_info("Memory: %s (%" PRIu64 ")", format_bytes(buf, sizeof(buf), p), p); + log_info("Memory: %s (%" PRIu64 ")", FORMAT_BYTES(p), p); } static void test_physical_memory_scale(void) { diff --git a/src/test/test-xattr-util.c b/src/test/test-xattr-util.c index 6aa55ba17e..7017b02ac9 100644 --- a/src/test/test-xattr-util.c +++ b/src/test/test-xattr-util.c @@ -51,9 +51,7 @@ cleanup: } static void test_getcrtime(void) { - _cleanup_close_ int fd = -1; - char ts[FORMAT_TIMESTAMP_MAX]; const char *vt; usec_t usec, k; int r; @@ -67,7 +65,7 @@ static void test_getcrtime(void) { if (r < 0) log_debug_errno(r, "btime: %m"); else - log_debug("btime: %s", format_timestamp(ts, sizeof(ts), usec)); + log_debug("btime: %s", FORMAT_TIMESTAMP(usec)); k = now(CLOCK_REALTIME); diff --git a/src/timedate/timedatectl.c b/src/timedate/timedatectl.c index d31f67f4cb..c0575c0323 100644 --- a/src/timedate/timedatectl.c +++ b/src/timedate/timedatectl.c @@ -359,8 +359,6 @@ DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(ntp_leap, uint32_t); REENABLE_WARNING; static int print_ntp_status_info(NTPStatusInfo *i) { - char ts[FORMAT_TIMESPAN_MAX], jitter[FORMAT_TIMESPAN_MAX], - tmin[FORMAT_TIMESPAN_MAX], tmax[FORMAT_TIMESPAN_MAX]; usec_t delay, t14, t23, offset, root_distance; _cleanup_(table_unrefp) Table *table = NULL; bool offset_sign; @@ -407,9 +405,9 @@ static int print_ntp_status_info(NTPStatusInfo *i) { return table_log_add_error(r); r = table_add_cell_stringf(table, NULL, "%s (min: %s; max %s)", - format_timespan(ts, sizeof(ts), i->poll_interval, 0), - format_timespan(tmin, sizeof(tmin), i->poll_min, 0), - format_timespan(tmax, sizeof(tmax), i->poll_max, 0)); + FORMAT_TIMESPAN(i->poll_interval, 0), + FORMAT_TIMESPAN(i->poll_min, 0), + FORMAT_TIMESPAN(i->poll_max, 0)); if (r < 0) return table_log_add_error(r); @@ -468,7 +466,7 @@ static int print_ntp_status_info(NTPStatusInfo *i) { return table_log_add_error(r); r = table_add_cell_stringf(table, NULL, "%s (%" PRIi32 ")", - format_timespan(ts, sizeof(ts), DIV_ROUND_UP((nsec_t) (exp2(i->precision) * NSEC_PER_SEC), NSEC_PER_USEC), 0), + FORMAT_TIMESPAN(DIV_ROUND_UP((nsec_t) (exp2(i->precision) * NSEC_PER_SEC), NSEC_PER_USEC), 0), i->precision); if (r < 0) return table_log_add_error(r); @@ -478,8 +476,8 @@ static int print_ntp_status_info(NTPStatusInfo *i) { return table_log_add_error(r); r = table_add_cell_stringf(table, NULL, "%s (max: %s)", - format_timespan(ts, sizeof(ts), root_distance, 0), - format_timespan(tmax, sizeof(tmax), i->root_distance_max, 0)); + FORMAT_TIMESPAN(root_distance, 0), + FORMAT_TIMESPAN(i->root_distance_max, 0)); if (r < 0) return table_log_add_error(r); @@ -489,15 +487,15 @@ static int print_ntp_status_info(NTPStatusInfo *i) { r = table_add_cell_stringf(table, NULL, "%s%s", offset_sign ? "+" : "-", - format_timespan(ts, sizeof(ts), offset, 0)); + FORMAT_TIMESPAN(offset, 0)); if (r < 0) return table_log_add_error(r); r = table_add_many(table, TABLE_STRING, "Delay:", - TABLE_STRING, format_timespan(ts, sizeof(ts), delay, 0), + TABLE_STRING, FORMAT_TIMESPAN(delay, 0), TABLE_STRING, "Jitter:", - TABLE_STRING, format_timespan(jitter, sizeof(jitter), i->jitter, 0), + TABLE_STRING, FORMAT_TIMESPAN(i->jitter, 0), TABLE_STRING, "Packet count:", TABLE_UINT64, i->packet_count); if (r < 0) @@ -717,7 +715,6 @@ static int print_timesync_property(const char *name, const char *expected_value, case SD_BUS_TYPE_STRUCT: if (streq(name, "NTPMessage")) { _cleanup_(ntp_status_info_clear) NTPStatusInfo i = {}; - char ts[FORMAT_TIMESPAN_MAX], stamp[FORMAT_TIMESTAMP_MAX]; r = map_ntp_message(NULL, NULL, m, NULL, &i); if (r < 0) @@ -733,28 +730,21 @@ static int print_timesync_property(const char *name, const char *expected_value, printf("{ Leap=%u, Version=%u, Mode=%u, Stratum=%u, Precision=%i,", i.leap, i.version, i.mode, i.stratum, i.precision); - printf(" RootDelay=%s,", - format_timespan(ts, sizeof(ts), i.root_delay, 0)); - printf(" RootDispersion=%s,", - format_timespan(ts, sizeof(ts), i.root_dispersion, 0)); + printf(" RootDelay=%s,", FORMAT_TIMESPAN(i.root_delay, 0)); + printf(" RootDispersion=%s,", FORMAT_TIMESPAN(i.root_dispersion, 0)); if (i.stratum == 1) printf(" Reference=%s,", i.reference.str); else printf(" Reference=%" PRIX32 ",", be32toh(i.reference.val)); - printf(" OriginateTimestamp=%s,", - format_timestamp(stamp, sizeof(stamp), i.origin)); - printf(" ReceiveTimestamp=%s,", - format_timestamp(stamp, sizeof(stamp), i.recv)); - printf(" TransmitTimestamp=%s,", - format_timestamp(stamp, sizeof(stamp), i.trans)); - printf(" DestinationTimestamp=%s,", - format_timestamp(stamp, sizeof(stamp), i.dest)); + printf(" OriginateTimestamp=%s,", FORMAT_TIMESTAMP(i.origin)); + printf(" ReceiveTimestamp=%s,", FORMAT_TIMESTAMP(i.recv)); + printf(" TransmitTimestamp=%s,", FORMAT_TIMESTAMP(i.trans)); + printf(" DestinationTimestamp=%s,", FORMAT_TIMESTAMP(i.dest)); printf(" Ignored=%s PacketCount=%" PRIu64 ",", yes_no(i.spike), i.packet_count); - printf(" Jitter=%s }\n", - format_timespan(ts, sizeof(ts), i.jitter, 0)); + printf(" Jitter=%s }\n", FORMAT_TIMESPAN(i.jitter, 0)); return 1; diff --git a/src/timesync/wait-sync.c b/src/timesync/wait-sync.c index 2a9b113ff4..892746d5ee 100644 --- a/src/timesync/wait-sync.c +++ b/src/timesync/wait-sync.c @@ -100,9 +100,7 @@ static int clock_state_update( ClockState *sp, sd_event *event) { - char buf[MAX((size_t)FORMAT_TIMESTAMP_MAX, STRLEN("unrepresentable"))]; struct timex tx = {}; - const char * ts; usec_t t; int r; @@ -149,10 +147,9 @@ static int clock_state_update( if (tx.status & STA_NANO) tx.time.tv_usec /= 1000; t = timeval_load(&tx.time); - ts = format_timestamp_style(buf, sizeof(buf), t, TIMESTAMP_US_UTC); - if (!ts) - strcpy(buf, "unrepresentable"); - log_info("adjtime state %d status %x time %s", sp->adjtime_state, tx.status, ts); + + log_info("adjtime state %d status %x time %s", sp->adjtime_state, tx.status, + FORMAT_TIMESTAMP_STYLE(t, TIMESTAMP_US_UTC) ?: "unrepresentable"); sp->has_watchfile = access("/run/systemd/timesync/synchronized", F_OK) >= 0; if (sp->has_watchfile) diff --git a/src/tmpfiles/tmpfiles.c b/src/tmpfiles/tmpfiles.c index b89555d8e0..fb90f6bfbb 100644 --- a/src/tmpfiles/tmpfiles.c +++ b/src/tmpfiles/tmpfiles.c @@ -544,22 +544,20 @@ static bool needs_cleanup( bool is_dir) { if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) { - char a[FORMAT_TIMESTAMP_MAX]; /* Follows spelling in stat(1). */ log_debug("%s \"%s\": modify time %s is too new.", is_dir ? "Directory" : "File", sub_path, - format_timestamp_style(a, sizeof(a), mtime / NSEC_PER_USEC, TIMESTAMP_US)); + FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US)); return false; } if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) { - char a[FORMAT_TIMESTAMP_MAX]; log_debug("%s \"%s\": access time %s is too new.", is_dir ? "Directory" : "File", sub_path, - format_timestamp_style(a, sizeof(a), atime / NSEC_PER_USEC, TIMESTAMP_US)); + FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US)); return false; } @@ -569,21 +567,19 @@ static bool needs_cleanup( * by default for directories, because we change it when deleting. */ if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) { - char a[FORMAT_TIMESTAMP_MAX]; log_debug("%s \"%s\": change time %s is too new.", is_dir ? "Directory" : "File", sub_path, - format_timestamp_style(a, sizeof(a), ctime / NSEC_PER_USEC, TIMESTAMP_US)); + FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US)); return false; } if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) { - char a[FORMAT_TIMESTAMP_MAX]; log_debug("%s \"%s\": birth time %s is too new.", is_dir ? "Directory" : "File", sub_path, - format_timestamp_style(a, sizeof(a), btime / NSEC_PER_USEC, TIMESTAMP_US)); + FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US)); return false; } @@ -810,13 +806,12 @@ static int dir_cleanup( finish: if (deleted) { - char a[FORMAT_TIMESTAMP_MAX], m[FORMAT_TIMESTAMP_MAX]; struct timespec ts[2]; log_debug("Restoring access and modification time on \"%s\": %s, %s", p, - format_timestamp_style(a, sizeof(a), self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US), - format_timestamp_style(m, sizeof(m), self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US)); + FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US), + FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US)); timespec_store_nsec(ts + 0, self_atime_nsec); timespec_store_nsec(ts + 1, self_mtime_nsec); @@ -2503,7 +2498,6 @@ static char *age_by_to_string(AgeBy ab, bool is_dir) { } static int clean_item_instance(Item *i, const char* instance) { - char timestamp[FORMAT_TIMESTAMP_MAX]; _cleanup_closedir_ DIR *d = NULL; STRUCT_STATX_DEFINE(sx); int mountpoint, r; @@ -2562,7 +2556,7 @@ static int clean_item_instance(Item *i, const char* instance) { log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s", mountpoint ? "mount point" : "directory", instance, - format_timestamp_style(timestamp, sizeof(timestamp), cutoff, TIMESTAMP_US), + FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US), ab_f, ab_d); } diff --git a/src/udev/udev-event.c b/src/udev/udev-event.c index b28089be71..c31d4851a0 100644 --- a/src/udev/udev-event.c +++ b/src/udev/udev-event.c @@ -600,7 +600,6 @@ reenable: static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) { Spawn *spawn = userdata; - char timeout[FORMAT_TIMESPAN_MAX]; assert(spawn); @@ -610,20 +609,19 @@ static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) { log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing", spawn->cmd, spawn->pid, - format_timespan(timeout, sizeof(timeout), spawn->timeout_usec, USEC_PER_SEC)); + FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC)); return 1; } static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) { Spawn *spawn = userdata; - char timeout[FORMAT_TIMESPAN_MAX]; assert(spawn); log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete", spawn->cmd, spawn->pid, - format_timespan(timeout, sizeof(timeout), spawn->timeout_warn_usec, USEC_PER_SEC)); + FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC)); return 1; } @@ -1080,10 +1078,8 @@ void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_s log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command); } else { if (event->exec_delay_usec > 0) { - char buf[FORMAT_TIMESPAN_MAX]; - log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.", - command, format_timespan(buf, sizeof(buf), event->exec_delay_usec, USEC_PER_SEC)); + command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC)); (void) usleep(event->exec_delay_usec); } diff --git a/src/userdb/userwork.c b/src/userdb/userwork.c index 8b7a20b08d..c3eb99ce9c 100644 --- a/src/userdb/userwork.c +++ b/src/userdb/userwork.c @@ -503,18 +503,16 @@ static int run(int argc, char *argv[]) { n = now(CLOCK_MONOTONIC); if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) { - char buf[FORMAT_TIMESPAN_MAX]; log_debug("Exiting worker, ran for %s, that's enough.", - format_timespan(buf, sizeof(buf), usec_sub_unsigned(n, start_time), 0)); + FORMAT_TIMESPAN(usec_sub_unsigned(n, start_time), 0)); break; } if (last_busy_usec == USEC_INFINITY) last_busy_usec = n; else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) { - char buf[FORMAT_TIMESPAN_MAX]; log_debug("Exiting worker, been idle for %s.", - format_timespan(buf, sizeof(buf), usec_sub_unsigned(n, last_busy_usec), 0)); + FORMAT_TIMESPAN(usec_sub_unsigned(n, last_busy_usec), 0)); break; } |