diff options
75 files changed, 644 insertions, 646 deletions
diff --git a/Userland/Utilities/adjtime.cpp b/Userland/Utilities/adjtime.cpp index 9274d7fccb..f721c782ab 100644 --- a/Userland/Utilities/adjtime.cpp +++ b/Userland/Utilities/adjtime.cpp @@ -51,7 +51,7 @@ int main(int argc, char** argv) return 1; } double remaining_delta = remaining_delta_timeval.tv_sec + remaining_delta_timeval.tv_usec / 1'000'000.0; - printf("%f\n", remaining_delta); + outln("{}", remaining_delta); return 0; } diff --git a/Userland/Utilities/allocate.cpp b/Userland/Utilities/allocate.cpp index 05b4c8860c..da932099b6 100644 --- a/Userland/Utilities/allocate.cpp +++ b/Userland/Utilities/allocate.cpp @@ -7,13 +7,12 @@ #include <AK/Optional.h> #include <AK/String.h> #include <LibCore/ElapsedTimer.h> -#include <stdio.h> #include <string.h> #include <unistd.h> static void usage() { - printf("usage: allocate [number [unit (B/KiB/MiB)]]\n"); + warnln("usage: allocate [number [unit (B/KiB/MiB)]]"); exit(1); } @@ -60,21 +59,21 @@ int main(int argc, char** argv) Core::ElapsedTimer timer; - printf("allocating memory (%d bytes)...\n", count); + outln("allocating memory ({} bytes)...", count); timer.start(); char* ptr = (char*)malloc(count); if (!ptr) { - printf("failed.\n"); + outln("failed."); return 1; } - printf("done in %dms\n", timer.elapsed()); + outln("done in {}ms", timer.elapsed()); auto pages = count / PAGE_SIZE; auto step = pages / 10; Core::ElapsedTimer timer2; - printf("writing one byte to each page of allocated memory...\n"); + outln("writing one byte to each page of allocated memory..."); timer.start(); timer2.start(); for (int i = 0; i < pages; ++i) { @@ -87,24 +86,24 @@ int main(int argc, char** argv) auto bps = double(step * PAGE_SIZE) / (double(ms) / 1000); - printf("step took %dms (%fMiB/s)\n", ms, bps / MiB); + outln("step took {}ms ({}MiB/s)", ms, bps / MiB); timer2.start(); } } - printf("done in %dms\n", timer.elapsed()); + outln("done in {}ms", timer.elapsed()); - printf("sleeping for ten seconds...\n"); + outln("sleeping for ten seconds..."); for (int i = 0; i < 10; i++) { - printf("%d\n", i); + outln("{}", i); sleep(1); } - printf("done.\n"); + outln("done."); - printf("freeing memory...\n"); + outln("freeing memory..."); timer.start(); free(ptr); - printf("done in %dms\n", timer.elapsed()); + outln("done in {}ms", timer.elapsed()); return 0; } diff --git a/Userland/Utilities/aplay.cpp b/Userland/Utilities/aplay.cpp index ea2ffe6016..ae54ed329b 100644 --- a/Userland/Utilities/aplay.cpp +++ b/Userland/Utilities/aplay.cpp @@ -25,21 +25,21 @@ int main(int argc, char** argv) auto audio_client = Audio::ClientConnection::construct(); NonnullRefPtr<Audio::Loader> loader = Audio::Loader::create(path); if (loader->has_error()) { - fprintf(stderr, "Failed to load audio file: %s\n", loader->error_string()); + warnln("Failed to load audio file: {}", loader->error_string()); return 1; } - printf("\033[34;1m Playing\033[0m: %s\n", path); - printf("\033[34;1m Format\033[0m: %u Hz, %u-bit, %s\n", + outln("\033[34;1m Playing\033[0m: {}", path); + outln("\033[34;1m Format\033[0m: {} Hz, {}-bit, {}", loader->sample_rate(), loader->bits_per_sample(), loader->num_channels() == 1 ? "Mono" : "Stereo"); - printf("\033[34;1mProgress\033[0m: \033[s"); + out("\033[34;1mProgress\033[0m: \033[s"); for (;;) { auto samples = loader->get_more_samples(); if (samples) { - printf("\033[u"); - printf("%d/%d", loader->loaded_samples(), loader->total_samples()); + out("\033[u"); + out("{}/{}", loader->loaded_samples(), loader->total_samples()); fflush(stdout); audio_client->enqueue(*samples); } else if (should_loop) { @@ -50,6 +50,6 @@ int main(int argc, char** argv) break; } } - printf("\n"); + outln(); return 0; } diff --git a/Userland/Utilities/arp.cpp b/Userland/Utilities/arp.cpp index 5684bd7a85..51c118e5c3 100644 --- a/Userland/Utilities/arp.cpp +++ b/Userland/Utilities/arp.cpp @@ -8,17 +8,16 @@ #include <AK/ByteBuffer.h> #include <AK/JsonObject.h> #include <LibCore/File.h> -#include <stdio.h> int main() { auto file = Core::File::construct("/proc/net/arp"); if (!file->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Error: %s\n", file->error_string()); + warnln("Failed to open {}: {}", file->name(), file->error_string()); return 1; } - printf("Address HWaddress\n"); + outln("Address HWaddress"); auto file_contents = file->read_all(); auto json = JsonValue::from_string(file_contents); VERIFY(json.has_value()); @@ -28,9 +27,7 @@ int main() auto ip_address = if_object.get("ip_address").to_string(); auto mac_address = if_object.get("mac_address").to_string(); - printf("%-15s ", ip_address.characters()); - printf("%-17s ", mac_address.characters()); - printf("\n"); + outln("{:15} {:17}", ip_address, mac_address); }); return 0; diff --git a/Userland/Utilities/avol.cpp b/Userland/Utilities/avol.cpp index 10dd8627c1..d70d106ce9 100644 --- a/Userland/Utilities/avol.cpp +++ b/Userland/Utilities/avol.cpp @@ -28,19 +28,19 @@ int main(int argc, char** argv) if (!mute && !unmute && !volume) { auto volume = audio_client->get_main_mix_volume(); - printf("Volume: %d\n", volume); + outln("Volume: {}", volume); return 0; } if (!(mute ^ unmute ^ (volume != nullptr))) { - fprintf(stderr, "Only one of mute, unmute or volume must be used\n"); + warnln("Only one of mute, unmute or volume must be used"); return 1; } if (mute) { audio_client->set_muted(true); - printf("Muted.\n"); + outln("Muted."); } else if (unmute) { audio_client->set_muted(false); - printf("Unmuted.\n"); + outln("Unmuted."); } else { auto new_volume = atoi(volume); audio_client->set_main_mix_volume(new_volume); diff --git a/Userland/Utilities/base64.cpp b/Userland/Utilities/base64.cpp index a57f6f961d..21e4dc04f5 100644 --- a/Userland/Utilities/base64.cpp +++ b/Userland/Utilities/base64.cpp @@ -56,5 +56,5 @@ int main(int argc, char** argv) } auto encoded = encode_base64(buffer); - printf("%s\n", encoded.characters()); + outln("{}", encoded); } diff --git a/Userland/Utilities/cal.cpp b/Userland/Utilities/cal.cpp index c18fc5015e..1c5b05fd79 100644 --- a/Userland/Utilities/cal.cpp +++ b/Userland/Utilities/cal.cpp @@ -125,20 +125,20 @@ int main(int argc, char** argv) clean_buffers(); if (year_mode) { - printf(" "); - printf("Year %4d", year); - printf(" \n\n"); + out(" Year {:04} ", year); + outln(); + outln(); for (int i = 1; i < 12; ++i) { insert_month_to_print(0, i++, year); insert_month_to_print(1, i++, year); insert_month_to_print(2, i, year); - printf("%s\n", print_buffer); + outln("{}", print_buffer); clean_buffers(); } } else { insert_month_to_print(0, month, year); - printf("%s\n\n", print_buffer); + outln("{}", print_buffer); clean_buffers(); } diff --git a/Userland/Utilities/chgrp.cpp b/Userland/Utilities/chgrp.cpp index 22de36e7a9..67354ebfe8 100644 --- a/Userland/Utilities/chgrp.cpp +++ b/Userland/Utilities/chgrp.cpp @@ -33,7 +33,7 @@ int main(int argc, char** argv) gid_t new_gid = -1; if (String(gid_arg).is_empty()) { - fprintf(stderr, "Empty gid option\n"); + warnln("Empty gid option"); return 1; } @@ -43,7 +43,7 @@ int main(int argc, char** argv) } else { auto* group = getgrnam(gid_arg); if (!group) { - fprintf(stderr, "Unknown group '%s'\n", gid_arg); + warnln("Unknown group '{}'", gid_arg); return 1; } new_gid = group->gr_gid; diff --git a/Userland/Utilities/chmod.cpp b/Userland/Utilities/chmod.cpp index 4dd7ccd02c..5b23252fc2 100644 --- a/Userland/Utilities/chmod.cpp +++ b/Userland/Utilities/chmod.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <AK/Optional.h> #include <stdio.h> #include <string.h> @@ -58,8 +59,8 @@ int main(int argc, char** argv) } if (argc < 3) { - printf("usage: chmod <octal-mode> <path...>\n" - " chmod [[ugoa][+-=][rwx...],...] <path...>\n"); + warnln("usage: chmod <octal-mode> <path...>"); + warnln(" chmod [[ugoa][+-=][rwx...],...] <path...>"); return 1; } @@ -100,7 +101,7 @@ int main(int argc, char** argv) continue; } if (!tmp_mask.has_value()) { - fprintf(stderr, "chmod: invalid mode: %s\n", argv[1]); + warnln("chmod: invalid mode: {}", argv[1]); return 1; } mask |= tmp_mask.value(); diff --git a/Userland/Utilities/chown.cpp b/Userland/Utilities/chown.cpp index a1d15de091..7f29202d1f 100644 --- a/Userland/Utilities/chown.cpp +++ b/Userland/Utilities/chown.cpp @@ -21,7 +21,7 @@ int main(int argc, char** argv) } if (argc < 3) { - printf("usage: chown <uid[:gid]> <path>\n"); + warnln("usage: chown <uid[:gid]> <path>"); return 0; } @@ -30,11 +30,11 @@ int main(int argc, char** argv) auto parts = String(argv[1]).split(':', true); if (parts.is_empty()) { - fprintf(stderr, "Empty uid/gid spec\n"); + warnln("Empty uid/gid spec"); return 1; } if (parts[0].is_empty() || (parts.size() == 2 && parts[1].is_empty()) || parts.size() > 2) { - fprintf(stderr, "Invalid uid/gid spec\n"); + warnln("Invalid uid/gid spec"); return 1; } @@ -44,7 +44,7 @@ int main(int argc, char** argv) } else { auto* passwd = getpwnam(parts[0].characters()); if (!passwd) { - fprintf(stderr, "Unknown user '%s'\n", parts[0].characters()); + warnln("Unknown user '{}'", parts[0]); return 1; } new_uid = passwd->pw_uid; @@ -57,7 +57,7 @@ int main(int argc, char** argv) } else { auto* group = getgrnam(parts[1].characters()); if (!group) { - fprintf(stderr, "Unknown group '%s'\n", parts[1].characters()); + warnln("Unknown group '{}'", parts[1]); return 1; } new_gid = group->gr_gid; diff --git a/Userland/Utilities/chroot.cpp b/Userland/Utilities/chroot.cpp index 4463829ad1..0141232bc4 100644 --- a/Userland/Utilities/chroot.cpp +++ b/Userland/Utilities/chroot.cpp @@ -65,7 +65,7 @@ int main(int argc, char** argv) else if (part == "remount") flags |= MS_REMOUNT; else if (part == "bind") - fprintf(stderr, "Ignoring -o bind, as it doesn't make sense for chroot\n"); + warnln("Ignoring -o bind, as it doesn't make sense for chroot"); else return false; } diff --git a/Userland/Utilities/cp.cpp b/Userland/Utilities/cp.cpp index 78fc174936..c0ca9a96fc 100644 --- a/Userland/Utilities/cp.cpp +++ b/Userland/Utilities/cp.cpp @@ -47,7 +47,7 @@ int main(int argc, char** argv) } if (verbose) - printf("'%s' -> '%s'\n", source, destination); + outln("'{}' -> '{}'", source, destination); } return 0; } diff --git a/Userland/Utilities/crash.cpp b/Userland/Utilities/crash.cpp index c9bbf76463..c805268e17 100644 --- a/Userland/Utilities/crash.cpp +++ b/Userland/Utilities/crash.cpp @@ -249,7 +249,7 @@ int main(int argc, char** argv) if (do_use_io_instruction || do_all_crash_types) { Crash("Attempt to use an I/O instruction", [] { u8 keyboard_status = IO::in8(0x64); - printf("Keyboard status: %#02x\n", keyboard_status); + outln("Keyboard status: {:#02x}", keyboard_status); return Crash::Failure::DidNotCrash; }).run(run_type); } @@ -267,7 +267,7 @@ int main(int argc, char** argv) perror("pledge"); return Crash::Failure::DidNotCrash; } - printf("Didn't pledge 'stdio', this should fail!\n"); + outln("Didn't pledge 'stdio', this should fail!"); return Crash::Failure::DidNotCrash; }).run(run_type); } diff --git a/Userland/Utilities/cut.cpp b/Userland/Utilities/cut.cpp index 15c6e8bf09..58db6b449b 100644 --- a/Userland/Utilities/cut.cpp +++ b/Userland/Utilities/cut.cpp @@ -33,7 +33,7 @@ struct Index { static void print_usage_and_exit(int ret) { - printf("Usage: cut -b list [File]\n"); + warnln("Usage: cut -b list [File]"); exit(ret); } @@ -59,24 +59,24 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indices) { for (auto& token : tokens) { if (token.length() == 0) { - fprintf(stderr, "cut: byte/character positions are numbered from 1\n"); + warnln("cut: byte/character positions are numbered from 1"); print_usage_and_exit(1); } if (token == "-") { - fprintf(stderr, "cut: invalid range with no endpoint: %s\n", token.characters()); + warnln("cut: invalid range with no endpoint: {}", token); print_usage_and_exit(1); } if (token[0] == '-') { auto index = token.substring(1, token.length() - 1).to_int(); if (!index.has_value()) { - fprintf(stderr, "cut: invalid byte/character position '%s'\n", token.characters()); + warnln("cut: invalid byte/character position '{}'", token); print_usage_and_exit(1); } if (index.value() == 0) { - fprintf(stderr, "cut: byte/character positions are numbered from 1\n"); + warnln("cut: byte/character positions are numbered from 1"); print_usage_and_exit(1); } @@ -85,12 +85,12 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indices) } else if (token[token.length() - 1] == '-') { auto index = token.substring(0, token.length() - 1).to_int(); if (!index.has_value()) { - fprintf(stderr, "cut: invalid byte/character position '%s'\n", token.characters()); + warnln("cut: invalid byte/character position '{}'", token); print_usage_and_exit(1); } if (index.value() == 0) { - fprintf(stderr, "cut: byte/character positions are numbered from 1\n"); + warnln("cut: byte/character positions are numbered from 1"); print_usage_and_exit(1); } Index tmp = { index.value(), -1, Index::Type::SliceIndex }; @@ -100,21 +100,21 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indices) if (range.size() == 2) { auto index1 = range[0].to_int(); if (!index1.has_value()) { - fprintf(stderr, "cut: invalid byte/character position '%s'\n", range[0].characters()); + warnln("cut: invalid byte/character position '{}'", range[0]); print_usage_and_exit(1); } auto index2 = range[1].to_int(); if (!index2.has_value()) { - fprintf(stderr, "cut: invalid byte/character position '%s'\n", range[1].characters()); + warnln("cut: invalid byte/character position '{}'", range[1]); print_usage_and_exit(1); } if (index1.value() > index2.value()) { - fprintf(stderr, "cut: invalid decreasing range\n"); + warnln("cut: invalid decreasing range"); print_usage_and_exit(1); } else if (index1.value() == 0 || index2.value() == 0) { - fprintf(stderr, "cut: byte/character positions are numbered from 1\n"); + warnln("cut: byte/character positions are numbered from 1"); print_usage_and_exit(1); } @@ -123,19 +123,19 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indices) } else if (range.size() == 1) { auto index = range[0].to_int(); if (!index.has_value()) { - fprintf(stderr, "cut: invalid byte/character position '%s'\n", range[0].characters()); + warnln("cut: invalid byte/character position '{}'", range[0]); print_usage_and_exit(1); } if (index.value() == 0) { - fprintf(stderr, "cut: byte/character positions are numbered from 1\n"); + warnln("cut: byte/character positions are numbered from 1"); print_usage_and_exit(1); } Index tmp = { index.value(), index.value(), Index::Type::SingleIndex }; add_if_not_exists(indices, tmp); } else { - fprintf(stderr, "cut: invalid byte or character range\n"); + warnln("cut: invalid byte or character range"); print_usage_and_exit(1); } } @@ -148,7 +148,7 @@ static void cut_file(const String& file, const Vector<Index>& byte_vector) if (!file.is_null()) { fp = fopen(file.characters(), "r"); if (!fp) { - fprintf(stderr, "cut: Could not open file '%s'\n", file.characters()); + warnln("cut: Could not open file '{}'", file); return; } } @@ -161,17 +161,17 @@ static void cut_file(const String& file, const Vector<Index>& byte_vector) line_length--; for (auto& i : byte_vector) { if (i.m_type == Index::Type::SliceIndex && i.m_from < line_length) - printf("%s", line + i.m_from - 1); + out("{}", line + i.m_from - 1); else if (i.m_type == Index::Type::SingleIndex && i.m_from <= line_length) - printf("%c", line[i.m_from - 1]); + out("{:c}", line[i.m_from - 1]); else if (i.m_type == Index::Type::RangedIndex && i.m_from <= line_length) { auto to = i.m_to > line_length ? line_length : i.m_to; auto sub_string = String(line).substring(i.m_from - 1, to - i.m_from + 1); - printf("%s", sub_string.characters()); + out("{}", sub_string); } else break; } - printf("\n"); + outln(); } if (line) @@ -205,7 +205,7 @@ int main(int argc, char** argv) } else if (argv[i][0] != '-') { files.append(argv[i++]); } else { - fprintf(stderr, "cut: invalid argument %s\n", argv[i]); + warnln("cut: invalid argument {}", argv[i]); print_usage_and_exit(1); } } diff --git a/Userland/Utilities/date.cpp b/Userland/Utilities/date.cpp index ef48ad6946..9a431098dd 100644 --- a/Userland/Utilities/date.cpp +++ b/Userland/Utilities/date.cpp @@ -36,7 +36,7 @@ int main(int argc, char** argv) auto number = String(set_date).to_uint(); if (!number.has_value()) { - fprintf(stderr, "date: Invalid timestamp value"); + warnln("date: Invalid timestamp value"); return 1; } @@ -52,7 +52,7 @@ int main(int argc, char** argv) // FIXME: this should be improved and will need to be cleaned up // when additional output formats and formatting is supported if (print_unix_date && print_iso_8601 && print_rfc_3339 && print_rfc_5322) { - fprintf(stderr, "date: multiple output formats specified\n"); + warnln("date: multiple output formats specified"); return 1; } @@ -60,19 +60,19 @@ int main(int argc, char** argv) auto date = Core::DateTime::from_timestamp(now); if (print_unix_date) { - printf("%lld\n", (long long)now); + outln("{}", (long long)now); return 0; } else if (print_iso_8601) { - printf("%s\n", date.to_string("%Y-%m-%dT%H:%M:%S-00:00").characters()); + outln("{}", date.to_string("%Y-%m-%dT%H:%M:%S-00:00")); return 0; } else if (print_rfc_5322) { - printf("%s\n", date.to_string("%a, %d %b %Y %H:%M:%S -0000").characters()); + outln("{}", date.to_string("%a, %d %b %Y %H:%M:%S -0000")); return 0; } else if (print_rfc_3339) { - printf("%s\n", date.to_string("%Y-%m-%d %H:%M:%S-00:00").characters()); + outln("{}", date.to_string("%Y-%m-%d %H:%M:%S-00:00")); return 0; } else { - printf("%s\n", date.to_string().characters()); + outln("{}", date.to_string()); return 0; } } diff --git a/Userland/Utilities/dd.cpp b/Userland/Utilities/dd.cpp index 60875a9e35..828a55fbab 100644 --- a/Userland/Utilities/dd.cpp +++ b/Userland/Utilities/dd.cpp @@ -41,7 +41,7 @@ static String split_at_equals(const char* argument) auto values = string_value.split('='); if (values.size() != 2) { - fprintf(stderr, "Unable to parse: %s\n", argument); + warnln("Unable to parse: {}", argument); return {}; } else { return values[1]; @@ -57,7 +57,7 @@ static int handle_io_file_arguments(int& fd, int flags, const char* argument) fd = open(value.characters(), flags, 0666); if (fd == -1) { - fprintf(stderr, "Unable to open: %s\n", value.characters()); + warnln("Unable to open: {}", value); return -1; } else { return 0; @@ -89,13 +89,13 @@ static int handle_size_arguments(size_t& numeric_value, const char* argument) Optional<unsigned> numeric_optional = value.to_uint(); if (!numeric_optional.has_value()) { - fprintf(stderr, "Invalid size-value: %s\n", value.characters()); + warnln("Invalid size-value: {}", value); return -1; } numeric_value = numeric_optional.value() * suffix_multiplier; if (numeric_value < 1) { - fprintf(stderr, "Invalid size-value: %lu\n", numeric_value); + warnln("Invalid size-value: {}", numeric_value); return -1; } else { return 0; @@ -119,7 +119,7 @@ static int handle_status_arguments(Status& status, const char* argument) status = None; return 0; } else { - fprintf(stderr, "Unknown status: %s\n", value.characters()); + warnln("Unknown status: {}", value); return -1; } } @@ -144,7 +144,7 @@ int main(int argc, char** argv) for (int a = 1; a < argc; a++) { if (!strcmp(argv[a], "--help")) { - printf("%s", usage); + out("{}", usage); return 0; } else if (!strncmp(argv[a], "if=", 3)) { if (handle_io_file_arguments(input_fd, input_flags, argv[a]) < 0) { @@ -175,19 +175,19 @@ int main(int argc, char** argv) return 1; } } else { - fprintf(stderr, "%s", usage); + warn("{}", usage); return 1; } } if ((buffer = (uint8_t*)malloc(block_size)) == nullptr) { - fprintf(stderr, "Unable to allocate %lu bytes for the buffer.\n", block_size); + warnln("Unable to allocate {} bytes for the buffer.", block_size); return -1; } if (seek > 0) { if (lseek(output_fd, seek * block_size, SEEK_SET) < 0) { - fprintf(stderr, "Unable to seek %lu bytes.\n", seek * block_size); + warnln("Unable to seek {} bytes.", seek * block_size); return -1; } } @@ -195,7 +195,7 @@ int main(int argc, char** argv) while (1) { nread = read(input_fd, buffer, block_size); if (nread < 0) { - fprintf(stderr, "Cannot read from the input.\n"); + warnln("Cannot read from the input."); break; } else if (nread == 0) { break; @@ -212,7 +212,7 @@ int main(int argc, char** argv) nwritten = write(output_fd, buffer, nread); if (nwritten < 0) { - fprintf(stderr, "Cannot write to the output.\n"); + warnln("Cannot write to the output."); break; } else if (nwritten == 0) { break; @@ -233,9 +233,9 @@ int main(int argc, char** argv) } if (status == Default) { - fprintf(stderr, "%lu+%lu blocks in\n", total_blocks_in, partial_blocks_in); - fprintf(stderr, "%lu+%lu blocks out\n", total_blocks_out, partial_blocks_out); - fprintf(stderr, "%lu bytes copied.\n", total_bytes_copied); + warnln("{}+{} blocks in", total_blocks_in, partial_blocks_in); + warnln("{}+{} blocks out", total_blocks_out, partial_blocks_out); + warnln("{} bytes copied.", total_bytes_copied); } free(buffer); diff --git a/Userland/Utilities/ddate.cpp b/Userland/Utilities/ddate.cpp index 09fae4abce..8d2ed07653 100644 --- a/Userland/Utilities/ddate.cpp +++ b/Userland/Utilities/ddate.cpp @@ -107,7 +107,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) } auto date = Core::DateTime::from_timestamp(time(nullptr)); - printf("Today is %s\n", DiscordianDate(date).to_string().characters()); + outln("Today is {}", DiscordianDate(date).to_string()); return 0; } diff --git a/Userland/Utilities/df.cpp b/Userland/Utilities/df.cpp index b0620f5090..91222420c6 100644 --- a/Userland/Utilities/df.cpp +++ b/Userland/Utilities/df.cpp @@ -13,7 +13,6 @@ #include <LibCore/ArgsParser.h> #include <LibCore/File.h> #include <inttypes.h> -#include <stdio.h> #include <stdlib.h> static bool flag_human_readable = false; @@ -37,14 +36,14 @@ int main(int argc, char** argv) auto file = Core::File::construct("/proc/df"); if (!file->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Failed to open /proc/df: %s\n", file->error_string()); + warnln("Failed to open {}: {}", file->name(), file->error_string()); return 1; } if (flag_human_readable) { - printf("Filesystem Size Used Available Mount point\n"); + outln("Filesystem Size Used Available Mount point"); } else { - printf("Filesystem Blocks Used Available Mount point\n"); + outln("Filesystem Blocks Used Available Mount point"); } auto file_contents = file->read_all(); @@ -61,20 +60,20 @@ int main(int argc, char** argv) auto block_size = fs_object.get("block_size").to_u64(); auto mount_point = fs_object.get("mount_point").to_string(); - printf("%-10s", fs.characters()); + out("{:10}", fs); if (flag_human_readable) { - printf("%10s ", human_readable_size(total_block_count * block_size).characters()); - printf("%10s ", human_readable_size((total_block_count - free_block_count) * block_size).characters()); - printf("%10s ", human_readable_size(free_block_count * block_size).characters()); + out("{:>10} ", human_readable_size(total_block_count * block_size)); + out("{:>10} ", human_readable_size((total_block_count - free_block_count) * block_size)); + out("{:>10} ", human_readable_size(free_block_count * block_size)); } else { - printf("%10" PRIu64 " ", (uint64_t)total_block_count); - printf("%10" PRIu64 " ", (uint64_t)(total_block_count - free_block_count)); - printf("%10" PRIu64 " ", (uint64_t)free_block_count); + out("{:>10} ", (uint64_t)total_block_count); + out("{:>10} ", (uint64_t)(total_block_count - free_block_count)); + out("{:>10} ", (uint64_t)free_block_count); } - printf("%s", mount_point.characters()); - printf("\n"); + out("{}", mount_point); + outln(); }); return 0; diff --git a/Userland/Utilities/dmesg.cpp b/Userland/Utilities/dmesg.cpp index 6ddf7c431b..0703b080e6 100644 --- a/Userland/Utilities/dmesg.cpp +++ b/Userland/Utilities/dmesg.cpp @@ -25,13 +25,12 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) unveil(nullptr, nullptr); - auto f = Core::File::construct("/proc/dmesg"); - if (!f->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "open: failed to open /proc/dmesg: %s\n", f->error_string()); + auto file = Core::File::construct("/proc/dmesg"); + if (!file->open(Core::OpenMode::ReadOnly)) { + warnln("Failed to open {}: {}", file->name(), file->error_string()); return 1; } - const auto& b = f->read_all(); - for (size_t i = 0; i < b.size(); ++i) - putchar(b[i]); + auto buffer = file->read_all(); + out("{}", String::copy(buffer)); return 0; } diff --git a/Userland/Utilities/du.cpp b/Userland/Utilities/du.cpp index cc60dfa722..964eb0c7b9 100644 --- a/Userland/Utilities/du.cpp +++ b/Userland/Utilities/du.cpp @@ -136,7 +136,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep if (--max_depth >= 0 && S_ISDIR(path_stat.st_mode)) { auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir); if (di.has_error()) { - fprintf(stderr, "DirIterator: %s\n", di.error_string()); + warnln("DirIterator: {}", di.error_string()); return 1; } while (di.has_next()) { @@ -167,7 +167,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep size = size / block_size + (size % block_size != 0); if (du_option.time_type == DuOption::TimeType::NotUsed) - printf("%" PRIi64 "\t%s\n", size, path.characters()); + outln("{}\t{}", size, path); else { auto time = path_stat.st_mtime; switch (du_option.time_type) { @@ -181,7 +181,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep } const auto formatted_time = Core::DateTime::from_timestamp(time).to_string(); - printf("%" PRIi64 "\t%s\t%s\n", size, formatted_time.characters(), path.characters()); + outln("{}\t{}\t{}", size, formatted_time, path); } return 0; diff --git a/Userland/Utilities/echo.cpp b/Userland/Utilities/echo.cpp index a997622b11..a70caa9919 100644 --- a/Userland/Utilities/echo.cpp +++ b/Userland/Utilities/echo.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/String.h> #include <LibCore/ArgsParser.h> #include <stdio.h> #include <unistd.h> @@ -23,12 +24,8 @@ int main(int argc, char** argv) args_parser.add_positional_argument(values, "Values to print out", "string", Core::ArgsParser::Required::No); args_parser.parse(argc, argv); - for (size_t i = 0; i < values.size(); ++i) { - fputs(values[i], stdout); - if (i != values.size() - 1) - fputc(' ', stdout); - } + out("{}", String::join(' ', values)); if (!no_trailing_newline) - printf("\n"); + outln(); return 0; } diff --git a/Userland/Utilities/env.cpp b/Userland/Utilities/env.cpp index db580193cd..5e07641d83 100644 --- a/Userland/Utilities/env.cpp +++ b/Userland/Utilities/env.cpp @@ -57,7 +57,7 @@ int main(int argc, char** argv) if (new_argv.size() == 0) { for (auto entry = environ; *entry != nullptr; ++entry) - printf("%s\n", *entry); + outln("{}", *entry); return 0; } diff --git a/Userland/Utilities/fgrep.cpp b/Userland/Utilities/fgrep.cpp index e9a32ce004..c4ddfeaa8f 100644 --- a/Userland/Utilities/fgrep.cpp +++ b/Userland/Utilities/fgrep.cpp @@ -5,6 +5,7 @@ */ #include <AK/Assertions.h> +#include <AK/Format.h> #include <stdio.h> #include <string.h> #include <unistd.h> @@ -12,7 +13,7 @@ int main(int argc, char** argv) { if (argc < 2) { - printf("usage: fgrep <str>\n"); + warnln("usage: fgrep <str>"); return 0; } for (;;) { diff --git a/Userland/Utilities/find.cpp b/Userland/Utilities/find.cpp index 5da5f23962..2e1639badc 100644 --- a/Userland/Utilities/find.cpp +++ b/Userland/Utilities/find.cpp @@ -5,6 +5,7 @@ */ #include <AK/Assertions.h> +#include <AK/CheckedFormatString.h> #include <AK/LexicalPath.h> #include <AK/NonnullOwnPtr.h> #include <AK/OwnPtr.h> @@ -23,16 +24,13 @@ bool g_follow_symlinks = false; bool g_there_was_an_error = false; bool g_have_seen_action_command = false; -[[noreturn]] static void fatal_error(const char* format, ...) +template<typename... Parameters> +[[noreturn]] static void fatal_error(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters) { - fputs("\033[31m", stderr); - - va_list ap; - va_start(ap, format); - vfprintf(stderr, format, ap); - va_end(ap); - - fputs("\033[0m\n", stderr); + warn("\033[31m"); + warn(move(fmtstr), parameters...); + warn("\033[0m"); + warnln(); exit(1); } @@ -67,7 +65,7 @@ public: { StringView type = arg; if (type.length() != 1 || !StringView("bcdlpfs").contains(type[0])) - fatal_error("Invalid mode: \033[1m%s", arg); + fatal_error("Invalid mode: \033[1m{}", arg); m_type = type[0]; } @@ -105,7 +103,7 @@ public: { auto number = StringView(arg).to_uint(); if (!number.has_value()) - fatal_error("Invalid number: \033[1m%s", arg); + fatal_error("Invalid number: \033[1m{}", arg); m_links = number.value(); } @@ -128,7 +126,7 @@ public: // Attempt to parse it as decimal UID. auto number = StringView(arg).to_uint(); if (!number.has_value()) - fatal_error("Invalid user: \033[1m%s", arg); + fatal_error("Invalid user: \033[1m{}", arg); m_uid = number.value(); } } @@ -152,7 +150,7 @@ public: // Attempt to parse it as decimal GID. auto number = StringView(arg).to_int(); if (!number.has_value()) - fatal_error("Invalid group: \033[1m%s", arg); + fatal_error("Invalid group: \033[1m{}", arg); m_gid = number.value(); } } @@ -177,7 +175,7 @@ public: } auto number = view.to_uint(); if (!number.has_value()) - fatal_error("Invalid size: \033[1m%s", arg); + fatal_error("Invalid size: \033[1m{}", arg); m_size = number.value(); } @@ -224,7 +222,7 @@ public: private: virtual bool evaluate(const char* file_path) const override { - printf("%s%c", file_path, m_terminator); + out("{}{}", file_path, m_terminator); return true; } @@ -354,7 +352,7 @@ static OwnPtr<Command> parse_simple_command(char* argv[]) command_argv.append(argv[optind]); return make<ExecCommand>(move(command_argv)); } else { - fatal_error("Unsupported command \033[1m%s", argv[optind]); + fatal_error("Unsupported command \033[1m{}", argv[optind]); } } @@ -467,7 +465,7 @@ static void walk_tree(const char* root_path, Command& command) } if (dir_iterator.has_error()) { - fprintf(stderr, "%s: %s\n", root_path, dir_iterator.error_string()); + warnln("{}: {}", root_path, dir_iterator.error_string()); g_there_was_an_error = true; } } diff --git a/Userland/Utilities/flock.cpp b/Userland/Utilities/flock.cpp index e63e248a5e..f8678e7ed9 100644 --- a/Userland/Utilities/flock.cpp +++ b/Userland/Utilities/flock.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <errno.h> #include <spawn.h> #include <stdio.h> @@ -14,7 +15,7 @@ int main(int argc, char** argv) { if (argc < 3) { - printf("usage: flock <path> <command...>\n"); + warnln("usage: flock <path> <command...>"); return 0; } diff --git a/Userland/Utilities/functrace.cpp b/Userland/Utilities/functrace.cpp index 98aa5555f4..daca7c00b9 100644 --- a/Userland/Utilities/functrace.cpp +++ b/Userland/Utilities/functrace.cpp @@ -30,7 +30,7 @@ static bool g_should_output_color = false; static void handle_sigint(int) { - printf("Debugger: SIGINT\n"); + outln("Debugger: SIGINT"); // The destructor of DebugSession takes care of detaching g_debug_session = nullptr; @@ -47,7 +47,7 @@ static void print_function_call(String function_name, size_t depth) static void print_syscall(PtraceRegisters& regs, size_t depth) { for (size_t i = 0; i < depth; ++i) { - printf(" "); + out(" "); } const char* begin_color = g_should_output_color ? "\033[34;1m" : ""; const char* end_color = g_should_output_color ? "\033[0m" : ""; diff --git a/Userland/Utilities/grep.cpp b/Userland/Utilities/grep.cpp index a7eef6c56d..76da12e437 100644 --- a/Userland/Utilities/grep.cpp +++ b/Userland/Utilities/grep.cpp @@ -26,9 +26,9 @@ enum class BinaryFileMode { template<typename... Ts> void fail(StringView format, Ts... args) { - fprintf(stderr, "\x1b[31m"); + warn("\x1b[31m"); warnln(format, forward<Ts>(args)...); - fprintf(stderr, "\x1b[0m"); + warn("\x1b[0m"); abort(); } diff --git a/Userland/Utilities/gron.cpp b/Userland/Utilities/gron.cpp index 67c27149ce..58bf1e2c7b 100644 --- a/Userland/Utilities/gron.cpp +++ b/Userland/Utilities/gron.cpp @@ -42,13 +42,13 @@ int main(int argc, char** argv) } if (argc != 2 || !strcmp(argv[1], "--help")) { - fprintf(stderr, "usage: gron <file>\n"); - fprintf(stderr, "Print each value in a JSON file with its fully expanded key.\n"); + warnln("usage: gron <file>"); + warnln("Print each value in a JSON file with its fully expanded key."); return 0; } auto file = Core::File::construct(argv[1]); if (!file->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Couldn't open %s for reading: %s\n", argv[1], file->error_string()); + warnln("Failed to open {}: {}", file->name(), file->error_string()); return 1; } @@ -79,19 +79,19 @@ int main(int argc, char** argv) static void print(const String& name, const JsonValue& value, Vector<String>& trail) { for (size_t i = 0; i < trail.size(); ++i) - printf("%s", trail[i].characters()); + out("{}", trail[i]); - printf("%s%s%s = ", color_name, name.characters(), color_off); + out("{}{}{} = ", color_name, name, color_off); if (value.is_object()) { - printf("%s{}%s;\n", color_brace, color_off); + outln("{}{{}}{};", color_brace, color_off); trail.append(String::formatted("{}{}{}.", color_name, name, color_off)); value.as_object().for_each_member([&](auto& on, auto& ov) { print(on, ov, trail); }); trail.take_last(); return; } if (value.is_array()) { - printf("%s[]%s;\n", color_brace, color_off); + outln("{}[]{};", color_brace, color_off); trail.append(String::formatted("{}{}{}", color_name, name, color_off)); for (int i = 0; i < value.as_array().size(); ++i) { auto element_name = String::formatted("{}{}[{}{}{}{}{}]{}", color_off, color_brace, color_off, color_index, i, color_off, color_brace, color_off); @@ -102,18 +102,18 @@ static void print(const String& name, const JsonValue& value, Vector<String>& tr } switch (value.type()) { case JsonValue::Type::Null: - printf("%s", color_null); + out("{}", color_null); break; case JsonValue::Type::Bool: - printf("%s", color_bool); + out("{}", color_bool); break; case JsonValue::Type::String: - printf("%s", color_string); + out("{}", color_string); break; default: - printf("%s", color_index); + out("{}", color_index); break; } - printf("%s%s;\n", value.serialized<StringBuilder>().characters(), color_off); + outln("{}{};", value.serialized<StringBuilder>(), color_off); } diff --git a/Userland/Utilities/head.cpp b/Userland/Utilities/head.cpp index ad2a095980..e380c876a9 100644 --- a/Userland/Utilities/head.cpp +++ b/Userland/Utilities/head.cpp @@ -78,16 +78,16 @@ int head(const String& filename, bool print_filename, ssize_t line_count, ssize_ } else { fd = open(filename.characters(), O_RDONLY); if (fd < 0) { - fprintf(stderr, "can't open %s for reading: %s\n", filename.characters(), strerror(errno)); + warnln("Failed to open {}: {}", filename, strerror(errno)); return 1; } } if (print_filename) { if (is_stdin) { - puts("==> standard input <=="); + outln("==> standard input <=="); } else { - printf("==> %s <==\n", filename.characters()); + outln("==> {} <==", filename); } } diff --git a/Userland/Utilities/hexdump.cpp b/Userland/Utilities/hexdump.cpp index a587fdce9a..f817d20b59 100644 --- a/Userland/Utilities/hexdump.cpp +++ b/Userland/Utilities/hexdump.cpp @@ -37,15 +37,15 @@ int main(int argc, char** argv) auto print_line = [&] { for (size_t i = 0; i < 16; ++i) { if (i < line.size()) - printf("%02x ", line[i]); + out("{:02x} ", line[i]); else - printf(" "); + out(" "); if (i == 7) - printf(" "); + out(" "); } - printf(" "); + out(" "); for (size_t i = 0; i < 16; ++i) { if (i < line.size() && isprint(line[i])) diff --git a/Userland/Utilities/host.cpp b/Userland/Utilities/host.cpp index 0c8139dcb3..0683dbb867 100644 --- a/Userland/Utilities/host.cpp +++ b/Userland/Utilities/host.cpp @@ -35,22 +35,22 @@ int main(int argc, char** argv) // Okay, let's do a reverse lookup. auto* hostent = gethostbyaddr(&addr.sin_addr, sizeof(in_addr), AF_INET); if (!hostent) { - fprintf(stderr, "Reverse lookup failed for '%s'\n", name_or_ip); + warnln("Reverse lookup failed for '{}'", name_or_ip); return 1; } - printf("%s is %s\n", name_or_ip, hostent->h_name); + outln("{} is {}", name_or_ip, hostent->h_name); return 0; } auto* hostent = gethostbyname(name_or_ip); if (!hostent) { - fprintf(stderr, "Lookup failed for '%s'\n", name_or_ip); + warnln("Lookup failed for '{}'", name_or_ip); return 1; } char buffer[INET_ADDRSTRLEN]; const char* ip_str = inet_ntop(AF_INET, hostent->h_addr_list[0], buffer, sizeof(buffer)); - printf("%s is %s\n", name_or_ip, ip_str); + outln("{} is {}", name_or_ip, ip_str); return 0; } diff --git a/Userland/Utilities/hostname.cpp b/Userland/Utilities/hostname.cpp index d7111e5134..4694480903 100644 --- a/Userland/Utilities/hostname.cpp +++ b/Userland/Utilities/hostname.cpp @@ -25,10 +25,10 @@ int main(int argc, char** argv) perror("gethostname"); return 1; } - printf("%s\n", buffer); + outln("{}", buffer); } else { if (strlen(hostname) >= HOST_NAME_MAX) { - fprintf(stderr, "Hostname must be less than %i characters\n", HOST_NAME_MAX); + warnln("Hostname must be less than {} characters", HOST_NAME_MAX); return 1; } sethostname(hostname, strlen(hostname)); diff --git a/Userland/Utilities/id.cpp b/Userland/Utilities/id.cpp index b9c66d442e..cfba5e4b1c 100644 --- a/Userland/Utilities/id.cpp +++ b/Userland/Utilities/id.cpp @@ -48,12 +48,12 @@ int main(int argc, char** argv) args_parser.parse(argc, argv); if (flag_print_name && !(flag_print_uid || flag_print_gid || flag_print_gid_all)) { - fprintf(stderr, "cannot print only names or real IDs in default format\n"); + warnln("cannot print only names or real IDs in default format"); return 1; } if (flag_print_uid + flag_print_gid + flag_print_gid_all > 1) { - fprintf(stderr, "cannot print \"only\" of more than one choice\n"); + warnln("cannot print \"only\" of more than one choice"); return 1; } @@ -65,9 +65,9 @@ static bool print_uid_object(uid_t uid) { if (flag_print_name) { struct passwd* pw = getpwuid(uid); - printf("%s", pw ? pw->pw_name : "n/a"); + out("{}", pw ? pw->pw_name : "n/a"); } else - printf("%u", uid); + out("{}", uid); return true; } @@ -76,9 +76,9 @@ static bool print_gid_object(gid_t gid) { if (flag_print_name) { struct group* gr = getgrgid(gid); - printf("%s", gr ? gr->gr_name : "n/a"); + out("{}", gr ? gr->gr_name : "n/a"); } else - printf("%u", gid); + out("{}", gid); return true; } @@ -97,11 +97,11 @@ static bool print_gid_list() for (int g = 0; g < extra_gid_count; ++g) { auto* gr = getgrgid(extra_gids[g]); if (flag_print_name && gr) - printf("%s", gr->gr_name); + out("{}", gr->gr_name); else - printf("%u", extra_gids[g]); + out("{}", extra_gids[g]); if (g != extra_gid_count - 1) - printf(" "); + out(" "); } } return true; @@ -114,7 +114,7 @@ static bool print_full_id_list() struct passwd* pw = getpwuid(uid); struct group* gr = getgrgid(gid); - printf("uid=%u(%s) gid=%u(%s)", uid, pw ? pw->pw_name : "n/a", gid, gr ? gr->gr_name : "n/a"); + out("uid={}({}) gid={}({})", uid, pw ? pw->pw_name : "n/a", gid, gr ? gr->gr_name : "n/a"); int extra_gid_count = getgroups(0, nullptr); if (extra_gid_count) { @@ -124,15 +124,15 @@ static bool print_full_id_list() perror("\ngetgroups"); return false; } - printf(" groups="); + out(" groups="); for (int g = 0; g < extra_gid_count; ++g) { auto* gr = getgrgid(extra_gids[g]); if (gr) - printf("%u(%s)", extra_gids[g], gr->gr_name); + out("{}({})", extra_gids[g], gr->gr_name); else - printf("%u", extra_gids[g]); + out("{}", extra_gids[g]); if (g != extra_gid_count - 1) - printf(","); + out(","); } } return true; @@ -154,6 +154,6 @@ static int print_id_objects() return 1; } - printf("\n"); + outln(); return 0; } diff --git a/Userland/Utilities/ifconfig.cpp b/Userland/Utilities/ifconfig.cpp index 18118c3645..bdc7ccbcfc 100644 --- a/Userland/Utilities/ifconfig.cpp +++ b/Userland/Utilities/ifconfig.cpp @@ -39,7 +39,7 @@ int main(int argc, char** argv) auto file = Core::File::construct("/proc/net/adapters"); if (!file->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Error: %s\n", file->error_string()); + outln("Failed to open {}: {}", file->name(), file->error_string()); return 1; } @@ -61,21 +61,21 @@ int main(int argc, char** argv) auto bytes_out = if_object.get("bytes_out").to_u32(); auto mtu = if_object.get("mtu").to_u32(); - printf("%s:\n", name.characters()); - printf("\tmac: %s\n", mac_address.characters()); - printf("\tipv4: %s\n", ipv4_address.characters()); - printf("\tnetmask: %s\n", netmask.characters()); - printf("\tgateway: %s\n", gateway.characters()); - printf("\tclass: %s\n", class_name.characters()); - printf("\tRX: %u packets %u bytes (%s)\n", packets_in, bytes_in, human_readable_size(bytes_in).characters()); - printf("\tTX: %u packets %u bytes (%s)\n", packets_out, bytes_out, human_readable_size(bytes_out).characters()); - printf("\tMTU: %u\n", mtu); - printf("\n"); + outln("{}:", name); + outln("\tmac: {}", mac_address); + outln("\tipv4: {}", ipv4_address); + outln("\tnetmask: {}", netmask); + outln("\tgateway: {}", gateway); + outln("\tclass: {}", class_name); + outln("\tRX: {} packets {} bytes ({})", packets_in, bytes_in, human_readable_size(bytes_in)); + outln("\tTX: {} packets {} bytes ({})", packets_out, bytes_out, human_readable_size(bytes_out)); + outln("\tMTU: {}", mtu); + outln(); }); } else { if (!value_adapter) { - fprintf(stderr, "No network adapter was specified.\n"); + warnln("No network adapter was specified."); return 1; } @@ -85,7 +85,7 @@ int main(int argc, char** argv) auto address = IPv4Address::from_string(value_ipv4); if (!address.has_value()) { - fprintf(stderr, "Invalid IPv4 address: '%s'\n", value_ipv4); + warnln("Invalid IPv4 address: '{}'", value_ipv4); return 1; } @@ -100,7 +100,7 @@ int main(int argc, char** argv) bool fits = ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ); if (!fits) { - fprintf(stderr, "Interface name '%s' is too long\n", ifname.characters()); + warnln("Interface name '{}' is too long", ifname); return 1; } ifr.ifr_addr.sa_family = AF_INET; @@ -117,7 +117,7 @@ int main(int argc, char** argv) auto address = IPv4Address::from_string(value_mask); if (!address.has_value()) { - fprintf(stderr, "Invalid IPv4 mask: '%s'\n", value_mask); + warnln("Invalid IPv4 mask: '{}'", value_mask); return 1; } @@ -132,7 +132,7 @@ int main(int argc, char** argv) bool fits = ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ); if (!fits) { - fprintf(stderr, "Interface name '%s' is too long\n", ifname.characters()); + warnln("Interface name '{}' is too long", ifname); return 1; } ifr.ifr_netmask.sa_family = AF_INET; diff --git a/Userland/Utilities/ini.cpp b/Userland/Utilities/ini.cpp index c51736a281..72db021dca 100644 --- a/Userland/Utilities/ini.cpp +++ b/Userland/Utilities/ini.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Linus Groh <linusg@serenityos.org> + * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -30,7 +30,7 @@ int main(int argc, char** argv) args_parser.parse(argc, argv); if (!Core::File::exists(path)) { - fprintf(stderr, "File does not exist: '%s'\n", path); + warnln("File does not exist: '{}'", path); return 1; } @@ -44,7 +44,7 @@ int main(int argc, char** argv) auto value = config->read_entry(group, key); if (!value.is_empty()) - printf("%s\n", value.characters()); + outln("{}", value); return 0; } diff --git a/Userland/Utilities/kill.cpp b/Userland/Utilities/kill.cpp index 28865c1871..01e4d22901 100644 --- a/Userland/Utilities/kill.cpp +++ b/Userland/Utilities/kill.cpp @@ -15,7 +15,7 @@ static void print_usage_and_exit() { - printf("usage: kill [-signal] <PID>\n"); + warnln("usage: kill [-signal] <PID>"); exit(1); } @@ -57,14 +57,14 @@ int main(int argc, char** argv) number = StringView(&argv[1][1]).to_uint(); if (!number.has_value()) { - printf("'%s' is not a valid signal name or number\n", &argv[1][1]); + warnln("'{}' is not a valid signal name or number", &argv[1][1]); return 2; } signum = number.value(); } auto pid_opt = String(argv[pid_argi]).to_int(); if (!pid_opt.has_value()) { - printf("'%s' is not a valid PID\n", argv[pid_argi]); + warnln("'{}' is not a valid PID", argv[pid_argi]); return 3; } pid_t pid = pid_opt.value(); diff --git a/Userland/Utilities/killall.cpp b/Userland/Utilities/killall.cpp index 8dea645cfb..59c877609c 100644 --- a/Userland/Utilities/killall.cpp +++ b/Userland/Utilities/killall.cpp @@ -13,7 +13,7 @@ static void print_usage_and_exit() { - printf("usage: killall [-signal] process_name\n"); + warnln("usage: killall [-signal] process_name"); exit(1); } @@ -60,7 +60,7 @@ int main(int argc, char** argv) number = String(&argv[1][1]).to_uint(); if (!number.has_value()) { - printf("'%s' is not a valid signal name or number\n", &argv[1][1]); + warnln("'{}' is not a valid signal name or number", &argv[1][1]); return 2; } signum = number.value(); diff --git a/Userland/Utilities/lsirq.cpp b/Userland/Utilities/lsirq.cpp index 4b30c893ea..87323c181c 100644 --- a/Userland/Utilities/lsirq.cpp +++ b/Userland/Utilities/lsirq.cpp @@ -28,7 +28,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) auto proc_interrupts = Core::File::construct("/proc/interrupts"); if (!proc_interrupts->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Error: %s\n", proc_interrupts->error_string()); + warnln("Error: {}", proc_interrupts->error_string()); return 1; } @@ -37,7 +37,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) return 1; } - printf("%4s %-10s\n", " ", "CPU0"); + outln(" CPU0"); auto file_contents = proc_interrupts->read_all(); auto json = JsonValue::from_string(file_contents); VERIFY(json.has_value()); @@ -48,8 +48,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) auto controller = handler.get("controller").to_string(); auto call_count = handler.get("call_count").to_string(); - printf("%4s: %-10s %-10s %-30s\n", - interrupt.characters(), call_count.characters(), controller.characters(), purpose.characters()); + outln("{:>4}: {:10} {:10} {:30}", interrupt, call_count, controller, purpose); }); return 0; diff --git a/Userland/Utilities/lsof.cpp b/Userland/Utilities/lsof.cpp index 330d6363ba..72fd20c0dd 100644 --- a/Userland/Utilities/lsof.cpp +++ b/Userland/Utilities/lsof.cpp @@ -66,7 +66,7 @@ static Vector<OpenFile> get_open_files_by_pid(pid_t pid) { auto file = Core::File::open(String::formatted("/proc/{}/fds", pid), Core::OpenMode::ReadOnly); if (file.is_error()) { - printf("lsof: PID %d: %s\n", pid, file.error().characters()); + outln("lsof: PID {}: {}", pid, file.error()); return Vector<OpenFile>(); } auto data = file.value()->read_all(); @@ -95,7 +95,7 @@ static Vector<OpenFile> get_open_files_by_pid(pid_t pid) static void display_entry(const OpenFile& file, const Core::ProcessStatistics& statistics) { - printf("%-28s %4d %4d %-10s %4d %s\n", statistics.name.characters(), file.pid, statistics.pgid, statistics.username.characters(), file.fd, file.full_name.characters()); + outln("{:28} {:>4} {:>4} {:10} {:>4} {}", statistics.name, file.pid, statistics.pgid, statistics.username, file.fd, file.full_name); } int main(int argc, char* argv[]) @@ -145,7 +145,7 @@ int main(int argc, char* argv[]) arg_uid_int = arg.value(); } - printf("%-28s %4s %4s %-10s %4s %s\n", "COMMAND", "PID", "PGID", "USER", "FD", "NAME"); + outln("{:28} {:>4} {:>4} {:10} {:>4} {}", "COMMAND", "PID", "PGID", "USER", "FD", "NAME"); auto processes = Core::ProcessStatisticsReader::get_all(); if (!processes.has_value()) return 1; diff --git a/Userland/Utilities/lspci.cpp b/Userland/Utilities/lspci.cpp index 660f4822b3..63453f2c1f 100644 --- a/Userland/Utilities/lspci.cpp +++ b/Userland/Utilities/lspci.cpp @@ -56,7 +56,7 @@ int main(int argc, char** argv) auto proc_pci = Core::File::construct("/proc/pci"); if (!proc_pci->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Error: %s\n", proc_pci->error_string()); + warnln("Failed to open {}: {}", proc_pci->name(), proc_pci->error_string()); return 1; } diff --git a/Userland/Utilities/man.cpp b/Userland/Utilities/man.cpp index 9af4e02a23..28b637649e 100644 --- a/Userland/Utilities/man.cpp +++ b/Userland/Utilities/man.cpp @@ -70,7 +70,7 @@ int main(int argc, char* argv[]) } } if (!section) { - fprintf(stderr, "No man page for %s\n", name); + warnln("No man page for {}", name); exit(1); } } @@ -92,11 +92,11 @@ int main(int argc, char* argv[]) auto buffer = file->read_all(); auto source = String::copy(buffer); - printf("%s(%s)\t\tSerenityOS manual\n", name, section); + outln("{}({})\t\tSerenityOS manual", name, section); auto document = Markdown::Document::parse(source); VERIFY(document); String rendered = document->render_for_terminal(view_width); - printf("%s", rendered.characters()); + out("{}", rendered); } diff --git a/Userland/Utilities/md.cpp b/Userland/Utilities/md.cpp index 1a74f153c2..7bda9bd2cf 100644 --- a/Userland/Utilities/md.cpp +++ b/Userland/Utilities/md.cpp @@ -51,7 +51,7 @@ int main(int argc, char* argv[]) success = file->open(Core::OpenMode::ReadOnly); } if (!success) { - fprintf(stderr, "Error: %s\n", file->error_string()); + warnln("Error: {}", file->error_string()); return 1; } @@ -67,10 +67,10 @@ int main(int argc, char* argv[]) auto document = Markdown::Document::parse(input); if (!document) { - fprintf(stderr, "Error parsing\n"); + warnln("Error parsing"); return 1; } String res = html ? document->render_to_html() : document->render_for_terminal(view_width); - printf("%s", res.characters()); + out("{}", res); } diff --git a/Userland/Utilities/mkdir.cpp b/Userland/Utilities/mkdir.cpp index 0a3e4c57dd..05752966b9 100644 --- a/Userland/Utilities/mkdir.cpp +++ b/Userland/Utilities/mkdir.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> - * Copyright (c) 2020, Linus Groh <linusg@serenityos.org> + * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -61,7 +61,7 @@ int main(int argc, char** argv) } } else { if (!S_ISDIR(st.st_mode)) { - fprintf(stderr, "mkdir: cannot create directory '%s': not a directory\n", path.characters()); + warnln("mkdir: cannot create directory '{}': not a directory", path); has_errors = true; break; } diff --git a/Userland/Utilities/mknod.cpp b/Userland/Utilities/mknod.cpp index e86da4147f..5f68894d8f 100644 --- a/Userland/Utilities/mknod.cpp +++ b/Userland/Utilities/mknod.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> @@ -16,7 +17,7 @@ constexpr unsigned encoded_device(unsigned major, unsigned minor) static int usage() { - printf("usage: mknod <name> <c|b|p> [<major> <minor>]\n"); + warnln("usage: mknod <name> <c|b|p> [<major> <minor>]"); return 0; } diff --git a/Userland/Utilities/more.cpp b/Userland/Utilities/more.cpp index f7afc6007b..ef115ff167 100644 --- a/Userland/Utilities/more.cpp +++ b/Userland/Utilities/more.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <fcntl.h> #include <stdio.h> #include <sys/ioctl.h> @@ -13,11 +14,11 @@ static int key_fd; static void wait_for_key() { - printf("\033[7m--[ more ]--\033[0m"); + out("\033[7m--[ more ]--\033[0m"); fflush(stdout); char dummy; [[maybe_unused]] auto rc = read(key_fd, &dummy, 1); - printf("\n"); + outln(); } int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) @@ -43,7 +44,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) auto* str = fgets(buffer, sizeof(buffer), stdin); if (!str) break; - printf("%s", str); + out("{}", str); ++lines_printed; if ((lines_printed % (ws.ws_row - 1)) == 0) { wait_for_key(); diff --git a/Userland/Utilities/mount.cpp b/Userland/Utilities/mount.cpp index bf513e9544..93cc57deda 100644 --- a/Userland/Utilities/mount.cpp +++ b/Userland/Utilities/mount.cpp @@ -36,7 +36,7 @@ static int parse_options(const StringView& options) else if (part == "remount") flags |= MS_REMOUNT; else - fprintf(stderr, "Ignoring invalid option: %s\n", part.to_string().characters()); + warnln("Ignoring invalid option: {}", part); } return flags; } @@ -69,7 +69,7 @@ static bool mount_all() auto fstab = Core::File::construct("/etc/fstab"); if (!fstab->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Failed to open /etc/fstab: %s\n", fstab->error_string()); + warnln("Failed to open {}: {}", fstab->name(), fstab->error_string()); return false; } @@ -83,7 +83,7 @@ static bool mount_all() Vector<String> parts = line.split('\t'); if (parts.size() < 3) { - fprintf(stderr, "Invalid fstab entry: %s\n", line.characters()); + warnln("Invalid fstab entry: {}", line); all_ok = false; continue; } @@ -105,7 +105,7 @@ static bool mount_all() int rc = mount(fd, mountpoint, fstype, flags); if (rc != 0) { - fprintf(stderr, "Failed to mount %s (FD: %d) (%s) on %s: %s\n", filename, fd, fstype, mountpoint, strerror(errno)); + warnln("Failed to mount {} (FD: {}) ({}) on {}: {}", filename, fd, fstype, mountpoint, strerror(errno)); all_ok = false; continue; } @@ -119,7 +119,7 @@ static bool print_mounts() // Output info about currently mounted filesystems. auto df = Core::File::construct("/proc/df"); if (!df->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Failed to open /proc/df: %s\n", df->error_string()); + warnln("Failed to open {}: {}", df->name(), df->error_string()); return false; } @@ -135,23 +135,23 @@ static bool print_mounts() auto readonly = fs_object.get("readonly").to_bool(); auto mount_flags = fs_object.get("mount_flags").to_int(); - printf("%s on %s type %s (", source.characters(), mount_point.characters(), class_name.characters()); + out("{} on {} type {} (", source, mount_point, class_name); if (readonly || mount_flags & MS_RDONLY) - printf("ro"); + out("ro"); else - printf("rw"); + out("rw"); if (mount_flags & MS_NODEV) - printf(",nodev"); + out(",nodev"); if (mount_flags & MS_NOEXEC) - printf(",noexec"); + out(",noexec"); if (mount_flags & MS_NOSUID) - printf(",nosuid"); + out(",nosuid"); if (mount_flags & MS_BIND) - printf(",bind"); + out(",bind"); - printf(")\n"); + outln(")"); }); return true; diff --git a/Userland/Utilities/mv.cpp b/Userland/Utilities/mv.cpp index ba9ce07ea9..6962a6a3e7 100644 --- a/Userland/Utilities/mv.cpp +++ b/Userland/Utilities/mv.cpp @@ -79,14 +79,14 @@ int main(int argc, char** argv) } rc = unlink(old_path); if (rc < 0) - fprintf(stderr, "mv: unlink '%s': %s\n", old_path, strerror(errno)); + warnln("mv: unlink '{}': {}", old_path, strerror(errno)); } else { warnln("mv: cannot move '{}' : {}", old_path, strerror(errno)); } } if (verbose && rc == 0) - printf("renamed '%s' -> '%s'\n", old_path, new_path); + outln("renamed '{}' -> '{}'", old_path, new_path); } return 0; diff --git a/Userland/Utilities/nl.cpp b/Userland/Utilities/nl.cpp index e4e59ceab3..c9752be16e 100644 --- a/Userland/Utilities/nl.cpp +++ b/Userland/Utilities/nl.cpp @@ -7,7 +7,7 @@ #include <AK/String.h> #include <AK/Vector.h> #include <LibCore/ArgsParser.h> - +#include <errno.h> #include <stdio.h> #include <string.h> @@ -61,7 +61,7 @@ int main(int argc, char** argv) for (auto& file : files) { FILE* file_pointer = fopen(file, "r"); if (!file_pointer) { - fprintf(stderr, "unable to open %s\n", file); + warnln("Failed to open {}: {}", file, strerror(errno)); continue; } file_pointers.append(file_pointer); @@ -78,20 +78,20 @@ int main(int argc, char** argv) if (previous_character == 0 || previous_character == '\n') { if (next_character == '\n' && number_style != NumberAllLines) { // Skip printing line count on empty lines. - printf("\n"); + outln(); continue; } if (number_style != NumberNoLines) - printf("%*d%s", number_width, (line_number += increment), separator); + out("{1:{0}}{2}", number_width, (line_number += increment), separator); else - printf("%*s", number_width, ""); + out("{1:{0}}", number_width, ""); } putchar(next_character); previous_character = next_character; } fclose(file_pointer); if (previous_character != '\n') - printf("\n"); // for cases where files have no trailing newline + outln(); // for cases where files have no trailing newline } return 0; } diff --git a/Userland/Utilities/pape.cpp b/Userland/Utilities/pape.cpp index a1f86788c5..d95def5993 100644 --- a/Userland/Utilities/pape.cpp +++ b/Userland/Utilities/pape.cpp @@ -15,20 +15,20 @@ static int handle_show_all() { Core::DirIterator di("/res/wallpapers", Core::DirIterator::SkipDots); if (di.has_error()) { - fprintf(stderr, "DirIterator: %s\n", di.error_string()); + warnln("DirIterator: {}", di.error_string()); return 1; } while (di.has_next()) { String name = di.next_path(); - printf("%s\n", name.characters()); + outln("{}", name); } return 0; } static int handle_show_current() { - printf("%s\n", GUI::Desktop::the().wallpaper().characters()); + outln("{}", GUI::Desktop::the().wallpaper()); return 0; } @@ -39,7 +39,7 @@ static int handle_set_pape(const String& name) builder.append(name); String path = builder.to_string(); if (!GUI::Desktop::the().set_wallpaper(path)) { - fprintf(stderr, "pape: Failed to set wallpaper %s\n", path.characters()); + warnln("pape: Failed to set wallpaper {}", path); return 1; } return 0; diff --git a/Userland/Utilities/pidof.cpp b/Userland/Utilities/pidof.cpp index 625c50287b..5f90e7ac0e 100644 --- a/Userland/Utilities/pidof.cpp +++ b/Userland/Utilities/pidof.cpp @@ -23,7 +23,7 @@ static int pid_of(const String& process_name, bool single_shot, bool omit_pid, p for (auto& it : processes.value()) { if (it.name == process_name) { if (!omit_pid || it.pid != pid) { - printf(" %d" + (displayed_at_least_one ? 0 : 1), it.pid); + out(displayed_at_least_one ? " {}" : "{}", it.pid); displayed_at_least_one = true; if (single_shot) @@ -33,7 +33,7 @@ static int pid_of(const String& process_name, bool single_shot, bool omit_pid, p } if (displayed_at_least_one) - printf("\n"); + outln(); return 0; } @@ -58,7 +58,7 @@ int main(int argc, char** argv) } else { auto number = StringView(omit_pid_value).to_uint(); if (!number.has_value()) { - fprintf(stderr, "Invalid value for -o\n"); + warnln("Invalid value for -o"); args_parser.print_usage(stderr, argv[0]); return 1; } diff --git a/Userland/Utilities/ping.cpp b/Userland/Utilities/ping.cpp index 3d0466f632..cc954bbaa5 100644 --- a/Userland/Utilities/ping.cpp +++ b/Userland/Utilities/ping.cpp @@ -45,7 +45,7 @@ int main(int argc, char** argv) } if (setgid(getgid()) || setuid(getuid())) { - fprintf(stderr, "Failed to drop privileges.\n"); + warnln("Failed to drop privileges."); return 1; } @@ -66,7 +66,7 @@ int main(int argc, char** argv) auto* hostent = gethostbyname(host); if (!hostent) { - printf("Lookup failed for '%s'\n", host); + warnln("Lookup failed for '{}'", host); return 1; } @@ -101,17 +101,18 @@ int main(int argc, char** argv) sighandler_t ret = signal(SIGINT, [](int) { int packet_loss = 100; - printf("\n--- %s ping statistics ---\n", host); + outln(); + outln("--- {} ping statistics ---", host); if (total_pings) packet_loss -= 100.0f * successful_pings / total_pings; - printf("%d packets transmitted, %d received, %d%% packet loss\n", + outln("{} packets transmitted, {} received, {}% packet loss", total_pings, successful_pings, packet_loss); int average_ms = 0; if (successful_pings) average_ms = total_ms / successful_pings; - printf("rtt min/avg/max = %d/%d/%d ms\n", min_ms, average_ms, max_ms); + outln("rtt min/avg/max = {}/{}/{} ms", min_ms, average_ms, max_ms); exit(0); }); @@ -153,7 +154,7 @@ int main(int argc, char** argv) rc = recvfrom(fd, &pong_packet, sizeof(PongPacket), 0, (struct sockaddr*)&peer_address, &peer_address_size); if (rc < 0) { if (errno == EAGAIN) { - printf("Request (seq=%u) timed out.\n", ntohs(ping_packet.header.un.echo.sequence)); + outln("Request (seq={}) timed out.", ntohs(ping_packet.header.un.echo.sequence)); break; } perror("recvfrom"); @@ -190,7 +191,7 @@ int main(int argc, char** argv) max_ms = ms; char addr_buf[INET_ADDRSTRLEN]; - printf("Pong from %s: id=%u, seq=%u%s, time=%dms\n", + outln("Pong from {}: id={}, seq={}{}, time={}ms", inet_ntop(AF_INET, &peer_address.sin_addr, addr_buf, sizeof(addr_buf)), ntohs(pong_packet.header.un.echo.id), ntohs(pong_packet.header.un.echo.sequence), diff --git a/Userland/Utilities/pmap.cpp b/Userland/Utilities/pmap.cpp index 9682fec115..862103560f 100644 --- a/Userland/Utilities/pmap.cpp +++ b/Userland/Utilities/pmap.cpp @@ -37,16 +37,16 @@ int main(int argc, char** argv) auto file = Core::File::construct(String::formatted("/proc/{}/vm", pid)); if (!file->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Error: %s\n", file->error_string()); + warnln("Failed to open {}: {}", file->name(), file->error_string()); return 1; } - printf("%s:\n", pid); + outln("{}:", pid); if (extended) { - printf("Address Size Resident Dirty Access VMObject Type Purgeable CoW Pages Name\n"); + outln("Address Size Resident Dirty Access VMObject Type Purgeable CoW Pages Name"); } else { - printf("Address Size Access Name\n"); + outln("Address Size Access Name"); } auto file_contents = file->read_all(); @@ -70,8 +70,8 @@ int main(int argc, char** argv) (map.get("shared").to_bool() ? "s" : "-"), (map.get("syscall").to_bool() ? "c" : "-")); - printf("%08x ", address); - printf("%10s ", size.characters()); + out("{:08x} ", address); + out("{:>10} ", size); if (extended) { auto resident = map.get("amount_resident").to_string(); auto dirty = map.get("amount_dirty").to_string(); @@ -80,18 +80,18 @@ int main(int argc, char** argv) vmobject = vmobject.substring(0, vmobject.length() - 8); auto purgeable = map.get("purgeable").to_string(); auto cow_pages = map.get("cow_pages").to_string(); - printf("%10s ", resident.characters()); - printf("%10s ", dirty.characters()); - printf("%-6s ", access.characters()); - printf("%-14s ", vmobject.characters()); - printf("%-10s ", purgeable.characters()); - printf("%10s ", cow_pages.characters()); + out("{:>10} ", resident); + out("{:>10} ", dirty); + out("{:6} ", access); + out("{:14} ", vmobject); + out("{:10} ", purgeable); + out("{:>10} ", cow_pages); } else { - printf("%-6s ", access.characters()); + out("{:6} ", access); } auto name = map.get("name").to_string(); - printf("%-20s", name.characters()); - printf("\n"); + out("{:20}", name); + outln(); } return 0; diff --git a/Userland/Utilities/pro.cpp b/Userland/Utilities/pro.cpp index 9b6da33ba3..16bd615304 100644 --- a/Userland/Utilities/pro.cpp +++ b/Userland/Utilities/pro.cpp @@ -179,7 +179,7 @@ int main(int argc, char** argv) URL url(url_str); if (!url.is_valid()) { - fprintf(stderr, "'%s' is not a valid URL\n", url_str); + warnln("'{}' is not a valid URL", url_str); return 1; } @@ -188,7 +188,7 @@ int main(int argc, char** argv) auto request = protocol_client->start_request(method, url.to_string(), request_headers, data ? StringView { data }.bytes() : ReadonlyBytes {}); if (!request) { - fprintf(stderr, "Failed to start request for '%s'\n", url_str); + warnln("Failed to start request for '{}'", url_str); return 1; } @@ -201,12 +201,12 @@ int main(int argc, char** argv) bool received_actual_headers = false; request->on_progress = [&](Optional<u32> maybe_total_size, u32 downloaded_size) { - fprintf(stderr, "\r\033[2K"); + warn("\r\033[2K"); if (maybe_total_size.has_value()) { - fprintf(stderr, "\033]9;%d;%d;\033\\", downloaded_size, maybe_total_size.value()); - fprintf(stderr, "Download progress: %s / %s", human_readable_size(downloaded_size).characters(), human_readable_size(maybe_total_size.value()).characters()); + warn("\033]9;{};{};\033\\", downloaded_size, maybe_total_size.value()); + warn("Download progress: {} / {}", human_readable_size(downloaded_size), human_readable_size(maybe_total_size.value())); } else { - fprintf(stderr, "Download progress: %s / ???", human_readable_size(downloaded_size).characters()); + warn("Download progress: {} / ???", human_readable_size(downloaded_size)); } gettimeofday(¤t_time, nullptr); @@ -215,7 +215,7 @@ int main(int argc, char** argv) auto time_diff_ms = time_diff.tv_sec * 1000 + time_diff.tv_usec / 1000; auto size_diff = downloaded_size - previous_downloaded_size; - fprintf(stderr, " at %s/s", human_readable_size(((float)size_diff / (float)time_diff_ms) * 1000).characters()); + warn(" at {}/s", human_readable_size(((float)size_diff / (float)time_diff_ms) * 1000)); if (time_diff_ms >= download_speed_rolling_average_time_in_ms) { previous_downloaded_size = previous_midpoint_downloaded_size; @@ -264,10 +264,10 @@ int main(int argc, char** argv) }; } request->on_finish = [&](bool success, auto) { - fprintf(stderr, "\033]9;-1;\033\\"); - fprintf(stderr, "\n"); + warn("\033]9;-1;\033\\"); + warnln(); if (!success) - fprintf(stderr, "Request failed :(\n"); + warnln("Request failed :("); loop.quit(0); }; diff --git a/Userland/Utilities/profile.cpp b/Userland/Utilities/profile.cpp index 6bce266bac..46c7fc8b3f 100644 --- a/Userland/Utilities/profile.cpp +++ b/Userland/Utilities/profile.cpp @@ -74,7 +74,7 @@ int main(int argc, char** argv) if (pid_argument || all_processes) { if (!(enable ^ disable ^ wait ^ free)) { - fprintf(stderr, "-p <PID> requires -e xor -d xor -w xor -f.\n"); + warnln("-p <PID> requires -e xor -d xor -w xor -f."); return 1; } diff --git a/Userland/Utilities/ps.cpp b/Userland/Utilities/ps.cpp index 6392dcbafa..068b905120 100644 --- a/Userland/Utilities/ps.cpp +++ b/Userland/Utilities/ps.cpp @@ -85,18 +85,18 @@ int main(int argc, char** argv) auto print_column = [](auto& column, auto& string) { if (!column.width) { - printf("%s", string.characters()); + out("{}", string); return; } if (column.alignment == Alignment::Right) - printf("%*s ", column.width, string.characters()); + out("{1:>{0}} ", column.width, string); else - printf("%-*s ", column.width, string.characters()); + out("{1:{0}} ", column.width, string); }; for (auto& column : columns) print_column(column, column.title); - printf("\n"); + outln(); auto processes = Core::ProcessStatisticsReader::get_all(); if (!processes.has_value()) @@ -132,7 +132,7 @@ int main(int argc, char** argv) for (auto& column : columns) print_column(column, column.buffer); - printf("\n"); + outln(); } return 0; diff --git a/Userland/Utilities/purge.cpp b/Userland/Utilities/purge.cpp index 47bb3b1484..fcbefd4493 100644 --- a/Userland/Utilities/purge.cpp +++ b/Userland/Utilities/purge.cpp @@ -33,6 +33,6 @@ int main(int argc, char** argv) perror("purge"); return 1; } - printf("Purged page count: %d\n", purged_page_count); + outln("Purged page count: {}", purged_page_count); return 0; } diff --git a/Userland/Utilities/readelf.cpp b/Userland/Utilities/readelf.cpp index 4f5fddea3d..a95ad827e7 100644 --- a/Userland/Utilities/readelf.cpp +++ b/Userland/Utilities/readelf.cpp @@ -413,14 +413,14 @@ int main(int argc, char** argv) ELF::Image elf_image(elf_image_data); if (!elf_image.is_valid()) { - fprintf(stderr, "File is not a valid ELF object\n"); + warnln("File is not a valid ELF object"); return -1; } String interpreter_path; if (!ELF::validate_program_headers(*(const Elf32_Ehdr*)elf_image_data.data(), elf_image_data.size(), (const u8*)elf_image_data.data(), elf_image_data.size(), &interpreter_path)) { - fprintf(stderr, "Invalid ELF headers\n"); + warnln("Invalid ELF headers"); return -1; } @@ -431,7 +431,7 @@ int main(int argc, char** argv) if (elf_image.is_dynamic()) { if (interpreter_path.is_null()) { interpreter_path = "/usr/lib/Loader.so"; - fprintf(stderr, "Warning: Dynamic ELF object has no interpreter path. Using: %s\n", interpreter_path.characters()); + warnln("Warning: Dynamic ELF object has no interpreter path. Using: {}", interpreter_path); } auto interpreter_file_or_error = MappedFile::map(interpreter_path); @@ -446,7 +446,7 @@ int main(int argc, char** argv) ELF::Image interpreter_image(interpreter_image_data); if (!interpreter_image.is_valid()) { - fprintf(stderr, "ELF interpreter image is invalid\n"); + warnln("ELF interpreter image is invalid"); return -1; } @@ -475,91 +475,92 @@ int main(int argc, char** argv) } if (display_elf_header) { - printf("ELF header:\n"); + outln("ELF header:"); - printf(" Magic: "); + out(" Magic: "); for (char i : StringView { header.e_ident, sizeof(header.e_ident) }) { if (isprint(i)) { - printf("%c ", i); + out("{:c} ", i); } else { - printf("%02x ", i); + out("{:02x} ", i); } } - printf("\n"); - - printf(" Type: %d (%s)\n", header.e_type, object_file_type_to_string(header.e_type)); - printf(" Machine: %u (%s)\n", header.e_machine, object_machine_type_to_string(header.e_machine)); - printf(" Version: 0x%x\n", header.e_version); - printf(" Entry point address: 0x%x\n", header.e_entry); - printf(" Start of program headers: %u (bytes into file)\n", header.e_phoff); - printf(" Start of section headers: %u (bytes into file)\n", header.e_shoff); - printf(" Flags: 0x%x\n", header.e_flags); - printf(" Size of this header: %u (bytes)\n", header.e_ehsize); - printf(" Size of program headers: %u (bytes)\n", header.e_phentsize); - printf(" Number of program headers: %u\n", header.e_phnum); - printf(" Size of section headers: %u (bytes)\n", header.e_shentsize); - printf(" Number of section headers: %u\n", header.e_shnum); - printf(" Section header string table index: %u\n", header.e_shstrndx); - printf("\n"); + outln(); + + outln(" Type: {} ({})", header.e_type, object_file_type_to_string(header.e_type)); + outln(" Machine: {} ({})", header.e_machine, object_machine_type_to_string(header.e_machine)); + outln(" Version: {:#x}", header.e_version); + outln(" Entry point address: {:#x}", header.e_entry); + outln(" Start of program headers: {} (bytes into file)", header.e_phoff); + outln(" Start of section headers: {} (bytes into file)", header.e_shoff); + outln(" Flags: {:#x}", header.e_flags); + outln(" Size of this header: {} (bytes)", header.e_ehsize); + outln(" Size of program headers: {} (bytes)", header.e_phentsize); + outln(" Number of program headers: {}", header.e_phnum); + outln(" Size of section headers: {} (bytes)", header.e_shentsize); + outln(" Number of section headers: {}", header.e_shnum); + outln(" Section header string table index: {}", header.e_shstrndx); + outln(); } if (display_section_headers) { if (!display_all) { - printf("There are %u section headers, starting at offset 0x%x:\n", header.e_shnum, header.e_shoff); - printf("\n"); + outln("There are {} section headers, starting at offset {:#x}:", header.e_shnum, header.e_shoff); + outln(); } if (!elf_image.section_count()) { - printf("There are no sections in this file.\n"); + outln("There are no sections in this file."); } else { - printf("Section Headers:\n"); - printf(" Name Type Address Offset Size Flags\n"); + outln("Section Headers:"); + outln(" Name Type Address Offset Size Flags"); elf_image.for_each_section([](const ELF::Image::Section& section) { - printf(" %-19s ", StringView(section.name()).to_string().characters()); - printf("%-15s ", object_section_header_type_to_string(section.type())); - printf("%08x ", section.address()); - printf("%08x ", section.offset()); - printf("%08x ", section.size()); - printf("%u", section.flags()); - printf("\n"); + out(" {:19} ", section.name()); + out("{:15} ", object_section_header_type_to_string(section.type())); + out("{:08x} ", section.address()); + out("{:08x} ", section.offset()); + out("{:08x} ", section.size()); + out("{}", section.flags()); + outln(); }); } - printf("\n"); + outln(); } if (display_program_headers) { if (!display_all) { - printf("Elf file type is %d (%s)\n", header.e_type, object_file_type_to_string(header.e_type)); - printf("Entry point 0x%x\n", header.e_entry); - printf("There are %u program headers, starting at offset %u\n", header.e_phnum, header.e_phoff); - printf("\n"); + outln("ELF file type is {} ({})", header.e_type, object_file_type_to_string(header.e_type)); + outln("Entry point {:#x}\n", header.e_entry); + outln("There are {} program headers, starting at offset {}", header.e_phnum, header.e_phoff); + outln(); } if (!elf_image.program_header_count()) { - printf("There are no program headers in this file.\n"); + outln("There are no program headers in this file."); } else { - printf("Program Headers:\n"); - printf(" Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align\n"); + outln("Program Headers:"); + outln(" Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align"); elf_image.for_each_program_header([](const ELF::Image::ProgramHeader& program_header) { - printf(" %-14s ", object_program_header_type_to_string(program_header.type())); - printf("0x%08x ", program_header.offset()); - printf("%p ", program_header.vaddr().as_ptr()); - printf("%p ", program_header.vaddr().as_ptr()); // FIXME: assumes PhysAddr = VirtAddr - printf("0x%08x ", program_header.size_in_image()); - printf("0x%08x ", program_header.size_in_memory()); - printf("%04x ", program_header.flags()); - printf("0x%08x", program_header.alignment()); - printf("\n"); + out(" "); + out("{:14} ", object_program_header_type_to_string(program_header.type())); + out("{:#08x} ", program_header.offset()); + out("{:p} ", program_header.vaddr().as_ptr()); + out("{:p} ", program_header.vaddr().as_ptr()); // FIXME: assumes PhysAddr = VirtAddr + out("{:#08x} ", program_header.size_in_image()); + out("{:#08x} ", program_header.size_in_memory()); + out("{:04x} ", program_header.flags()); + out("{:#08x}", program_header.alignment()); + outln(); if (program_header.type() == PT_INTERP) - printf(" [Interpreter: %s]\n", program_header.raw_data()); + outln(" [Interpreter: {}]", program_header.raw_data()); }); } // TODO: Display section to segment mapping - printf("\n"); + outln(); } if (display_dynamic_section) { @@ -572,9 +573,9 @@ int main(int argc, char** argv) found_dynamic_section = true; if (section.entry_count()) { - printf("Dynamic section '%s' at offset 0x%08x contains %u entries.\n", section.name().to_string().characters(), section.offset(), section.entry_count()); + outln("Dynamic section '{}' at offset {:#08x} contains {} entries.", section.name().to_string(), section.offset(), section.entry_count()); } else { - printf("Dynamic section '%s' at offset 0x%08x contains zero entries.\n", section.name().to_string().characters(), section.offset()); + outln("Dynamic section '{}' at offset {:#08x} contains zero entries.", section.name().to_string(), section.offset()); } return IterationDecision::Break; @@ -582,77 +583,77 @@ int main(int argc, char** argv) Vector<String> libraries; object->for_each_needed_library([&libraries](StringView entry) { - libraries.append(String::formatted("{}", entry).characters()); + libraries.append(String::formatted("{}", entry)); }); auto library_index = 0; - printf(" Tag Type Name / Value\n"); + outln(" Tag Type Name / Value"); object->for_each_dynamic_entry([&library_index, &libraries, &object](const ELF::DynamicObject::DynamicEntry& entry) { - printf(" 0x%08x ", entry.tag()); - printf("%-17s ", object_tag_to_string(entry.tag())); + out(" {:#08x} ", entry.tag()); + out("{:17} ", object_tag_to_string(entry.tag())); if (entry.tag() == DT_NEEDED) { - printf("Shared library: %s\n", String(libraries[library_index]).characters()); + outln("Shared library: {}", libraries[library_index]); library_index++; } else if (entry.tag() == DT_RPATH) { - printf("Library rpath: %s\n", String(object->rpath()).characters()); + outln("Library rpath: {}", object->rpath()); } else if (entry.tag() == DT_RUNPATH) { - printf("Library runpath: %s\n", String(object->runpath()).characters()); + outln("Library runpath: {}", object->runpath()); } else if (entry.tag() == DT_SONAME) { - printf("Library soname: %s\n", String(object->soname()).characters()); + outln("Library soname: {}", object->soname()); } else { - printf("0x%08x\n", entry.val()); + outln("{:#08x}", entry.val()); } }); } if (!found_dynamic_section) - printf("No dynamic section in this file.\n"); + outln("No dynamic section in this file."); - printf("\n"); + outln(); } if (display_relocations) { if (elf_image.is_dynamic()) { if (!object->relocation_section().entry_count()) { - printf("Relocation section '%s' at offset 0x%08x contains zero entries:\n", object->relocation_section().name().to_string().characters(), object->relocation_section().offset()); + outln("Relocation section '{}' at offset {:#08x} contains zero entries:", object->relocation_section().name(), object->relocation_section().offset()); } else { - printf("Relocation section '%s' at offset 0x%08x contains %u entries:\n", object->relocation_section().name().to_string().characters(), object->relocation_section().offset(), object->relocation_section().entry_count()); - printf(" Offset Type Sym Value Sym Name\n"); + outln("Relocation section '{}' at offset {:#08x} contains {} entries:", object->relocation_section().name(), object->relocation_section().offset(), object->relocation_section().entry_count()); + outln(" Offset Type Sym Value Sym Name"); object->relocation_section().for_each_relocation([](const ELF::DynamicObject::Relocation& reloc) { - printf(" 0x%08x ", reloc.offset()); - printf(" %-17s ", object_relocation_type_to_string(reloc.type())); - printf(" 0x%08x ", reloc.symbol().value()); - printf(" %s", reloc.symbol().name().to_string().characters()); - printf("\n"); + out(" {:#08x} ", reloc.offset()); + out(" {:17} ", object_relocation_type_to_string(reloc.type())); + out(" {:#08x} ", reloc.symbol().value()); + out(" {}", reloc.symbol().name()); + outln(); }); } - printf("\n"); + outln(); if (!object->plt_relocation_section().entry_count()) { - printf("Relocation section '%s' at offset 0x%08x contains zero entries:\n", object->plt_relocation_section().name().to_string().characters(), object->plt_relocation_section().offset()); + outln("Relocation section '{}' at offset {:#08x} contains zero entries:", object->plt_relocation_section().name(), object->plt_relocation_section().offset()); } else { - printf("Relocation section '%s' at offset 0x%08x contains %u entries:\n", object->plt_relocation_section().name().to_string().characters(), object->plt_relocation_section().offset(), object->plt_relocation_section().entry_count()); - printf(" Offset Type Sym Value Sym Name\n"); + outln("Relocation section '{}' at offset {:#08x} contains {} entries:", object->plt_relocation_section().name(), object->plt_relocation_section().offset(), object->plt_relocation_section().entry_count()); + outln(" Offset Type Sym Value Sym Name"); object->plt_relocation_section().for_each_relocation([](const ELF::DynamicObject::Relocation& reloc) { - printf(" 0x%08x ", reloc.offset()); - printf(" %-17s ", object_relocation_type_to_string(reloc.type())); - printf(" 0x%08x ", reloc.symbol().value()); - printf(" %s", reloc.symbol().name().to_string().characters()); - printf("\n"); + out(" {:#08x} ", reloc.offset()); + out(" {:17} ", object_relocation_type_to_string(reloc.type())); + out(" {:#08x} ", reloc.symbol().value()); + out(" {}", reloc.symbol().name()); + outln(); }); } } else { - printf("No relocations in this file.\n"); + outln("No relocations in this file."); } - printf("\n"); + outln(); } if (display_unwind_info) { // TODO: Unwind info - printf("Decoding of unwind sections for machine type %s is not supported.\n", object_machine_type_to_string(header.e_machine)); - printf("\n"); + outln("Decoding of unwind sections for machine type {} is not supported.", object_machine_type_to_string(header.e_machine)); + outln(); } if (display_core_notes) { @@ -663,16 +664,16 @@ int main(int argc, char** argv) found_notes = true; - printf("Displaying notes section '%s' at offset 0x%08x of length 0x%08x:\n", object_program_header_type_to_string(program_header.type()), program_header.offset(), program_header.size_in_image()); + outln("Displaying notes section '{}' at offset {:#08x} of length {:#08x}:", object_program_header_type_to_string(program_header.type()), program_header.offset(), program_header.size_in_image()); // FIXME: Parse CORE notes. Notes are in JSON format on SerenityOS, but vary between systems. - printf("%s\n", program_header.raw_data()); + outln("{}", program_header.raw_data()); }); if (!found_notes) - printf("No core notes in this file.\n"); + outln("No core notes in this file."); - printf("\n"); + outln(); } if (display_dynamic_symbol_table || display_symbol_table) { @@ -686,9 +687,9 @@ int main(int argc, char** argv) found_dynamic_symbol_table = true; if (!section.entry_count()) { - printf("Symbol table '%s' contains zero entries.\n", ELF_DYNSYM); + outln("Symbol table '{}' contains zero entries.", ELF_DYNSYM); } else { - printf("Symbol table '%s' contains %u entries.\n", ELF_DYNSYM, section.entry_count()); + outln("Symbol table '{}' contains {} entries.", ELF_DYNSYM, section.entry_count()); } return IterationDecision::Break; @@ -696,48 +697,48 @@ int main(int argc, char** argv) if (object->symbol_count()) { // FIXME: Add support for init/fini/start/main sections - printf(" Num: Value Size Type Bind Name\n"); + outln(" Num: Value Size Type Bind Name"); object->for_each_symbol([](const ELF::DynamicObject::Symbol& sym) { - printf(" %4u: ", sym.index()); - printf("%08x ", sym.value()); - printf("%08x ", sym.size()); - printf("%-8s ", object_symbol_type_to_string(sym.type())); - printf("%-8s ", object_symbol_binding_to_string(sym.bind())); - printf("%s", StringView(sym.name()).to_string().characters()); - printf("\n"); + out(" {:>4}: ", sym.index()); + out("{:08x} ", sym.value()); + out("{:08x} ", sym.size()); + out("{:8} ", object_symbol_type_to_string(sym.type())); + out("{:8} ", object_symbol_binding_to_string(sym.bind())); + out("{}", sym.name()); + outln(); }); } } if (!found_dynamic_symbol_table) - printf("No dynamic symbol information for this file.\n"); + outln("No dynamic symbol information for this file."); - printf("\n"); + outln(); } if (display_symbol_table) { if (elf_image.symbol_count()) { - printf("Symbol table '%s' contains %u entries:\n", ELF_SYMTAB, elf_image.symbol_count()); - printf(" Num: Value Size Type Bind Name\n"); + outln("Symbol table '{}' contains {} entries:", ELF_SYMTAB, elf_image.symbol_count()); + outln(" Num: Value Size Type Bind Name"); elf_image.for_each_symbol([](const ELF::Image::Symbol& sym) { - printf(" %4u: ", sym.index()); - printf("%08x ", sym.value()); - printf("%08x ", sym.size()); - printf("%-8s ", object_symbol_type_to_string(sym.type())); - printf("%-8s ", object_symbol_binding_to_string(sym.bind())); - printf("%s", StringView(sym.name()).to_string().characters()); - printf("\n"); + out(" {:>4}: ", sym.index()); + out("{:08x} ", sym.value()); + out("{:08x} ", sym.size()); + out("{:8} ", object_symbol_type_to_string(sym.type())); + out("{:8} ", object_symbol_binding_to_string(sym.bind())); + out("{}", sym.name()); + outln(); }); } else { - printf("Symbol table '%s' contains zero entries.\n", ELF_SYMTAB); + outln("Symbol table '{}' contains zero entries.", ELF_SYMTAB); } - printf("\n"); + outln(); } if (display_hardening) { - printf("Security Hardening:\n"); - printf("RELRO Stack Canary NX PIE RPATH RUNPATH Symbols \n"); + outln("Security Hardening:"); + outln("RELRO Stack Canary NX PIE RPATH RUNPATH Symbols "); bool relro = false; elf_image.for_each_program_header([&relro](const ELF::Image::ProgramHeader& program_header) { @@ -758,11 +759,11 @@ int main(int argc, char** argv) return IterationDecision::Continue; }); if (full_relro) - printf("\033[0;32m%-13s\033[0m ", "Full RELRO"); + out("\033[0;32m{:13}\033[0m ", "Full RELRO"); else - printf("\033[0;33m%-13s\033[0m ", "Partial RELRO"); + out("\033[0;33m{:13}\033[0m ", "Partial RELRO"); } else { - printf("\033[0;31m%-13s\033[0m ", "No RELRO"); + out("\033[0;31m{:13}\033[0m ", "No RELRO"); } bool canary = false; @@ -775,9 +776,9 @@ int main(int argc, char** argv) }); if (canary) - printf("\033[0;32m%-12s\033[0m ", "Canary found"); + out("\033[0;32m{:12}\033[0m ", "Canary found"); else - printf("\033[0;31m%-12s\033[0m ", "No canary"); + out("\033[0;31m{:12}\033[0m ", "No canary"); bool nx = false; elf_image.for_each_program_header([&nx](const ELF::Image::ProgramHeader& program_header) { @@ -792,39 +793,39 @@ int main(int argc, char** argv) }); if (nx) - printf("\033[0;32m%-12s\033[0m ", "NX enabled"); + out("\033[0;32m{:12}\033[0m ", "NX enabled"); else - printf("\033[0;31m%-12s\033[0m ", "NX disabled"); + out("\033[0;31m{:12}\033[0m ", "NX disabled"); bool pie = false; if (header.e_type == ET_REL || header.e_type == ET_DYN) pie = true; if (pie) - printf("\033[0;32m%-12s\033[0m ", "PIE enabled"); + out("\033[0;32m{:12}\033[0m ", "PIE enabled"); else - printf("\033[0;31m%-12s\033[0m ", "No PIE"); + out("\033[0;31m{:12}\033[0m ", "No PIE"); StringView rpath; if (elf_image.is_dynamic()) rpath = object->rpath(); if (rpath.is_empty()) - printf("\033[0;32m%-12s\033[0m ", "No RPATH"); + out("\033[0;32m{:12}\033[0m ", "No RPATH"); else - printf("\033[0;31m%-12s\033[0m ", rpath.to_string().characters()); + out("\033[0;31m{:12}\033[0m ", rpath); StringView runpath; if (elf_image.is_dynamic()) runpath = object->runpath(); if (runpath.is_empty()) - printf("\033[0;32m%-12s\033[0m ", "No RUNPATH"); + out("\033[0;32m{:12}\033[0m ", "No RUNPATH"); else - printf("\033[0;31m%-12s\033[0m ", runpath.to_string().characters()); + out("\033[0;31m{:12}\033[0m ", runpath); - printf("%u symbols ", elf_image.symbol_count()); - printf("\n"); + out("{} symbols", elf_image.symbol_count()); + outln(); } return 0; diff --git a/Userland/Utilities/readlink.cpp b/Userland/Utilities/readlink.cpp index c126b4002e..318e31ac1a 100644 --- a/Userland/Utilities/readlink.cpp +++ b/Userland/Utilities/readlink.cpp @@ -30,9 +30,9 @@ int main(int argc, char** argv) perror(path); return 1; } - printf("%s", destination.characters()); + out("{}", destination); if (!no_newline) - putchar('\n'); + outln(); } return 0; diff --git a/Userland/Utilities/realpath.cpp b/Userland/Utilities/realpath.cpp index 3c9ff71eab..0f48afb494 100644 --- a/Userland/Utilities/realpath.cpp +++ b/Userland/Utilities/realpath.cpp @@ -28,7 +28,7 @@ int main(int argc, char** argv) perror("realpath"); return 1; } - printf("%s\n", value); + outln("{}", value); free(value); return 0; } diff --git a/Userland/Utilities/seq.cpp b/Userland/Utilities/seq.cpp index 07c885de7e..848ab49bc9 100644 --- a/Userland/Utilities/seq.cpp +++ b/Userland/Utilities/seq.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <AK/StdLibExtras.h> #include <stdio.h> #include <stdlib.h> @@ -28,7 +29,7 @@ static double get_double(const char* name, const char* d_string, int* number_of_ char* end; double d = strtod(d_string, &end); if (d == 0 && end == d_string) { - fprintf(stderr, "%s: invalid argument \"%s\"\n", name, d_string); + warnln("{}: invalid argument \"{}\"", name, d_string); print_usage(stderr); exit(1); } @@ -73,18 +74,18 @@ int main(int argc, const char* argv[]) end = get_double(argv[0], argv[3], &number_of_end_decimals); break; default: - fprintf(stderr, "%s: unexpected number of arguments\n", argv[0]); + warnln("{}: unexpected number of arguments", argv[0]); print_usage(stderr); return 1; } if (step == 0) { - fprintf(stderr, "%s: increment must not be 0\n", argv[0]); + warnln("{}: increment must not be 0", argv[0]); return 1; } if (__builtin_isnan(start) || __builtin_isnan(step) || __builtin_isnan(end)) { - fprintf(stderr, "%s: start, step, and end must not be NaN\n", argv[0]); + warnln("{}: start, step, and end must not be NaN", argv[0]); return 1; } @@ -101,7 +102,7 @@ int main(int argc, const char* argv[]) else if ((dot - buf) + 1 + number_of_decimals < (int)sizeof(buf)) dot[1 + number_of_decimals] = '\0'; } - printf("%s\n", buf); + outln("{}", buf); d += step; } diff --git a/Userland/Utilities/su.cpp b/Userland/Utilities/su.cpp index 4e34129ba5..72348b51f0 100644 --- a/Userland/Utilities/su.cpp +++ b/Userland/Utilities/su.cpp @@ -41,7 +41,7 @@ int main(int argc, char** argv) ? Core::Account::from_name(user) : Core::Account::from_uid(0); if (account_or_error.is_error()) { - fprintf(stderr, "Core::Account::from_name: %s\n", account_or_error.error().characters()); + warnln("Core::Account::from_name: {}", account_or_error.error()); return 1; } diff --git a/Userland/Utilities/sysctl.cpp b/Userland/Utilities/sysctl.cpp index 1ced156c95..9cdd2e2146 100644 --- a/Userland/Utilities/sysctl.cpp +++ b/Userland/Utilities/sysctl.cpp @@ -19,12 +19,12 @@ static String read_var(const String& name) auto path = builder.to_string(); auto f = Core::File::construct(path); if (!f->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "open: %s\n", f->error_string()); + warnln("Failed to open {}: {}", f->name(), f->error_string()); exit(1); } const auto& b = f->read_all(); if (f->error() < 0) { - fprintf(stderr, "read: %s\n", f->error_string()); + warnln("Failed to read: {}", f->error_string()); exit(1); } return String((const char*)b.data(), b.size(), Chomp); @@ -38,12 +38,12 @@ static void write_var(const String& name, const String& value) auto path = builder.to_string(); auto f = Core::File::construct(path); if (!f->open(Core::OpenMode::WriteOnly)) { - fprintf(stderr, "open: %s\n", f->error_string()); + warnln("Failed to open: {}", f->error_string()); exit(1); } f->write(value); if (f->error() < 0) { - fprintf(stderr, "write: %s\n", f->error_string()); + warnln("Failed to write: {}", f->error_string()); exit(1); } } @@ -52,13 +52,13 @@ static int handle_show_all() { Core::DirIterator di("/proc/sys", Core::DirIterator::SkipDots); if (di.has_error()) { - fprintf(stderr, "DirIterator: %s\n", di.error_string()); + outln("DirIterator: {}", di.error_string()); return 1; } while (di.has_next()) { String variable_name = di.next_path(); - printf("%s = %s\n", variable_name.characters(), read_var(variable_name).characters()); + outln("{} = {}", variable_name, read_var(variable_name)); } return 0; } @@ -71,13 +71,13 @@ static int handle_var(const String& var) bool is_write = parts.size() > 1; if (!is_write) { - printf("%s = %s\n", variable_name.characters(), read_var(variable_name).characters()); + outln("{} = {}", variable_name, read_var(variable_name)); return 0; } - printf("%s = %s", variable_name.characters(), read_var(variable_name).characters()); + out("{} = {}", variable_name, read_var(variable_name)); write_var(variable_name, parts[1]); - printf(" -> %s\n", read_var(variable_name).characters()); + outln(" -> {}", read_var(variable_name)); return 0; } diff --git a/Userland/Utilities/tail.cpp b/Userland/Utilities/tail.cpp index a735462c04..cb668801ac 100644 --- a/Userland/Utilities/tail.cpp +++ b/Userland/Utilities/tail.cpp @@ -44,7 +44,7 @@ static off_t find_seek_pos(Core::File& file, int wanted_lines) // stopping when we've found the number of lines we want. off_t pos = 0; if (!file.seek(0, Core::SeekMode::FromEndPosition, &pos)) { - fprintf(stderr, "Failed to find end of file: %s\n", file.error_string()); + warnln("Failed to find end of file: {}", file.error_string()); return 1; } @@ -91,7 +91,7 @@ int main(int argc, char* argv[]) auto f = Core::File::construct(file); if (!f->open(Core::OpenMode::ReadOnly)) { - fprintf(stderr, "Error opening file %s: %s\n", file, strerror(errno)); + warnln("Failed to open {}: {}", f->name(), f->error_string()); exit(1); } diff --git a/Userland/Utilities/test-crypto.cpp b/Userland/Utilities/test-crypto.cpp index 89ebc0a16e..00255b721f 100644 --- a/Userland/Utilities/test-crypto.cpp +++ b/Userland/Utilities/test-crypto.cpp @@ -94,15 +94,15 @@ static void print_buffer(ReadonlyBytes buffer, int split) for (size_t i = 0; i < buffer.size(); ++i) { if (split > 0) { if (i % split == 0 && i) { - printf(" "); + out(" "); for (size_t j = i - split; j < i; ++j) { auto ch = buffer[j]; - printf("%c", ch >= 32 && ch <= 127 ? ch : '.'); // silly hack + out("{}", ch >= 32 && ch <= 127 ? ch : '.'); // silly hack } - puts(""); + outln(); } } - printf("%02x ", buffer[i]); + out("{:02x} ", buffer[i]); } puts(""); } @@ -130,16 +130,16 @@ static int run(Function<void(const char*, size_t)> fn) } } else { if (filename == nullptr) { - puts("must specify a filename"); + warnln("must specify a filename"); return 1; } if (!Core::File::exists(filename)) { - puts("File does not exist"); + warnln("File does not exist"); return 1; } auto file = Core::File::open(filename, Core::OpenMode::ReadOnly); if (file.is_error()) { - printf("That's a weird file man...\n"); + warnln("Failed to open {}: {}", filename, file.error()); return 1; } auto buffer = file.value()->read_all(); @@ -160,7 +160,7 @@ static void tls(const char* message, size_t len) tls->on_tls_ready_to_read = [](auto& tls) { auto buffer = tls.read(); if (buffer.has_value()) - fprintf(stdout, "%.*s", (int)buffer.value().size(), buffer.value().data()); + out("{}", StringView { buffer->data(), buffer->size() }); }; tls->on_tls_ready_to_write = [&](auto&) { if (write.size()) { @@ -196,7 +196,7 @@ static void aes_cbc(const char* message, size_t len) cipher.encrypt(buffer, enc_span, iv); if (binary) - printf("%.*s", (int)enc_span.size(), enc_span.data()); + out("{}", StringView { enc_span.data(), enc_span.size() }); else print_buffer(enc_span, Crypto::Cipher::AESCipher::block_size()); } else { @@ -207,27 +207,27 @@ static void aes_cbc(const char* message, size_t len) auto dec = cipher.create_aligned_buffer(buffer.size()); auto dec_span = dec.bytes(); cipher.decrypt(buffer, dec_span, iv); - printf("%.*s\n", (int)dec_span.size(), dec_span.data()); + outln("{}", StringView { dec_span.data(), dec_span.size() }); } } static void adler32(const char* message, size_t len) { auto checksum = Crypto::Checksum::Adler32({ (const u8*)message, len }); - printf("%#10X\n", checksum.digest()); + outln("{:#10X}", checksum.digest()); } static void crc32(const char* message, size_t len) { auto checksum = Crypto::Checksum::CRC32({ (const u8*)message, len }); - printf("%#10X\n", checksum.digest()); + outln("{:#10X}", checksum.digest()); } static void md5(const char* message, size_t len) { auto digest = Crypto::Hash::MD5::hash((const u8*)message, len); if (binary) - printf("%.*s", (int)Crypto::Hash::MD5::digest_size(), digest.data); + out("{}", StringView { digest.data, Crypto::Hash::MD5::digest_size() }); else print_buffer({ digest.data, Crypto::Hash::MD5::digest_size() }, -1); } @@ -237,7 +237,7 @@ static void hmac_md5(const char* message, size_t len) Crypto::Authentication::HMAC<Crypto::Hash::MD5> hmac(secret_key); auto mac = hmac.process((const u8*)message, len); if (binary) - printf("%.*s", (int)hmac.digest_size(), mac.data); + out("{}", StringView { mac.data, hmac.digest_size() }); else print_buffer({ mac.data, hmac.digest_size() }, -1); } @@ -246,7 +246,7 @@ static void sha1(const char* message, size_t len) { auto digest = Crypto::Hash::SHA1::hash((const u8*)message, len); if (binary) - printf("%.*s", (int)Crypto::Hash::SHA1::digest_size(), digest.data); + out("{}", StringView { digest.data, Crypto::Hash::SHA1::digest_size() }); else print_buffer({ digest.data, Crypto::Hash::SHA1::digest_size() }, -1); } @@ -255,7 +255,7 @@ static void sha256(const char* message, size_t len) { auto digest = Crypto::Hash::SHA256::hash((const u8*)message, len); if (binary) - printf("%.*s", (int)Crypto::Hash::SHA256::digest_size(), digest.data); + out("{}", StringView { digest.data, Crypto::Hash::SHA256::digest_size() }); else print_buffer({ digest.data, Crypto::Hash::SHA256::digest_size() }, -1); } @@ -265,7 +265,7 @@ static void hmac_sha256(const char* message, size_t len) Crypto::Authentication::HMAC<Crypto::Hash::SHA256> hmac(secret_key); auto mac = hmac.process((const u8*)message, len); if (binary) - printf("%.*s", (int)hmac.digest_size(), mac.data); + out("{}", StringView { mac.data, hmac.digest_size() }); else print_buffer({ mac.data, hmac.digest_size() }, -1); } @@ -274,7 +274,7 @@ static void sha384(const char* message, size_t len) { auto digest = Crypto::Hash::SHA384::hash((const u8*)message, len); if (binary) - printf("%.*s", (int)Crypto::Hash::SHA384::digest_size(), digest.data); + out("{}", StringView { digest.data, Crypto::Hash::SHA384::digest_size() }); else print_buffer({ digest.data, Crypto::Hash::SHA384::digest_size() }, -1); } @@ -283,7 +283,7 @@ static void sha512(const char* message, size_t len) { auto digest = Crypto::Hash::SHA512::hash((const u8*)message, len); if (binary) - printf("%.*s", (int)Crypto::Hash::SHA512::digest_size(), digest.data); + out("{}", StringView { digest.data, Crypto::Hash::SHA512::digest_size() }); else print_buffer({ digest.data, Crypto::Hash::SHA512::digest_size() }, -1); } @@ -293,7 +293,7 @@ static void hmac_sha512(const char* message, size_t len) Crypto::Authentication::HMAC<Crypto::Hash::SHA512> hmac(secret_key); auto mac = hmac.process((const u8*)message, len); if (binary) - printf("%.*s", (int)hmac.digest_size(), mac.data); + out("{}", StringView { mac.data, hmac.digest_size() }); else print_buffer({ mac.data, hmac.digest_size() }, -1); } @@ -319,18 +319,18 @@ auto main(int argc, char** argv) -> int StringView mode_sv { mode }; if (mode_sv == "list") { - puts("test-crypto modes"); - puts("\tdigest - Access digest (authentication) functions"); - puts("\thash - Access hash functions"); - puts("\tchecksum - Access checksum functions"); - puts("\tencrypt -- Access encryption functions"); - puts("\tdecrypt -- Access decryption functions"); - puts("\ttls -- Connect to a peer over TLS 1.2"); - puts("\tlist -- List all known modes"); - puts("these modes only contain tests"); - puts("\ttest -- Run every test suite"); - puts("\tbigint -- Run big integer test suite"); - puts("\tpk -- Run Public-key system tests"); + outln("test-crypto modes"); + outln("\tdigest - Access digest (authentication) functions"); + outln("\thash - Access hash functions"); + outln("\tchecksum - Access checksum functions"); + outln("\tencrypt -- Access encryption functions"); + outln("\tdecrypt -- Access decryption functions"); + outln("\ttls -- Connect to a peer over TLS 1.2"); + outln("\tlist -- List all known modes"); + outln("these modes only contain tests"); + outln("\ttest -- Run every test suite"); + outln("\tbigint -- Run big integer test suite"); + outln("\tpk -- Run Public-key system tests"); return 0; } @@ -364,7 +364,7 @@ auto main(int argc, char** argv) -> int return sha512_tests(); return run(sha512); } - printf("unknown hash function '%s'\n", suite); + warnln("unknown hash function '{}'", suite); return 1; } if (mode_sv == "checksum") { @@ -382,7 +382,7 @@ auto main(int argc, char** argv) -> int return adler32_tests(); return run(adler32); } - printf("unknown checksum function '%s'\n", suite); + warnln("unknown checksum function '{}'", suite); return 1; } if (mode_sv == "digest") { @@ -413,7 +413,7 @@ auto main(int argc, char** argv) -> int if (run_tests) return ghash_tests(); } - printf("unknown hash function '%s'\n", suite); + warnln("unknown hash function '{}'", suite); return 1; } if (mode_sv == "pk") { @@ -507,11 +507,11 @@ auto main(int argc, char** argv) -> int return aes_cbc_tests(); if (!Crypto::Cipher::AESCipher::KeyType::is_valid_key_size(key_bits)) { - printf("Invalid key size for AES: %d\n", key_bits); + warnln("Invalid key size for AES: {}", key_bits); return 1; } if (strlen(secret_key) != (size_t)key_bits / 8) { - printf("Key must be exactly %d bytes long\n", key_bits / 8); + warnln("Key must be exactly {} bytes long", key_bits / 8); return 1; } return run(aes_cbc); @@ -522,39 +522,39 @@ auto main(int argc, char** argv) -> int return 1; } else { - printf("Unknown cipher suite '%s'\n", suite); + warnln("Unknown cipher suite '{}'", suite); return 1; } } - printf("Unknown mode '%s', check out the list of modes\n", mode); + warnln("Unknown mode '{}', check out the list of modes", mode); return 1; } #define I_TEST(thing) \ { \ - printf("Testing " #thing "... "); \ + out("Testing " #thing "... "); \ fflush(stdout); \ gettimeofday(&start_time, nullptr); \ } -#define PASS \ - { \ - struct timeval end_time { \ - 0, 0 \ - }; \ - gettimeofday(&end_time, nullptr); \ - time_t interval_s = end_time.tv_sec - start_time.tv_sec; \ - suseconds_t interval_us = end_time.tv_usec; \ - if (interval_us < start_time.tv_usec) { \ - interval_s -= 1; \ - interval_us += 1000000; \ - } \ - interval_us -= start_time.tv_usec; \ - printf("PASS %llds %lldus\n", (long long)interval_s, (long long)interval_us); \ - } -#define FAIL(reason) \ - do { \ - printf("FAIL: " #reason "\n"); \ - g_some_test_failed = true; \ +#define PASS \ + { \ + struct timeval end_time { \ + 0, 0 \ + }; \ + gettimeofday(&end_time, nullptr); \ + time_t interval_s = end_time.tv_sec - start_time.tv_sec; \ + suseconds_t interval_us = end_time.tv_usec; \ + if (interval_us < start_time.tv_usec) { \ + interval_s -= 1; \ + interval_us += 1000000; \ + } \ + interval_us -= start_time.tv_usec; \ + outln("PASS {}s {}us", (long long)interval_s, (long long)interval_us); \ + } +#define FAIL(reason) \ + do { \ + outln("FAIL: " #reason); \ + g_some_test_failed = true; \ } while (0) static ByteBuffer operator""_b(const char* string, size_t length) @@ -731,7 +731,7 @@ static void aes_cbc_test_decrypt() cipher.decrypt(in, out_span, iv); if (out_span.size() != strlen(true_value)) { FAIL(size mismatch); - printf("Expected %zu bytes but got %zu\n", strlen(true_value), out_span.size()); + outln("Expected {} bytes but got {}", strlen(true_value), out_span.size()); } else if (memcmp(out_span.data(), true_value, strlen(true_value)) != 0) { FAIL(invalid data); print_buffer(out_span, Crypto::Cipher::AESCipher::block_size()); @@ -807,7 +807,7 @@ static void aes_ctr_test_encrypt() cipher.encrypt(in, out_span, ivec); if (out_expected.size() != out_actual.size()) { FAIL(size mismatch); - printf("Expected %zu bytes but got %zu\n", out_expected.size(), out_span.size()); + outln("Expected {} bytes but got {}", out_expected.size(), out_span.size()); print_buffer(out_span, Crypto::Cipher::AESCipher::block_size()); } else if (memcmp(out_expected.data(), out_span.data(), out_expected.size()) != 0) { FAIL(invalid data); @@ -1002,7 +1002,7 @@ static void aes_ctr_test_decrypt() cipher.decrypt(in, out_span, ivec); if (out_expected.size() != out_span.size()) { FAIL(size mismatch); - printf("Expected %zu bytes but got %zu\n", out_expected.size(), out_span.size()); + outln("Expected {} bytes but got {}", out_expected.size(), out_span.size()); print_buffer(out_span, Crypto::Cipher::AESCipher::block_size()); } else if (memcmp(out_expected.data(), out_span.data(), out_expected.size()) != 0) { FAIL(invalid data); @@ -1547,7 +1547,7 @@ static void sha1_test_name() Crypto::Hash::SHA1 sha; if (sha.class_name() != "SHA1") { FAIL(Invalid class name); - printf("%s\n", sha.class_name().characters()); + outln("{}", sha.class_name()); } else PASS; } @@ -1619,7 +1619,7 @@ static void sha256_test_name() Crypto::Hash::SHA256 sha; if (sha.class_name() != "SHA256") { FAIL(Invalid class name); - printf("%s\n", sha.class_name().characters()); + outln("{}", sha.class_name()); } else PASS; } @@ -1730,7 +1730,7 @@ static void sha384_test_name() Crypto::Hash::SHA384 sha; if (sha.class_name() != "SHA384") { FAIL(Invalid class name); - printf("%s\n", sha.class_name().characters()); + outln("{}", sha.class_name()); } else PASS; } @@ -1776,7 +1776,7 @@ static void sha512_test_name() Crypto::Hash::SHA512 sha; if (sha.class_name() != "SHA512") { FAIL(Invalid class name); - printf("%s\n", sha.class_name().characters()); + outln("{}", sha.class_name()); } else PASS; } @@ -2561,8 +2561,11 @@ static void bigint_theory_modular_power() PASS; } else { FAIL(Wrong result); - printf("b: %s\ne: %s\nm: %s\nexpect: %s\nactual: %s\n", - test_case.base.to_base10().characters(), test_case.exp.to_base10().characters(), test_case.mod.to_base10().characters(), test_case.expected.to_base10().characters(), actual.to_base10().characters()); + outln("b: {}", test_case.base.to_base10()); + outln("e: {}", test_case.exp.to_base10()); + outln("m: {}", test_case.mod.to_base10()); + outln("expect: {}", test_case.expected.to_base10()); + outln("actual: {}", actual.to_base10()); } } } @@ -2599,8 +2602,8 @@ static void bigint_theory_primality() PASS; } else { FAIL(Wrong primality guess); - printf("The number %s is %sa prime, but the test said it is %sa prime!\n", - test_case.candidate.to_base10().characters(), test_case.expected_result ? "" : "not ", actual_result ? "" : "not "); + outln("The number {} is {}a prime, but the test said it is {}a prime!", + test_case.candidate.to_base10(), test_case.expected_result ? "" : "not ", actual_result ? "" : "not "); } } } @@ -2623,10 +2626,10 @@ static void bigint_theory_random_number() auto actual_result = Crypto::NumberTheory::random_number(test_case.min, test_case.max); if (actual_result < test_case.min) { FAIL(Too small); - printf("The generated number %s is smaller than the requested minimum %s. (max = %s)\n", actual_result.to_base10().characters(), test_case.min.to_base10().characters(), test_case.max.to_base10().characters()); + outln("The generated number {} is smaller than the requested minimum {}. (max = {})", actual_result.to_base10(), test_case.min.to_base10(), test_case.max.to_base10()); } else if (!(actual_result < test_case.max)) { FAIL(Too large); - printf("The generated number %s is larger-or-equal to the requested maximum %s. (min = %s)\n", actual_result.to_base10().characters(), test_case.max.to_base10().characters(), test_case.min.to_base10().characters()); + outln("The generated number {} is larger-or-equal to the requested maximum {}. (min = {})", actual_result.to_base10(), test_case.max.to_base10(), test_case.min.to_base10()); } else { PASS; } @@ -2639,10 +2642,10 @@ static void bigint_theory_random_number() "100000000000000000000000000000"_bigint); // 10**29 if (actual_result < "100000000000000000000"_bigint) { // 10**20 FAIL(Too small); - printf("The generated number %s is extremely small. This *can* happen by pure chance, but should happen only once in a billion times. So it's probably an error.\n", actual_result.to_base10().characters()); + outln("The generated number {} is extremely small. This *can* happen by pure chance, but should happen only once in a billion times. So it's probably an error.", actual_result.to_base10()); } else if ("99999999900000000000000000000"_bigint < actual_result) { // 10**29 - 10**20 FAIL(Too large); - printf("The generated number %s is extremely large. This *can* happen by pure chance, but should happen only once in a billion times. So it's probably an error.\n", actual_result.to_base10().characters()); + outln("The generated number {} is extremely large. This *can* happen by pure chance, but should happen only once in a billion times. So it's probably an error.", actual_result.to_base10()); } else { PASS; } diff --git a/Userland/Utilities/test_efault.cpp b/Userland/Utilities/test_efault.cpp index 0967e3b970..b3e205cd8f 100644 --- a/Userland/Utilities/test_efault.cpp +++ b/Userland/Utilities/test_efault.cpp @@ -5,6 +5,7 @@ */ #include <AK/Assertions.h> +#include <AK/Format.h> #include <AK/Types.h> #include <errno.h> #include <fcntl.h> @@ -12,28 +13,28 @@ #include <sys/mman.h> #include <unistd.h> -#define EXPECT_OK(syscall, address, size) \ - do { \ - rc = syscall(fd, (void*)(address), (size_t)(size)); \ - if (rc < 0) { \ - fprintf(stderr, "Expected success: " #syscall "(%p, %zu), got rc=%d, errno=%d\n", (void*)(address), (size_t)(size), rc, errno); \ - } \ +#define EXPECT_OK(syscall, address, size) \ + do { \ + rc = syscall(fd, (void*)(address), (size_t)(size)); \ + if (rc < 0) { \ + warnln("Expected success: " #syscall "({:p}, {}), got rc={}, errno={}", (void*)(address), (size_t)(size), rc, errno); \ + } \ } while (0) -#define EXPECT_EFAULT(syscall, address, size) \ - do { \ - rc = syscall(fd, (void*)(address), (size_t)(size)); \ - if (rc >= 0 || errno != EFAULT) { \ - fprintf(stderr, "Expected EFAULT: " #syscall "(%p, %zu), got rc=%d, errno=%d\n", (void*)(address), (size_t)(size), rc, errno); \ - } \ +#define EXPECT_EFAULT(syscall, address, size) \ + do { \ + rc = syscall(fd, (void*)(address), (size_t)(size)); \ + if (rc >= 0 || errno != EFAULT) { \ + warnln("Expected EFAULT: " #syscall "({:p}, {}), got rc={}, errno={}", (void*)(address), (size_t)(size), rc, errno); \ + } \ } while (0) -#define EXPECT_EFAULT_NO_FD(syscall, address, size) \ - do { \ - rc = syscall((address), (size_t)(size)); \ - if (rc >= 0 || errno != EFAULT) { \ - fprintf(stderr, "Expected EFAULT: " #syscall "(%p, %zu), got rc=%d, errno=%d\n", (void*)(address), (size_t)(size), rc, errno); \ - } \ +#define EXPECT_EFAULT_NO_FD(syscall, address, size) \ + do { \ + rc = syscall((address), (size_t)(size)); \ + if (rc >= 0 || errno != EFAULT) { \ + warnln("Expected EFAULT: " #syscall "({:p}, {}), got rc={}, errno={}", (void*)(address), (size_t)(size), rc, errno); \ + } \ } while (0) int main(int, char**) diff --git a/Userland/Utilities/test_env.cpp b/Userland/Utilities/test_env.cpp index 3cc66ebd9a..d0bf3a6edf 100644 --- a/Userland/Utilities/test_env.cpp +++ b/Userland/Utilities/test_env.cpp @@ -5,6 +5,7 @@ */ #include <AK/Assertions.h> +#include <AK/Format.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -14,11 +15,11 @@ static void assert_env(const char* name, const char* value) char* result = getenv(name); if (!result) { perror("getenv"); - printf("(When reading value for '%s'; we expected '%s'.)\n", name, value); + outln("(When reading value for '{}'; we expected '{}'.)", name, value); VERIFY(false); } if (strcmp(result, value) != 0) { - printf("Expected '%s', got '%s' instead.\n", value, result); + outln("Expected '{}', got '{}' instead.", value, result); VERIFY(false); } } @@ -77,17 +78,17 @@ static void test_settenv_overwrite_empty() int main(int, char**) { -#define RUNTEST(x) \ - { \ - printf("Running " #x " ...\n"); \ - x(); \ - printf("Success!\n"); \ +#define RUNTEST(x) \ + { \ + outln("Running " #x " ..."); \ + x(); \ + outln("Success!"); \ } RUNTEST(test_getenv_preexisting); RUNTEST(test_puttenv); RUNTEST(test_settenv); RUNTEST(test_settenv_overwrite_empty); - printf("PASS\n"); + outln("PASS"); return 0; } diff --git a/Userland/Utilities/test_io.cpp b/Userland/Utilities/test_io.cpp index c29dddf014..6c09d09400 100644 --- a/Userland/Utilities/test_io.cpp +++ b/Userland/Utilities/test_io.cpp @@ -15,20 +15,20 @@ #include <sys/uio.h> #include <unistd.h> -#define EXPECT_ERROR_2(err, syscall, arg1, arg2) \ - do { \ - rc = syscall(arg1, arg2); \ - if (rc >= 0 || errno != err) { \ - fprintf(stderr, __FILE__ ":%d: Expected " #err ": " #syscall "(%p, %p), got rc=%d, errno=%d\n", __LINE__, (const void*)(arg1), (const void*)arg2, rc, errno); \ - } \ +#define EXPECT_ERROR_2(err, syscall, arg1, arg2) \ + do { \ + rc = syscall(arg1, arg2); \ + if (rc >= 0 || errno != err) { \ + warnln(__FILE__ ":{}: Expected " #err ": " #syscall "({:p}, {:p}), got rc={}, errno={}", __LINE__, (const void*)(arg1), (const void*)arg2, rc, errno); \ + } \ } while (0) -#define EXPECT_ERROR_3(err, syscall, arg1, arg2, arg3) \ - do { \ - rc = syscall(arg1, arg2, arg3); \ - if (rc >= 0 || errno != err) { \ - fprintf(stderr, __FILE__ ":%d: Expected " #err ": " #syscall "(%p, %p, %p), got rc=%d, errno=%d\n", __LINE__, (const void*)(arg1), (const void*)(arg2), (const void*)(arg3), rc, errno); \ - } \ +#define EXPECT_ERROR_3(err, syscall, arg1, arg2, arg3) \ + do { \ + rc = syscall(arg1, arg2, arg3); \ + if (rc >= 0 || errno != err) { \ + warnln(__FILE__ ":{}: Expected " #err ": " #syscall "({:p}, {:p}, {:p}), got rc={}, errno={}", __LINE__, (const void*)(arg1), (const void*)(arg2), (const void*)(arg3), rc, errno); \ + } \ } while (0) static void test_read_from_directory() @@ -92,7 +92,7 @@ static void test_read_past_eof() if (rc < 0) perror("read"); if (rc > 0) - fprintf(stderr, "read %d bytes past EOF\n", rc); + warnln("read {} bytes past EOF", rc); rc = close(fd); VERIFY(rc == 0); } @@ -121,11 +121,11 @@ static void test_mmap_directory() VERIFY(fd >= 0); auto* ptr = mmap(nullptr, 4096, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0); if (ptr != MAP_FAILED) { - fprintf(stderr, "Boo! mmap() of a directory succeeded!\n"); + warnln("Boo! mmap() of a directory succeeded!"); return; } if (errno != ENODEV) { - fprintf(stderr, "Boo! mmap() of a directory gave errno=%d instead of ENODEV!\n", errno); + warnln("Boo! mmap() of a directory gave errno={} instead of ENODEV!", errno); return; } close(fd); @@ -145,7 +145,7 @@ static void test_tmpfs_read_past_end() char buffer[16]; int nread = read(fd, buffer, sizeof(buffer)); if (nread != 0) { - fprintf(stderr, "Expected 0-length read past end of file in /tmp\n"); + warnln("Expected 0-length read past end of file in /tmp"); } close(fd); } @@ -161,7 +161,7 @@ static void test_procfs_read_past_end() char buffer[16]; int nread = read(fd, buffer, sizeof(buffer)); if (nread != 0) { - fprintf(stderr, "Expected 0-length read past end of file in /proc\n"); + warnln("Expected 0-length read past end of file in /proc"); } close(fd); } @@ -178,7 +178,7 @@ static void test_open_create_device() } if (st.st_mode != 0100600) { - fprintf(stderr, "Expected mode 0100600 after attempt to create a device node with open(O_CREAT), mode=%o\n", st.st_mode); + warnln("Expected mode 0100600 after attempt to create a device node with open(O_CREAT), mode={:o}", st.st_mode); } unlink("/tmp/fakedevice"); close(fd); @@ -198,7 +198,7 @@ static void test_unlink_symlink() rc = unlink("/tmp/linky"); if (rc < 0) { perror("unlink"); - fprintf(stderr, "Expected unlink() of a symlink into an unreadable directory to succeed!\n"); + warnln("Expected unlink() of a symlink into an unreadable directory to succeed!"); } } @@ -213,11 +213,11 @@ static void test_eoverflow() char buffer[16]; rc = read(fd, buffer, sizeof(buffer)); if (rc >= 0 || errno != EOVERFLOW) { - fprintf(stderr, "Expected EOVERFLOW when trying to read past INT32_MAX\n"); + warnln("Expected EOVERFLOW when trying to read past INT32_MAX"); } rc = write(fd, buffer, sizeof(buffer)); if (rc >= 0 || errno != EOVERFLOW) { - fprintf(stderr, "Expected EOVERFLOW when trying to write past INT32_MAX\n"); + warnln("Expected EOVERFLOW when trying to write past INT32_MAX"); } close(fd); } @@ -235,7 +235,7 @@ static void test_rmdir_while_inside_dir() int fd = open("x", O_CREAT | O_RDWR, 0600); if (fd >= 0 || errno != ENOENT) { - fprintf(stderr, "Expected ENOENT when trying to create a file inside a deleted directory. Got %d with errno=%d\n", fd, errno); + warnln("Expected ENOENT when trying to create a file inside a deleted directory. Got {} with errno={}", fd, errno); } rc = chdir("/home/anon"); @@ -258,14 +258,14 @@ static void test_writev() VERIFY_NOT_REACHED(); } if (nwritten != 12) { - fprintf(stderr, "Didn't write 12 bytes to pipe with writev\n"); + warnln("Didn't write 12 bytes to pipe with writev"); VERIFY_NOT_REACHED(); } char buffer[32]; int nread = read(pipefds[0], buffer, sizeof(buffer)); if (nread != 12 || memcmp(buffer, "HelloFriends", 12)) { - fprintf(stderr, "Didn't read the expected data from pipe after writev\n"); + warnln("Didn't read the expected data from pipe after writev"); VERIFY_NOT_REACHED(); } diff --git a/Userland/Utilities/tt.cpp b/Userland/Utilities/tt.cpp index 3f5dbc4e3e..bdf6c7e5af 100644 --- a/Userland/Utilities/tt.cpp +++ b/Userland/Utilities/tt.cpp @@ -48,11 +48,11 @@ int main(int argc, char** argv) return 1; } - printf("Hello from the first thread!\n"); + outln("Hello from the first thread!"); pthread_t thread_id; int rc = pthread_create( &thread_id, nullptr, [](void*) -> void* { - printf("Hi there, from the second thread!\n"); + outln("Hi there, from the second thread!"); pthread_exit((void*)0xDEADBEEF); return nullptr; }, @@ -67,7 +67,7 @@ int main(int argc, char** argv) perror("pthread_join"); return 1; } - printf("Okay, joined and got retval=%p\n", retval); + outln("Okay, joined and got retval={}", retval); return 0; } @@ -83,12 +83,12 @@ int mutex_test() pthread_t thread_id; rc = pthread_create( &thread_id, nullptr, [](void*) -> void* { - printf("I'm the secondary thread :^)\n"); + outln("I'm the secondary thread :^)"); for (;;) { pthread_mutex_lock(&mutex); - printf("Second thread stole mutex\n"); + outln("Second thread stole mutex"); sleep(1); - printf("Second thread giving back mutex\n"); + outln("Second thread giving back mutex"); pthread_mutex_unlock(&mutex); sleep(1); } @@ -102,7 +102,7 @@ int mutex_test() } for (;;) { pthread_mutex_lock(&mutex); - printf("Obnoxious spam!\n"); + outln("Obnoxious spam!"); pthread_mutex_unlock(&mutex); usleep(10000); } @@ -114,57 +114,57 @@ int detached_test() pthread_attr_t attributes; int rc = pthread_attr_init(&attributes); if (rc != 0) { - printf("pthread_attr_init: %s\n", strerror(rc)); + outln("pthread_attr_init: {}", strerror(rc)); return 1; } int detach_state = 99; // clearly invalid rc = pthread_attr_getdetachstate(&attributes, &detach_state); if (rc != 0) { - printf("pthread_attr_getdetachstate: %s\n", strerror(rc)); + outln("pthread_attr_getdetachstate: {}", strerror(rc)); return 2; } - printf("Default detach state: %s\n", detach_state == PTHREAD_CREATE_JOINABLE ? "joinable" : "detached"); + outln("Default detach state: {}", detach_state == PTHREAD_CREATE_JOINABLE ? "joinable" : "detached"); detach_state = PTHREAD_CREATE_DETACHED; rc = pthread_attr_setdetachstate(&attributes, detach_state); if (rc != 0) { - printf("pthread_attr_setdetachstate: %s\n", strerror(rc)); + outln("pthread_attr_setdetachstate: {}", strerror(rc)); return 3; } - printf("Set detach state on new thread to detached\n"); + outln("Set detach state on new thread to detached"); pthread_t thread_id; rc = pthread_create( &thread_id, &attributes, [](void*) -> void* { - printf("I'm the secondary thread :^)\n"); + outln("I'm the secondary thread :^)"); sleep(1); pthread_exit((void*)0xDEADBEEF); return nullptr; }, nullptr); if (rc != 0) { - printf("pthread_create: %s\n", strerror(rc)); + outln("pthread_create: {}", strerror(rc)); return 4; } void* ret_val; rc = pthread_join(thread_id, &ret_val); if (rc != 0 && rc != EINVAL) { - printf("pthread_join: %s\n", strerror(rc)); + outln("pthread_join: {}", strerror(rc)); return 5; } if (rc != EINVAL) { - printf("Expected EINVAL! Thread was joinable?\n"); + outln("Expected EINVAL! Thread was joinable?"); return 6; } sleep(2); - printf("Thread was created detached. I sure hope it exited on its own.\n"); + outln("Thread was created detached. I sure hope it exited on its own."); rc = pthread_attr_destroy(&attributes); if (rc != 0) { - printf("pthread_attr_destroy: %s\n", strerror(rc)); + outln("pthread_attr_destroy: {}", strerror(rc)); return 7; } @@ -176,30 +176,30 @@ int priority_test() pthread_attr_t attributes; int rc = pthread_attr_init(&attributes); if (rc != 0) { - printf("pthread_attr_init: %s\n", strerror(rc)); + outln("pthread_attr_init: {}", strerror(rc)); return 1; } struct sched_param sched_params; rc = pthread_attr_getschedparam(&attributes, &sched_params); if (rc != 0) { - printf("pthread_attr_getschedparam: %s\n", strerror(rc)); + outln("pthread_attr_getschedparam: {}", strerror(rc)); return 2; } - printf("Default priority: %d\n", sched_params.sched_priority); + outln("Default priority: {}", sched_params.sched_priority); sched_params.sched_priority = 3; rc = pthread_attr_setschedparam(&attributes, &sched_params); if (rc != 0) { - printf("pthread_attr_setschedparam: %s\n", strerror(rc)); + outln("pthread_attr_setschedparam: {}", strerror(rc)); return 3; } - printf("Set thread priority to 3\n"); + outln("Set thread priority to 3"); pthread_t thread_id; rc = pthread_create( &thread_id, &attributes, [](void*) -> void* { - printf("I'm the secondary thread :^)\n"); + outln("I'm the secondary thread :^)"); sleep(1); pthread_exit((void*)0xDEADBEEF); return nullptr; @@ -218,7 +218,7 @@ int priority_test() rc = pthread_attr_destroy(&attributes); if (rc != 0) { - printf("pthread_attr_destroy: %s\n", strerror(rc)); + outln("pthread_attr_destroy: {}", strerror(rc)); return 6; } @@ -230,30 +230,30 @@ int stack_size_test() pthread_attr_t attributes; int rc = pthread_attr_init(&attributes); if (rc != 0) { - printf("pthread_attr_init: %s\n", strerror(rc)); + outln("pthread_attr_init: {}", strerror(rc)); return 1; } size_t stack_size; rc = pthread_attr_getstacksize(&attributes, &stack_size); if (rc != 0) { - printf("pthread_attr_getstacksize: %s\n", strerror(rc)); + outln("pthread_attr_getstacksize: {}", strerror(rc)); return 2; } - printf("Default stack size: %zu\n", stack_size); + outln("Default stack size: {}", stack_size); stack_size = 8 * 1024 * 1024; rc = pthread_attr_setstacksize(&attributes, stack_size); if (rc != 0) { - printf("pthread_attr_setstacksize: %s\n", strerror(rc)); + outln("pthread_attr_setstacksize: {}", strerror(rc)); return 3; } - printf("Set thread stack size to 8 MiB\n"); + outln("Set thread stack size to 8 MiB"); pthread_t thread_id; rc = pthread_create( &thread_id, &attributes, [](void*) -> void* { - printf("I'm the secondary thread :^)\n"); + outln("I'm the secondary thread :^)"); sleep(1); pthread_exit((void*)0xDEADBEEF); return nullptr; @@ -272,7 +272,7 @@ int stack_size_test() rc = pthread_attr_destroy(&attributes); if (rc != 0) { - printf("pthread_attr_destroy: %s\n", strerror(rc)); + outln("pthread_attr_destroy: {}", strerror(rc)); return 6; } @@ -284,11 +284,11 @@ int staying_alive_test() pthread_t thread_id; int rc = pthread_create( &thread_id, nullptr, [](void*) -> void* { - printf("I'm the secondary thread :^)\n"); + outln("I'm the secondary thread :^)"); sleep(20); - printf("Secondary thread is still alive\n"); + outln("Secondary thread is still alive"); sleep(3520); - printf("Secondary thread exiting\n"); + outln("Secondary thread exiting"); pthread_exit((void*)0xDEADBEEF); return nullptr; }, @@ -299,10 +299,10 @@ int staying_alive_test() } sleep(1); - printf("I'm the main thread :^)\n"); + outln("I'm the main thread :^)"); sleep(3600); - printf("Main thread exiting\n"); + outln("Main thread exiting"); return 0; } @@ -311,7 +311,7 @@ int set_stack_test() pthread_attr_t attributes; int rc = pthread_attr_init(&attributes); if (rc < 0) { - printf("pthread_attr_init: %s\n", strerror(rc)); + outln("pthread_attr_init: {}", strerror(rc)); return 1; } @@ -325,29 +325,29 @@ int set_stack_test() rc = pthread_attr_setstack(&attributes, stack_addr, stack_size); if (rc != 0) { - printf("pthread_attr_setstack: %s\n", strerror(rc)); + outln("pthread_attr_setstack: {}", strerror(rc)); return 2; } - printf("Set thread stack to %p, size %zu\n", stack_addr, stack_size); + outln("Set thread stack to {:p}, size {}", stack_addr, stack_size); size_t stack_size_verify; void* stack_addr_verify; rc = pthread_attr_getstack(&attributes, &stack_addr_verify, &stack_size_verify); if (rc != 0) { - printf("pthread_attr_getstack: %s\n", strerror(rc)); + outln("pthread_attr_getstack: {}", strerror(rc)); return 3; } if (stack_addr != stack_addr_verify || stack_size != stack_size_verify) { - printf("Stack address and size don't match! addr: %p %p, size: %zu %zu\n", stack_addr, stack_addr_verify, stack_size, stack_size_verify); + outln("Stack address and size don't match! addr: {:p} {:p}, size: {} {}", stack_addr, stack_addr_verify, stack_size, stack_size_verify); return 4; } pthread_t thread_id; rc = pthread_create( &thread_id, &attributes, [](void*) -> void* { - printf("I'm the secondary thread :^)\n"); + outln("I'm the secondary thread :^)"); sleep(1); pthread_exit((void*)0xDEADBEEF); return nullptr; @@ -366,7 +366,7 @@ int set_stack_test() rc = pthread_attr_destroy(&attributes); if (rc != 0) { - printf("pthread_attr_destroy: %s\n", strerror(rc)); + outln("pthread_attr_destroy: {}", strerror(rc)); return 7; } diff --git a/Userland/Utilities/tty.cpp b/Userland/Utilities/tty.cpp index e28a8b3527..2476070b04 100644 --- a/Userland/Utilities/tty.cpp +++ b/Userland/Utilities/tty.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <stdio.h> #include <unistd.h> @@ -14,6 +15,6 @@ int main(int, char**) perror("Error"); return 1; } - printf("%s\n", tty); + outln("{}", tty); return 0; } diff --git a/Userland/Utilities/uptime.cpp b/Userland/Utilities/uptime.cpp index bec1e7ad34..530e85b88a 100644 --- a/Userland/Utilities/uptime.cpp +++ b/Userland/Utilities/uptime.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Format.h> #include <stdio.h> #include <unistd.h> @@ -35,24 +36,25 @@ int main(int, char**) unsigned seconds; sscanf(buffer, "%u", &seconds); - printf("Up "); + out("Up "); if (seconds / 86400 > 0) { - printf("%d day%s, ", seconds / 86400, (seconds / 86400) == 1 ? "" : "s"); + out("{} day{}, ", seconds / 86400, (seconds / 86400) == 1 ? "" : "s"); seconds %= 86400; } if (seconds / 3600 > 0) { - printf("%d hour%s, ", seconds / 3600, (seconds / 3600) == 1 ? "" : "s"); + out("{} hour{}, ", seconds / 3600, (seconds / 3600) == 1 ? "" : "s"); seconds %= 3600; } if (seconds / 60 > 0) { - printf("%d minute%s, ", seconds / 60, (seconds / 60) == 1 ? "" : "s"); + out("{} minute{}, ", seconds / 60, (seconds / 60) == 1 ? "" : "s"); seconds %= 60; } - printf("%d second%s\n", seconds, seconds == 1 ? "" : "s"); + out("{} second{}", seconds, seconds == 1 ? "" : "s"); + outln(); fclose(fp); return 0; diff --git a/Userland/Utilities/useradd.cpp b/Userland/Utilities/useradd.cpp index 04755687d7..37f8b60a1a 100644 --- a/Userland/Utilities/useradd.cpp +++ b/Userland/Utilities/useradd.cpp @@ -54,25 +54,25 @@ int main(int argc, char** argv) // Let's run a quick sanity check on username if (strpbrk(username, "\\/!@#$%^&*()~+=`:\n")) { - fprintf(stderr, "invalid character in username, %s\n", username); + warnln("invalid character in username, {}", username); return 1; } // Disallow names starting with _ and - if (username[0] == '_' || username[0] == '-' || !isalpha(username[0])) { - fprintf(stderr, "invalid username, %s\n", username); + warnln("invalid username, {}", username); return 1; } if (uid < 0) { - fprintf(stderr, "invalid uid %d!\n", uid); + warnln("invalid uid {}!", uid); return 3; } // First, let's sort out the uid for the user if (uid > 0) { if (getpwuid(static_cast<uid_t>(uid))) { - fprintf(stderr, "uid %u already exists!\n", uid); + warnln("uid {} already exists!", uid); return 4; } @@ -82,7 +82,7 @@ int main(int argc, char** argv) } if (gid < 0) { - fprintf(stderr, "invalid gid %d\n", gid); + warnln("invalid gid {}", gid); return 3; } diff --git a/Userland/Utilities/w.cpp b/Userland/Utilities/w.cpp index 62619d44d5..8768e74008 100644 --- a/Userland/Utilities/w.cpp +++ b/Userland/Utilities/w.cpp @@ -64,8 +64,7 @@ int main() auto now = time(nullptr); - printf("\033[1m%-10s %-12s %-16s %-6s %s\033[0m\n", - "USER", "TTY", "LOGIN@", "IDLE", "WHAT"); + outln("\033[1m{:10} {:12} {:16} {:6} {}\033[0m", "USER", "TTY", "LOGIN@", "IDLE", "WHAT"); json.value().as_object().for_each_member([&](auto& tty, auto& value) { const JsonObject& entry = value.as_object(); auto uid = entry.get("uid").to_u32(); @@ -99,12 +98,7 @@ int main() what = process.name; } - printf("%-10s %-12s %-16s %-6s %s\n", - username.characters(), - tty.characters(), - login_at.characters(), - idle_string.characters(), - what.characters()); + outln("{:10} {:12} {:16} {:6} {}", username, tty, login_at, idle_string, what); }); return 0; } diff --git a/Userland/Utilities/wasm.cpp b/Userland/Utilities/wasm.cpp index 0362774bff..f9a2d97dc5 100644 --- a/Userland/Utilities/wasm.cpp +++ b/Userland/Utilities/wasm.cpp @@ -27,15 +27,15 @@ static void print_buffer(ReadonlyBytes buffer, int split) for (size_t i = 0; i < buffer.size(); ++i) { if (split > 0) { if (i % split == 0 && i) { - printf(" "); + out(" "); for (size_t j = i - split; j < i; ++j) { auto ch = buffer[j]; - printf("%c", ch >= 32 && ch <= 127 ? ch : '.'); // silly hack + out("{:c}", ch >= 32 && ch <= 127 ? ch : '.'); // silly hack } - puts(""); + outln(); } } - printf("%02x ", buffer[i]); + out("{:02x} ", buffer[i]); } puts(""); } diff --git a/Userland/Utilities/watch.cpp b/Userland/Utilities/watch.cpp index e10fba6453..7b6955b70e 100644 --- a/Userland/Utilities/watch.cpp +++ b/Userland/Utilities/watch.cpp @@ -130,17 +130,18 @@ int main(int argc, char** argv) usecs_to_sleep = usecs_from(now, next_run_time); } // Clear the screen, then reset the cursor position to the top left. - fprintf(stderr, "\033[H\033[2J"); + warn("\033[H\033[2J"); // Print the header. if (!flag_noheader) { - fprintf(stderr, "%s\n\n", header.characters()); + warnln("{}", header); + warnln(); } else { fflush(stderr); } if (run_command(command) != 0) { exit_code = 1; if (flag_beep_on_fail) { - fprintf(stderr, "\a"); + warnln("\a"); fflush(stderr); } } diff --git a/Userland/Utilities/xargs.cpp b/Userland/Utilities/xargs.cpp index 9f40fd8be1..f48e909024 100644 --- a/Userland/Utilities/xargs.cpp +++ b/Userland/Utilities/xargs.cpp @@ -69,7 +69,7 @@ int main(int argc, char** argv) size_t max_lines = max(max_lines_for_one_command, 0); if (!split_with_nulls && strlen(specified_delimiter) > 1) { - fprintf(stderr, "xargs: the delimiter must be a single byte\n"); + warnln("xargs: the delimiter must be a single byte"); return 1; } @@ -205,8 +205,7 @@ bool run_command(Vector<char*>&& child_argv, bool verbose, bool is_stdin, int de if (verbose) { StringBuilder builder; builder.join(" ", child_argv); - fprintf(stderr, "xargs: %s\n", builder.to_string().characters()); - fflush(stderr); + warnln("xargs: {}", builder.to_string()); } auto pid = fork(); |