1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 00:17:46 +00:00

Userland: Replace most printf-style APIs with AK::Format APIs :^)

This commit is contained in:
Linus Groh 2021-05-31 15:43:25 +01:00
parent 4f1889c2cb
commit f5c35fccca
75 changed files with 642 additions and 644 deletions

View file

@ -51,7 +51,7 @@ int main(int argc, char** argv)
return 1; return 1;
} }
double remaining_delta = remaining_delta_timeval.tv_sec + remaining_delta_timeval.tv_usec / 1'000'000.0; 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; return 0;
} }

View file

@ -7,13 +7,12 @@
#include <AK/Optional.h> #include <AK/Optional.h>
#include <AK/String.h> #include <AK/String.h>
#include <LibCore/ElapsedTimer.h> #include <LibCore/ElapsedTimer.h>
#include <stdio.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
static void usage() static void usage()
{ {
printf("usage: allocate [number [unit (B/KiB/MiB)]]\n"); warnln("usage: allocate [number [unit (B/KiB/MiB)]]");
exit(1); exit(1);
} }
@ -60,21 +59,21 @@ int main(int argc, char** argv)
Core::ElapsedTimer timer; Core::ElapsedTimer timer;
printf("allocating memory (%d bytes)...\n", count); outln("allocating memory ({} bytes)...", count);
timer.start(); timer.start();
char* ptr = (char*)malloc(count); char* ptr = (char*)malloc(count);
if (!ptr) { if (!ptr) {
printf("failed.\n"); outln("failed.");
return 1; return 1;
} }
printf("done in %dms\n", timer.elapsed()); outln("done in {}ms", timer.elapsed());
auto pages = count / PAGE_SIZE; auto pages = count / PAGE_SIZE;
auto step = pages / 10; auto step = pages / 10;
Core::ElapsedTimer timer2; 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(); timer.start();
timer2.start(); timer2.start();
for (int i = 0; i < pages; ++i) { 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); 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(); 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++) { for (int i = 0; i < 10; i++) {
printf("%d\n", i); outln("{}", i);
sleep(1); sleep(1);
} }
printf("done.\n"); outln("done.");
printf("freeing memory...\n"); outln("freeing memory...");
timer.start(); timer.start();
free(ptr); free(ptr);
printf("done in %dms\n", timer.elapsed()); outln("done in {}ms", timer.elapsed());
return 0; return 0;
} }

View file

@ -25,21 +25,21 @@ int main(int argc, char** argv)
auto audio_client = Audio::ClientConnection::construct(); auto audio_client = Audio::ClientConnection::construct();
NonnullRefPtr<Audio::Loader> loader = Audio::Loader::create(path); NonnullRefPtr<Audio::Loader> loader = Audio::Loader::create(path);
if (loader->has_error()) { 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; return 1;
} }
printf("\033[34;1m Playing\033[0m: %s\n", path); outln("\033[34;1m Playing\033[0m: {}", path);
printf("\033[34;1m Format\033[0m: %u Hz, %u-bit, %s\n", outln("\033[34;1m Format\033[0m: {} Hz, {}-bit, {}",
loader->sample_rate(), loader->sample_rate(),
loader->bits_per_sample(), loader->bits_per_sample(),
loader->num_channels() == 1 ? "Mono" : "Stereo"); loader->num_channels() == 1 ? "Mono" : "Stereo");
printf("\033[34;1mProgress\033[0m: \033[s"); out("\033[34;1mProgress\033[0m: \033[s");
for (;;) { for (;;) {
auto samples = loader->get_more_samples(); auto samples = loader->get_more_samples();
if (samples) { if (samples) {
printf("\033[u"); out("\033[u");
printf("%d/%d", loader->loaded_samples(), loader->total_samples()); out("{}/{}", loader->loaded_samples(), loader->total_samples());
fflush(stdout); fflush(stdout);
audio_client->enqueue(*samples); audio_client->enqueue(*samples);
} else if (should_loop) { } else if (should_loop) {
@ -50,6 +50,6 @@ int main(int argc, char** argv)
break; break;
} }
} }
printf("\n"); outln();
return 0; return 0;
} }

View file

@ -8,17 +8,16 @@
#include <AK/ByteBuffer.h> #include <AK/ByteBuffer.h>
#include <AK/JsonObject.h> #include <AK/JsonObject.h>
#include <LibCore/File.h> #include <LibCore/File.h>
#include <stdio.h>
int main() int main()
{ {
auto file = Core::File::construct("/proc/net/arp"); auto file = Core::File::construct("/proc/net/arp");
if (!file->open(Core::OpenMode::ReadOnly)) { 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; return 1;
} }
printf("Address HWaddress\n"); outln("Address HWaddress");
auto file_contents = file->read_all(); auto file_contents = file->read_all();
auto json = JsonValue::from_string(file_contents); auto json = JsonValue::from_string(file_contents);
VERIFY(json.has_value()); VERIFY(json.has_value());
@ -28,9 +27,7 @@ int main()
auto ip_address = if_object.get("ip_address").to_string(); auto ip_address = if_object.get("ip_address").to_string();
auto mac_address = if_object.get("mac_address").to_string(); auto mac_address = if_object.get("mac_address").to_string();
printf("%-15s ", ip_address.characters()); outln("{:15} {:17}", ip_address, mac_address);
printf("%-17s ", mac_address.characters());
printf("\n");
}); });
return 0; return 0;

View file

@ -28,19 +28,19 @@ int main(int argc, char** argv)
if (!mute && !unmute && !volume) { if (!mute && !unmute && !volume) {
auto volume = audio_client->get_main_mix_volume(); auto volume = audio_client->get_main_mix_volume();
printf("Volume: %d\n", volume); outln("Volume: {}", volume);
return 0; return 0;
} }
if (!(mute ^ unmute ^ (volume != nullptr))) { 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; return 1;
} }
if (mute) { if (mute) {
audio_client->set_muted(true); audio_client->set_muted(true);
printf("Muted.\n"); outln("Muted.");
} else if (unmute) { } else if (unmute) {
audio_client->set_muted(false); audio_client->set_muted(false);
printf("Unmuted.\n"); outln("Unmuted.");
} else { } else {
auto new_volume = atoi(volume); auto new_volume = atoi(volume);
audio_client->set_main_mix_volume(new_volume); audio_client->set_main_mix_volume(new_volume);

View file

@ -56,5 +56,5 @@ int main(int argc, char** argv)
} }
auto encoded = encode_base64(buffer); auto encoded = encode_base64(buffer);
printf("%s\n", encoded.characters()); outln("{}", encoded);
} }

View file

@ -125,20 +125,20 @@ int main(int argc, char** argv)
clean_buffers(); clean_buffers();
if (year_mode) { if (year_mode) {
printf(" "); out(" Year {:04} ", year);
printf("Year %4d", year); outln();
printf(" \n\n"); outln();
for (int i = 1; i < 12; ++i) { for (int i = 1; i < 12; ++i) {
insert_month_to_print(0, i++, year); insert_month_to_print(0, i++, year);
insert_month_to_print(1, i++, year); insert_month_to_print(1, i++, year);
insert_month_to_print(2, i, year); insert_month_to_print(2, i, year);
printf("%s\n", print_buffer); outln("{}", print_buffer);
clean_buffers(); clean_buffers();
} }
} else { } else {
insert_month_to_print(0, month, year); insert_month_to_print(0, month, year);
printf("%s\n\n", print_buffer); outln("{}", print_buffer);
clean_buffers(); clean_buffers();
} }

View file

@ -33,7 +33,7 @@ int main(int argc, char** argv)
gid_t new_gid = -1; gid_t new_gid = -1;
if (String(gid_arg).is_empty()) { if (String(gid_arg).is_empty()) {
fprintf(stderr, "Empty gid option\n"); warnln("Empty gid option");
return 1; return 1;
} }
@ -43,7 +43,7 @@ int main(int argc, char** argv)
} else { } else {
auto* group = getgrnam(gid_arg); auto* group = getgrnam(gid_arg);
if (!group) { if (!group) {
fprintf(stderr, "Unknown group '%s'\n", gid_arg); warnln("Unknown group '{}'", gid_arg);
return 1; return 1;
} }
new_gid = group->gr_gid; new_gid = group->gr_gid;

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <AK/Optional.h> #include <AK/Optional.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
@ -58,8 +59,8 @@ int main(int argc, char** argv)
} }
if (argc < 3) { if (argc < 3) {
printf("usage: chmod <octal-mode> <path...>\n" warnln("usage: chmod <octal-mode> <path...>");
" chmod [[ugoa][+-=][rwx...],...] <path...>\n"); warnln(" chmod [[ugoa][+-=][rwx...],...] <path...>");
return 1; return 1;
} }
@ -100,7 +101,7 @@ int main(int argc, char** argv)
continue; continue;
} }
if (!tmp_mask.has_value()) { if (!tmp_mask.has_value()) {
fprintf(stderr, "chmod: invalid mode: %s\n", argv[1]); warnln("chmod: invalid mode: {}", argv[1]);
return 1; return 1;
} }
mask |= tmp_mask.value(); mask |= tmp_mask.value();

View file

@ -21,7 +21,7 @@ int main(int argc, char** argv)
} }
if (argc < 3) { if (argc < 3) {
printf("usage: chown <uid[:gid]> <path>\n"); warnln("usage: chown <uid[:gid]> <path>");
return 0; return 0;
} }
@ -30,11 +30,11 @@ int main(int argc, char** argv)
auto parts = String(argv[1]).split(':', true); auto parts = String(argv[1]).split(':', true);
if (parts.is_empty()) { if (parts.is_empty()) {
fprintf(stderr, "Empty uid/gid spec\n"); warnln("Empty uid/gid spec");
return 1; return 1;
} }
if (parts[0].is_empty() || (parts.size() == 2 && parts[1].is_empty()) || parts.size() > 2) { 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; return 1;
} }
@ -44,7 +44,7 @@ int main(int argc, char** argv)
} else { } else {
auto* passwd = getpwnam(parts[0].characters()); auto* passwd = getpwnam(parts[0].characters());
if (!passwd) { if (!passwd) {
fprintf(stderr, "Unknown user '%s'\n", parts[0].characters()); warnln("Unknown user '{}'", parts[0]);
return 1; return 1;
} }
new_uid = passwd->pw_uid; new_uid = passwd->pw_uid;
@ -57,7 +57,7 @@ int main(int argc, char** argv)
} else { } else {
auto* group = getgrnam(parts[1].characters()); auto* group = getgrnam(parts[1].characters());
if (!group) { if (!group) {
fprintf(stderr, "Unknown group '%s'\n", parts[1].characters()); warnln("Unknown group '{}'", parts[1]);
return 1; return 1;
} }
new_gid = group->gr_gid; new_gid = group->gr_gid;

View file

@ -65,7 +65,7 @@ int main(int argc, char** argv)
else if (part == "remount") else if (part == "remount")
flags |= MS_REMOUNT; flags |= MS_REMOUNT;
else if (part == "bind") 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 else
return false; return false;
} }

View file

@ -47,7 +47,7 @@ int main(int argc, char** argv)
} }
if (verbose) if (verbose)
printf("'%s' -> '%s'\n", source, destination); outln("'{}' -> '{}'", source, destination);
} }
return 0; return 0;
} }

View file

@ -249,7 +249,7 @@ int main(int argc, char** argv)
if (do_use_io_instruction || do_all_crash_types) { if (do_use_io_instruction || do_all_crash_types) {
Crash("Attempt to use an I/O instruction", [] { Crash("Attempt to use an I/O instruction", [] {
u8 keyboard_status = IO::in8(0x64); u8 keyboard_status = IO::in8(0x64);
printf("Keyboard status: %#02x\n", keyboard_status); outln("Keyboard status: {:#02x}", keyboard_status);
return Crash::Failure::DidNotCrash; return Crash::Failure::DidNotCrash;
}).run(run_type); }).run(run_type);
} }
@ -267,7 +267,7 @@ int main(int argc, char** argv)
perror("pledge"); perror("pledge");
return Crash::Failure::DidNotCrash; 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; return Crash::Failure::DidNotCrash;
}).run(run_type); }).run(run_type);
} }

View file

@ -33,7 +33,7 @@ struct Index {
static void print_usage_and_exit(int ret) static void print_usage_and_exit(int ret)
{ {
printf("Usage: cut -b list [File]\n"); warnln("Usage: cut -b list [File]");
exit(ret); exit(ret);
} }
@ -59,24 +59,24 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indices)
{ {
for (auto& token : tokens) { for (auto& token : tokens) {
if (token.length() == 0) { 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); print_usage_and_exit(1);
} }
if (token == "-") { 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); print_usage_and_exit(1);
} }
if (token[0] == '-') { if (token[0] == '-') {
auto index = token.substring(1, token.length() - 1).to_int(); auto index = token.substring(1, token.length() - 1).to_int();
if (!index.has_value()) { 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); print_usage_and_exit(1);
} }
if (index.value() == 0) { 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); 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] == '-') { } else if (token[token.length() - 1] == '-') {
auto index = token.substring(0, token.length() - 1).to_int(); auto index = token.substring(0, token.length() - 1).to_int();
if (!index.has_value()) { 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); print_usage_and_exit(1);
} }
if (index.value() == 0) { 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); print_usage_and_exit(1);
} }
Index tmp = { index.value(), -1, Index::Type::SliceIndex }; 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) { if (range.size() == 2) {
auto index1 = range[0].to_int(); auto index1 = range[0].to_int();
if (!index1.has_value()) { 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); print_usage_and_exit(1);
} }
auto index2 = range[1].to_int(); auto index2 = range[1].to_int();
if (!index2.has_value()) { 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); print_usage_and_exit(1);
} }
if (index1.value() > index2.value()) { if (index1.value() > index2.value()) {
fprintf(stderr, "cut: invalid decreasing range\n"); warnln("cut: invalid decreasing range");
print_usage_and_exit(1); print_usage_and_exit(1);
} else if (index1.value() == 0 || index2.value() == 0) { } 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); print_usage_and_exit(1);
} }
@ -123,19 +123,19 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indices)
} else if (range.size() == 1) { } else if (range.size() == 1) {
auto index = range[0].to_int(); auto index = range[0].to_int();
if (!index.has_value()) { 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); print_usage_and_exit(1);
} }
if (index.value() == 0) { 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); print_usage_and_exit(1);
} }
Index tmp = { index.value(), index.value(), Index::Type::SingleIndex }; Index tmp = { index.value(), index.value(), Index::Type::SingleIndex };
add_if_not_exists(indices, tmp); add_if_not_exists(indices, tmp);
} else { } else {
fprintf(stderr, "cut: invalid byte or character range\n"); warnln("cut: invalid byte or character range");
print_usage_and_exit(1); 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()) { if (!file.is_null()) {
fp = fopen(file.characters(), "r"); fp = fopen(file.characters(), "r");
if (!fp) { if (!fp) {
fprintf(stderr, "cut: Could not open file '%s'\n", file.characters()); warnln("cut: Could not open file '{}'", file);
return; return;
} }
} }
@ -161,17 +161,17 @@ static void cut_file(const String& file, const Vector<Index>& byte_vector)
line_length--; line_length--;
for (auto& i : byte_vector) { for (auto& i : byte_vector) {
if (i.m_type == Index::Type::SliceIndex && i.m_from < line_length) 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) 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) { 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 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); auto sub_string = String(line).substring(i.m_from - 1, to - i.m_from + 1);
printf("%s", sub_string.characters()); out("{}", sub_string);
} else } else
break; break;
} }
printf("\n"); outln();
} }
if (line) if (line)
@ -205,7 +205,7 @@ int main(int argc, char** argv)
} else if (argv[i][0] != '-') { } else if (argv[i][0] != '-') {
files.append(argv[i++]); files.append(argv[i++]);
} else { } else {
fprintf(stderr, "cut: invalid argument %s\n", argv[i]); warnln("cut: invalid argument {}", argv[i]);
print_usage_and_exit(1); print_usage_and_exit(1);
} }
} }

View file

@ -36,7 +36,7 @@ int main(int argc, char** argv)
auto number = String(set_date).to_uint(); auto number = String(set_date).to_uint();
if (!number.has_value()) { if (!number.has_value()) {
fprintf(stderr, "date: Invalid timestamp value"); warnln("date: Invalid timestamp value");
return 1; return 1;
} }
@ -52,7 +52,7 @@ int main(int argc, char** argv)
// FIXME: this should be improved and will need to be cleaned up // FIXME: this should be improved and will need to be cleaned up
// when additional output formats and formatting is supported // when additional output formats and formatting is supported
if (print_unix_date && print_iso_8601 && print_rfc_3339 && print_rfc_5322) { 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; return 1;
} }
@ -60,19 +60,19 @@ int main(int argc, char** argv)
auto date = Core::DateTime::from_timestamp(now); auto date = Core::DateTime::from_timestamp(now);
if (print_unix_date) { if (print_unix_date) {
printf("%lld\n", (long long)now); outln("{}", (long long)now);
return 0; return 0;
} else if (print_iso_8601) { } 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; return 0;
} else if (print_rfc_5322) { } 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; return 0;
} else if (print_rfc_3339) { } 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; return 0;
} else { } else {
printf("%s\n", date.to_string().characters()); outln("{}", date.to_string());
return 0; return 0;
} }
} }

View file

@ -41,7 +41,7 @@ static String split_at_equals(const char* argument)
auto values = string_value.split('='); auto values = string_value.split('=');
if (values.size() != 2) { if (values.size() != 2) {
fprintf(stderr, "Unable to parse: %s\n", argument); warnln("Unable to parse: {}", argument);
return {}; return {};
} else { } else {
return values[1]; 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); fd = open(value.characters(), flags, 0666);
if (fd == -1) { if (fd == -1) {
fprintf(stderr, "Unable to open: %s\n", value.characters()); warnln("Unable to open: {}", value);
return -1; return -1;
} else { } else {
return 0; 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(); Optional<unsigned> numeric_optional = value.to_uint();
if (!numeric_optional.has_value()) { if (!numeric_optional.has_value()) {
fprintf(stderr, "Invalid size-value: %s\n", value.characters()); warnln("Invalid size-value: {}", value);
return -1; return -1;
} }
numeric_value = numeric_optional.value() * suffix_multiplier; numeric_value = numeric_optional.value() * suffix_multiplier;
if (numeric_value < 1) { if (numeric_value < 1) {
fprintf(stderr, "Invalid size-value: %lu\n", numeric_value); warnln("Invalid size-value: {}", numeric_value);
return -1; return -1;
} else { } else {
return 0; return 0;
@ -119,7 +119,7 @@ static int handle_status_arguments(Status& status, const char* argument)
status = None; status = None;
return 0; return 0;
} else { } else {
fprintf(stderr, "Unknown status: %s\n", value.characters()); warnln("Unknown status: {}", value);
return -1; return -1;
} }
} }
@ -144,7 +144,7 @@ int main(int argc, char** argv)
for (int a = 1; a < argc; a++) { for (int a = 1; a < argc; a++) {
if (!strcmp(argv[a], "--help")) { if (!strcmp(argv[a], "--help")) {
printf("%s", usage); out("{}", usage);
return 0; return 0;
} else if (!strncmp(argv[a], "if=", 3)) { } else if (!strncmp(argv[a], "if=", 3)) {
if (handle_io_file_arguments(input_fd, input_flags, argv[a]) < 0) { if (handle_io_file_arguments(input_fd, input_flags, argv[a]) < 0) {
@ -175,19 +175,19 @@ int main(int argc, char** argv)
return 1; return 1;
} }
} else { } else {
fprintf(stderr, "%s", usage); warn("{}", usage);
return 1; return 1;
} }
} }
if ((buffer = (uint8_t*)malloc(block_size)) == nullptr) { 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; return -1;
} }
if (seek > 0) { if (seek > 0) {
if (lseek(output_fd, seek * block_size, SEEK_SET) < 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; return -1;
} }
} }
@ -195,7 +195,7 @@ int main(int argc, char** argv)
while (1) { while (1) {
nread = read(input_fd, buffer, block_size); nread = read(input_fd, buffer, block_size);
if (nread < 0) { if (nread < 0) {
fprintf(stderr, "Cannot read from the input.\n"); warnln("Cannot read from the input.");
break; break;
} else if (nread == 0) { } else if (nread == 0) {
break; break;
@ -212,7 +212,7 @@ int main(int argc, char** argv)
nwritten = write(output_fd, buffer, nread); nwritten = write(output_fd, buffer, nread);
if (nwritten < 0) { if (nwritten < 0) {
fprintf(stderr, "Cannot write to the output.\n"); warnln("Cannot write to the output.");
break; break;
} else if (nwritten == 0) { } else if (nwritten == 0) {
break; break;
@ -233,9 +233,9 @@ int main(int argc, char** argv)
} }
if (status == Default) { if (status == Default) {
fprintf(stderr, "%lu+%lu blocks in\n", total_blocks_in, partial_blocks_in); warnln("{}+{} blocks in", total_blocks_in, partial_blocks_in);
fprintf(stderr, "%lu+%lu blocks out\n", total_blocks_out, partial_blocks_out); warnln("{}+{} blocks out", total_blocks_out, partial_blocks_out);
fprintf(stderr, "%lu bytes copied.\n", total_bytes_copied); warnln("{} bytes copied.", total_bytes_copied);
} }
free(buffer); free(buffer);

View file

@ -107,7 +107,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
} }
auto date = Core::DateTime::from_timestamp(time(nullptr)); 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; return 0;
} }

View file

@ -13,7 +13,6 @@
#include <LibCore/ArgsParser.h> #include <LibCore/ArgsParser.h>
#include <LibCore/File.h> #include <LibCore/File.h>
#include <inttypes.h> #include <inttypes.h>
#include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
static bool flag_human_readable = false; static bool flag_human_readable = false;
@ -37,14 +36,14 @@ int main(int argc, char** argv)
auto file = Core::File::construct("/proc/df"); auto file = Core::File::construct("/proc/df");
if (!file->open(Core::OpenMode::ReadOnly)) { 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; return 1;
} }
if (flag_human_readable) { if (flag_human_readable) {
printf("Filesystem Size Used Available Mount point\n"); outln("Filesystem Size Used Available Mount point");
} else { } else {
printf("Filesystem Blocks Used Available Mount point\n"); outln("Filesystem Blocks Used Available Mount point");
} }
auto file_contents = file->read_all(); 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 block_size = fs_object.get("block_size").to_u64();
auto mount_point = fs_object.get("mount_point").to_string(); auto mount_point = fs_object.get("mount_point").to_string();
printf("%-10s", fs.characters()); out("{:10}", fs);
if (flag_human_readable) { if (flag_human_readable) {
printf("%10s ", human_readable_size(total_block_count * block_size).characters()); out("{:>10} ", human_readable_size(total_block_count * block_size));
printf("%10s ", human_readable_size((total_block_count - free_block_count) * block_size).characters()); out("{:>10} ", human_readable_size((total_block_count - free_block_count) * block_size));
printf("%10s ", human_readable_size(free_block_count * block_size).characters()); out("{:>10} ", human_readable_size(free_block_count * block_size));
} else { } else {
printf("%10" PRIu64 " ", (uint64_t)total_block_count); out("{:>10} ", (uint64_t)total_block_count);
printf("%10" PRIu64 " ", (uint64_t)(total_block_count - free_block_count)); out("{:>10} ", (uint64_t)(total_block_count - free_block_count));
printf("%10" PRIu64 " ", (uint64_t)free_block_count); out("{:>10} ", (uint64_t)free_block_count);
} }
printf("%s", mount_point.characters()); out("{}", mount_point);
printf("\n"); outln();
}); });
return 0; return 0;

View file

@ -25,13 +25,12 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
unveil(nullptr, nullptr); unveil(nullptr, nullptr);
auto f = Core::File::construct("/proc/dmesg"); auto file = Core::File::construct("/proc/dmesg");
if (!f->open(Core::OpenMode::ReadOnly)) { if (!file->open(Core::OpenMode::ReadOnly)) {
fprintf(stderr, "open: failed to open /proc/dmesg: %s\n", f->error_string()); warnln("Failed to open {}: {}", file->name(), file->error_string());
return 1; return 1;
} }
const auto& b = f->read_all(); auto buffer = file->read_all();
for (size_t i = 0; i < b.size(); ++i) out("{}", String::copy(buffer));
putchar(b[i]);
return 0; return 0;
} }

View file

@ -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)) { if (--max_depth >= 0 && S_ISDIR(path_stat.st_mode)) {
auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir); auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir);
if (di.has_error()) { if (di.has_error()) {
fprintf(stderr, "DirIterator: %s\n", di.error_string()); warnln("DirIterator: {}", di.error_string());
return 1; return 1;
} }
while (di.has_next()) { 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); size = size / block_size + (size % block_size != 0);
if (du_option.time_type == DuOption::TimeType::NotUsed) if (du_option.time_type == DuOption::TimeType::NotUsed)
printf("%" PRIi64 "\t%s\n", size, path.characters()); outln("{}\t{}", size, path);
else { else {
auto time = path_stat.st_mtime; auto time = path_stat.st_mtime;
switch (du_option.time_type) { 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(); 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; return 0;

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/String.h>
#include <LibCore/ArgsParser.h> #include <LibCore/ArgsParser.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.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.add_positional_argument(values, "Values to print out", "string", Core::ArgsParser::Required::No);
args_parser.parse(argc, argv); args_parser.parse(argc, argv);
for (size_t i = 0; i < values.size(); ++i) { out("{}", String::join(' ', values));
fputs(values[i], stdout);
if (i != values.size() - 1)
fputc(' ', stdout);
}
if (!no_trailing_newline) if (!no_trailing_newline)
printf("\n"); outln();
return 0; return 0;
} }

View file

@ -57,7 +57,7 @@ int main(int argc, char** argv)
if (new_argv.size() == 0) { if (new_argv.size() == 0) {
for (auto entry = environ; *entry != nullptr; ++entry) for (auto entry = environ; *entry != nullptr; ++entry)
printf("%s\n", *entry); outln("{}", *entry);
return 0; return 0;
} }

View file

@ -5,6 +5,7 @@
*/ */
#include <AK/Assertions.h> #include <AK/Assertions.h>
#include <AK/Format.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
@ -12,7 +13,7 @@
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
if (argc < 2) { if (argc < 2) {
printf("usage: fgrep <str>\n"); warnln("usage: fgrep <str>");
return 0; return 0;
} }
for (;;) { for (;;) {

View file

@ -5,6 +5,7 @@
*/ */
#include <AK/Assertions.h> #include <AK/Assertions.h>
#include <AK/CheckedFormatString.h>
#include <AK/LexicalPath.h> #include <AK/LexicalPath.h>
#include <AK/NonnullOwnPtr.h> #include <AK/NonnullOwnPtr.h>
#include <AK/OwnPtr.h> #include <AK/OwnPtr.h>
@ -23,16 +24,13 @@ bool g_follow_symlinks = false;
bool g_there_was_an_error = false; bool g_there_was_an_error = false;
bool g_have_seen_action_command = 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); warn("\033[31m");
warn(move(fmtstr), parameters...);
va_list ap; warn("\033[0m");
va_start(ap, format); warnln();
vfprintf(stderr, format, ap);
va_end(ap);
fputs("\033[0m\n", stderr);
exit(1); exit(1);
} }
@ -67,7 +65,7 @@ public:
{ {
StringView type = arg; StringView type = arg;
if (type.length() != 1 || !StringView("bcdlpfs").contains(type[0])) 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]; m_type = type[0];
} }
@ -105,7 +103,7 @@ public:
{ {
auto number = StringView(arg).to_uint(); auto number = StringView(arg).to_uint();
if (!number.has_value()) if (!number.has_value())
fatal_error("Invalid number: \033[1m%s", arg); fatal_error("Invalid number: \033[1m{}", arg);
m_links = number.value(); m_links = number.value();
} }
@ -128,7 +126,7 @@ public:
// Attempt to parse it as decimal UID. // Attempt to parse it as decimal UID.
auto number = StringView(arg).to_uint(); auto number = StringView(arg).to_uint();
if (!number.has_value()) if (!number.has_value())
fatal_error("Invalid user: \033[1m%s", arg); fatal_error("Invalid user: \033[1m{}", arg);
m_uid = number.value(); m_uid = number.value();
} }
} }
@ -152,7 +150,7 @@ public:
// Attempt to parse it as decimal GID. // Attempt to parse it as decimal GID.
auto number = StringView(arg).to_int(); auto number = StringView(arg).to_int();
if (!number.has_value()) if (!number.has_value())
fatal_error("Invalid group: \033[1m%s", arg); fatal_error("Invalid group: \033[1m{}", arg);
m_gid = number.value(); m_gid = number.value();
} }
} }
@ -177,7 +175,7 @@ public:
} }
auto number = view.to_uint(); auto number = view.to_uint();
if (!number.has_value()) if (!number.has_value())
fatal_error("Invalid size: \033[1m%s", arg); fatal_error("Invalid size: \033[1m{}", arg);
m_size = number.value(); m_size = number.value();
} }
@ -224,7 +222,7 @@ public:
private: private:
virtual bool evaluate(const char* file_path) const override virtual bool evaluate(const char* file_path) const override
{ {
printf("%s%c", file_path, m_terminator); out("{}{}", file_path, m_terminator);
return true; return true;
} }
@ -354,7 +352,7 @@ static OwnPtr<Command> parse_simple_command(char* argv[])
command_argv.append(argv[optind]); command_argv.append(argv[optind]);
return make<ExecCommand>(move(command_argv)); return make<ExecCommand>(move(command_argv));
} else { } 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()) { 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; g_there_was_an_error = true;
} }
} }

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <errno.h> #include <errno.h>
#include <spawn.h> #include <spawn.h>
#include <stdio.h> #include <stdio.h>
@ -14,7 +15,7 @@
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
if (argc < 3) { if (argc < 3) {
printf("usage: flock <path> <command...>\n"); warnln("usage: flock <path> <command...>");
return 0; return 0;
} }

View file

@ -30,7 +30,7 @@ static bool g_should_output_color = false;
static void handle_sigint(int) static void handle_sigint(int)
{ {
printf("Debugger: SIGINT\n"); outln("Debugger: SIGINT");
// The destructor of DebugSession takes care of detaching // The destructor of DebugSession takes care of detaching
g_debug_session = nullptr; 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) static void print_syscall(PtraceRegisters& regs, size_t depth)
{ {
for (size_t i = 0; i < depth; ++i) { for (size_t i = 0; i < depth; ++i) {
printf(" "); out(" ");
} }
const char* begin_color = g_should_output_color ? "\033[34;1m" : ""; const char* begin_color = g_should_output_color ? "\033[34;1m" : "";
const char* end_color = g_should_output_color ? "\033[0m" : ""; const char* end_color = g_should_output_color ? "\033[0m" : "";

View file

@ -26,9 +26,9 @@ enum class BinaryFileMode {
template<typename... Ts> template<typename... Ts>
void fail(StringView format, Ts... args) void fail(StringView format, Ts... args)
{ {
fprintf(stderr, "\x1b[31m"); warn("\x1b[31m");
warnln(format, forward<Ts>(args)...); warnln(format, forward<Ts>(args)...);
fprintf(stderr, "\x1b[0m"); warn("\x1b[0m");
abort(); abort();
} }

View file

@ -42,13 +42,13 @@ int main(int argc, char** argv)
} }
if (argc != 2 || !strcmp(argv[1], "--help")) { if (argc != 2 || !strcmp(argv[1], "--help")) {
fprintf(stderr, "usage: gron <file>\n"); warnln("usage: gron <file>");
fprintf(stderr, "Print each value in a JSON file with its fully expanded key.\n"); warnln("Print each value in a JSON file with its fully expanded key.");
return 0; return 0;
} }
auto file = Core::File::construct(argv[1]); auto file = Core::File::construct(argv[1]);
if (!file->open(Core::OpenMode::ReadOnly)) { 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; return 1;
} }
@ -79,19 +79,19 @@ int main(int argc, char** argv)
static void print(const String& name, const JsonValue& value, Vector<String>& trail) static void print(const String& name, const JsonValue& value, Vector<String>& trail)
{ {
for (size_t i = 0; i < trail.size(); ++i) 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()) { 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)); trail.append(String::formatted("{}{}{}.", color_name, name, color_off));
value.as_object().for_each_member([&](auto& on, auto& ov) { print(on, ov, trail); }); value.as_object().for_each_member([&](auto& on, auto& ov) { print(on, ov, trail); });
trail.take_last(); trail.take_last();
return; return;
} }
if (value.is_array()) { 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)); trail.append(String::formatted("{}{}{}", color_name, name, color_off));
for (int i = 0; i < value.as_array().size(); ++i) { 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); 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()) { switch (value.type()) {
case JsonValue::Type::Null: case JsonValue::Type::Null:
printf("%s", color_null); out("{}", color_null);
break; break;
case JsonValue::Type::Bool: case JsonValue::Type::Bool:
printf("%s", color_bool); out("{}", color_bool);
break; break;
case JsonValue::Type::String: case JsonValue::Type::String:
printf("%s", color_string); out("{}", color_string);
break; break;
default: default:
printf("%s", color_index); out("{}", color_index);
break; break;
} }
printf("%s%s;\n", value.serialized<StringBuilder>().characters(), color_off); outln("{}{};", value.serialized<StringBuilder>(), color_off);
} }

View file

@ -78,16 +78,16 @@ int head(const String& filename, bool print_filename, ssize_t line_count, ssize_
} else { } else {
fd = open(filename.characters(), O_RDONLY); fd = open(filename.characters(), O_RDONLY);
if (fd < 0) { 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; return 1;
} }
} }
if (print_filename) { if (print_filename) {
if (is_stdin) { if (is_stdin) {
puts("==> standard input <=="); outln("==> standard input <==");
} else { } else {
printf("==> %s <==\n", filename.characters()); outln("==> {} <==", filename);
} }
} }

View file

@ -37,15 +37,15 @@ int main(int argc, char** argv)
auto print_line = [&] { auto print_line = [&] {
for (size_t i = 0; i < 16; ++i) { for (size_t i = 0; i < 16; ++i) {
if (i < line.size()) if (i < line.size())
printf("%02x ", line[i]); out("{:02x} ", line[i]);
else else
printf(" "); out(" ");
if (i == 7) if (i == 7)
printf(" "); out(" ");
} }
printf(" "); out(" ");
for (size_t i = 0; i < 16; ++i) { for (size_t i = 0; i < 16; ++i) {
if (i < line.size() && isprint(line[i])) if (i < line.size() && isprint(line[i]))

View file

@ -35,22 +35,22 @@ int main(int argc, char** argv)
// Okay, let's do a reverse lookup. // Okay, let's do a reverse lookup.
auto* hostent = gethostbyaddr(&addr.sin_addr, sizeof(in_addr), AF_INET); auto* hostent = gethostbyaddr(&addr.sin_addr, sizeof(in_addr), AF_INET);
if (!hostent) { if (!hostent) {
fprintf(stderr, "Reverse lookup failed for '%s'\n", name_or_ip); warnln("Reverse lookup failed for '{}'", name_or_ip);
return 1; return 1;
} }
printf("%s is %s\n", name_or_ip, hostent->h_name); outln("{} is {}", name_or_ip, hostent->h_name);
return 0; return 0;
} }
auto* hostent = gethostbyname(name_or_ip); auto* hostent = gethostbyname(name_or_ip);
if (!hostent) { if (!hostent) {
fprintf(stderr, "Lookup failed for '%s'\n", name_or_ip); warnln("Lookup failed for '{}'", name_or_ip);
return 1; return 1;
} }
char buffer[INET_ADDRSTRLEN]; char buffer[INET_ADDRSTRLEN];
const char* ip_str = inet_ntop(AF_INET, hostent->h_addr_list[0], buffer, sizeof(buffer)); 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; return 0;
} }

View file

@ -25,10 +25,10 @@ int main(int argc, char** argv)
perror("gethostname"); perror("gethostname");
return 1; return 1;
} }
printf("%s\n", buffer); outln("{}", buffer);
} else { } else {
if (strlen(hostname) >= HOST_NAME_MAX) { 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; return 1;
} }
sethostname(hostname, strlen(hostname)); sethostname(hostname, strlen(hostname));

View file

@ -48,12 +48,12 @@ int main(int argc, char** argv)
args_parser.parse(argc, argv); args_parser.parse(argc, argv);
if (flag_print_name && !(flag_print_uid || flag_print_gid || flag_print_gid_all)) { 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; return 1;
} }
if (flag_print_uid + flag_print_gid + flag_print_gid_all > 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; return 1;
} }
@ -65,9 +65,9 @@ static bool print_uid_object(uid_t uid)
{ {
if (flag_print_name) { if (flag_print_name) {
struct passwd* pw = getpwuid(uid); struct passwd* pw = getpwuid(uid);
printf("%s", pw ? pw->pw_name : "n/a"); out("{}", pw ? pw->pw_name : "n/a");
} else } else
printf("%u", uid); out("{}", uid);
return true; return true;
} }
@ -76,9 +76,9 @@ static bool print_gid_object(gid_t gid)
{ {
if (flag_print_name) { if (flag_print_name) {
struct group* gr = getgrgid(gid); struct group* gr = getgrgid(gid);
printf("%s", gr ? gr->gr_name : "n/a"); out("{}", gr ? gr->gr_name : "n/a");
} else } else
printf("%u", gid); out("{}", gid);
return true; return true;
} }
@ -97,11 +97,11 @@ static bool print_gid_list()
for (int g = 0; g < extra_gid_count; ++g) { for (int g = 0; g < extra_gid_count; ++g) {
auto* gr = getgrgid(extra_gids[g]); auto* gr = getgrgid(extra_gids[g]);
if (flag_print_name && gr) if (flag_print_name && gr)
printf("%s", gr->gr_name); out("{}", gr->gr_name);
else else
printf("%u", extra_gids[g]); out("{}", extra_gids[g]);
if (g != extra_gid_count - 1) if (g != extra_gid_count - 1)
printf(" "); out(" ");
} }
} }
return true; return true;
@ -114,7 +114,7 @@ static bool print_full_id_list()
struct passwd* pw = getpwuid(uid); struct passwd* pw = getpwuid(uid);
struct group* gr = getgrgid(gid); 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); int extra_gid_count = getgroups(0, nullptr);
if (extra_gid_count) { if (extra_gid_count) {
@ -124,15 +124,15 @@ static bool print_full_id_list()
perror("\ngetgroups"); perror("\ngetgroups");
return false; return false;
} }
printf(" groups="); out(" groups=");
for (int g = 0; g < extra_gid_count; ++g) { for (int g = 0; g < extra_gid_count; ++g) {
auto* gr = getgrgid(extra_gids[g]); auto* gr = getgrgid(extra_gids[g]);
if (gr) if (gr)
printf("%u(%s)", extra_gids[g], gr->gr_name); out("{}({})", extra_gids[g], gr->gr_name);
else else
printf("%u", extra_gids[g]); out("{}", extra_gids[g]);
if (g != extra_gid_count - 1) if (g != extra_gid_count - 1)
printf(","); out(",");
} }
} }
return true; return true;
@ -154,6 +154,6 @@ static int print_id_objects()
return 1; return 1;
} }
printf("\n"); outln();
return 0; return 0;
} }

View file

@ -39,7 +39,7 @@ int main(int argc, char** argv)
auto file = Core::File::construct("/proc/net/adapters"); auto file = Core::File::construct("/proc/net/adapters");
if (!file->open(Core::OpenMode::ReadOnly)) { 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; return 1;
} }
@ -61,21 +61,21 @@ int main(int argc, char** argv)
auto bytes_out = if_object.get("bytes_out").to_u32(); auto bytes_out = if_object.get("bytes_out").to_u32();
auto mtu = if_object.get("mtu").to_u32(); auto mtu = if_object.get("mtu").to_u32();
printf("%s:\n", name.characters()); outln("{}:", name);
printf("\tmac: %s\n", mac_address.characters()); outln("\tmac: {}", mac_address);
printf("\tipv4: %s\n", ipv4_address.characters()); outln("\tipv4: {}", ipv4_address);
printf("\tnetmask: %s\n", netmask.characters()); outln("\tnetmask: {}", netmask);
printf("\tgateway: %s\n", gateway.characters()); outln("\tgateway: {}", gateway);
printf("\tclass: %s\n", class_name.characters()); outln("\tclass: {}", class_name);
printf("\tRX: %u packets %u bytes (%s)\n", packets_in, bytes_in, human_readable_size(bytes_in).characters()); outln("\tRX: {} packets {} bytes ({})", packets_in, bytes_in, human_readable_size(bytes_in));
printf("\tTX: %u packets %u bytes (%s)\n", packets_out, bytes_out, human_readable_size(bytes_out).characters()); outln("\tTX: {} packets {} bytes ({})", packets_out, bytes_out, human_readable_size(bytes_out));
printf("\tMTU: %u\n", mtu); outln("\tMTU: {}", mtu);
printf("\n"); outln();
}); });
} else { } else {
if (!value_adapter) { if (!value_adapter) {
fprintf(stderr, "No network adapter was specified.\n"); warnln("No network adapter was specified.");
return 1; return 1;
} }
@ -85,7 +85,7 @@ int main(int argc, char** argv)
auto address = IPv4Address::from_string(value_ipv4); auto address = IPv4Address::from_string(value_ipv4);
if (!address.has_value()) { if (!address.has_value()) {
fprintf(stderr, "Invalid IPv4 address: '%s'\n", value_ipv4); warnln("Invalid IPv4 address: '{}'", value_ipv4);
return 1; return 1;
} }
@ -100,7 +100,7 @@ int main(int argc, char** argv)
bool fits = ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ); bool fits = ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ);
if (!fits) { if (!fits) {
fprintf(stderr, "Interface name '%s' is too long\n", ifname.characters()); warnln("Interface name '{}' is too long", ifname);
return 1; return 1;
} }
ifr.ifr_addr.sa_family = AF_INET; ifr.ifr_addr.sa_family = AF_INET;
@ -117,7 +117,7 @@ int main(int argc, char** argv)
auto address = IPv4Address::from_string(value_mask); auto address = IPv4Address::from_string(value_mask);
if (!address.has_value()) { if (!address.has_value()) {
fprintf(stderr, "Invalid IPv4 mask: '%s'\n", value_mask); warnln("Invalid IPv4 mask: '{}'", value_mask);
return 1; return 1;
} }
@ -132,7 +132,7 @@ int main(int argc, char** argv)
bool fits = ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ); bool fits = ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ);
if (!fits) { if (!fits) {
fprintf(stderr, "Interface name '%s' is too long\n", ifname.characters()); warnln("Interface name '{}' is too long", ifname);
return 1; return 1;
} }
ifr.ifr_netmask.sa_family = AF_INET; ifr.ifr_netmask.sa_family = AF_INET;

View file

@ -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 * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -30,7 +30,7 @@ int main(int argc, char** argv)
args_parser.parse(argc, argv); args_parser.parse(argc, argv);
if (!Core::File::exists(path)) { if (!Core::File::exists(path)) {
fprintf(stderr, "File does not exist: '%s'\n", path); warnln("File does not exist: '{}'", path);
return 1; return 1;
} }
@ -44,7 +44,7 @@ int main(int argc, char** argv)
auto value = config->read_entry(group, key); auto value = config->read_entry(group, key);
if (!value.is_empty()) if (!value.is_empty())
printf("%s\n", value.characters()); outln("{}", value);
return 0; return 0;
} }

View file

@ -15,7 +15,7 @@
static void print_usage_and_exit() static void print_usage_and_exit()
{ {
printf("usage: kill [-signal] <PID>\n"); warnln("usage: kill [-signal] <PID>");
exit(1); exit(1);
} }
@ -57,14 +57,14 @@ int main(int argc, char** argv)
number = StringView(&argv[1][1]).to_uint(); number = StringView(&argv[1][1]).to_uint();
if (!number.has_value()) { 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; return 2;
} }
signum = number.value(); signum = number.value();
} }
auto pid_opt = String(argv[pid_argi]).to_int(); auto pid_opt = String(argv[pid_argi]).to_int();
if (!pid_opt.has_value()) { 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; return 3;
} }
pid_t pid = pid_opt.value(); pid_t pid = pid_opt.value();

View file

@ -13,7 +13,7 @@
static void print_usage_and_exit() static void print_usage_and_exit()
{ {
printf("usage: killall [-signal] process_name\n"); warnln("usage: killall [-signal] process_name");
exit(1); exit(1);
} }
@ -60,7 +60,7 @@ int main(int argc, char** argv)
number = String(&argv[1][1]).to_uint(); number = String(&argv[1][1]).to_uint();
if (!number.has_value()) { 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; return 2;
} }
signum = number.value(); signum = number.value();

View file

@ -28,7 +28,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
auto proc_interrupts = Core::File::construct("/proc/interrupts"); auto proc_interrupts = Core::File::construct("/proc/interrupts");
if (!proc_interrupts->open(Core::OpenMode::ReadOnly)) { if (!proc_interrupts->open(Core::OpenMode::ReadOnly)) {
fprintf(stderr, "Error: %s\n", proc_interrupts->error_string()); warnln("Error: {}", proc_interrupts->error_string());
return 1; return 1;
} }
@ -37,7 +37,7 @@ int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
return 1; return 1;
} }
printf("%4s %-10s\n", " ", "CPU0"); outln(" CPU0");
auto file_contents = proc_interrupts->read_all(); auto file_contents = proc_interrupts->read_all();
auto json = JsonValue::from_string(file_contents); auto json = JsonValue::from_string(file_contents);
VERIFY(json.has_value()); 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 controller = handler.get("controller").to_string();
auto call_count = handler.get("call_count").to_string(); auto call_count = handler.get("call_count").to_string();
printf("%4s: %-10s %-10s %-30s\n", outln("{:>4}: {:10} {:10} {:30}", interrupt, call_count, controller, purpose);
interrupt.characters(), call_count.characters(), controller.characters(), purpose.characters());
}); });
return 0; return 0;

View file

@ -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); auto file = Core::File::open(String::formatted("/proc/{}/fds", pid), Core::OpenMode::ReadOnly);
if (file.is_error()) { if (file.is_error()) {
printf("lsof: PID %d: %s\n", pid, file.error().characters()); outln("lsof: PID {}: {}", pid, file.error());
return Vector<OpenFile>(); return Vector<OpenFile>();
} }
auto data = file.value()->read_all(); 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) 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[]) int main(int argc, char* argv[])
@ -145,7 +145,7 @@ int main(int argc, char* argv[])
arg_uid_int = arg.value(); 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(); auto processes = Core::ProcessStatisticsReader::get_all();
if (!processes.has_value()) if (!processes.has_value())
return 1; return 1;

View file

@ -56,7 +56,7 @@ int main(int argc, char** argv)
auto proc_pci = Core::File::construct("/proc/pci"); auto proc_pci = Core::File::construct("/proc/pci");
if (!proc_pci->open(Core::OpenMode::ReadOnly)) { 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; return 1;
} }

View file

@ -70,7 +70,7 @@ int main(int argc, char* argv[])
} }
} }
if (!section) { if (!section) {
fprintf(stderr, "No man page for %s\n", name); warnln("No man page for {}", name);
exit(1); exit(1);
} }
} }
@ -92,11 +92,11 @@ int main(int argc, char* argv[])
auto buffer = file->read_all(); auto buffer = file->read_all();
auto source = String::copy(buffer); 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); auto document = Markdown::Document::parse(source);
VERIFY(document); VERIFY(document);
String rendered = document->render_for_terminal(view_width); String rendered = document->render_for_terminal(view_width);
printf("%s", rendered.characters()); out("{}", rendered);
} }

View file

@ -51,7 +51,7 @@ int main(int argc, char* argv[])
success = file->open(Core::OpenMode::ReadOnly); success = file->open(Core::OpenMode::ReadOnly);
} }
if (!success) { if (!success) {
fprintf(stderr, "Error: %s\n", file->error_string()); warnln("Error: {}", file->error_string());
return 1; return 1;
} }
@ -67,10 +67,10 @@ int main(int argc, char* argv[])
auto document = Markdown::Document::parse(input); auto document = Markdown::Document::parse(input);
if (!document) { if (!document) {
fprintf(stderr, "Error parsing\n"); warnln("Error parsing");
return 1; return 1;
} }
String res = html ? document->render_to_html() : document->render_for_terminal(view_width); String res = html ? document->render_to_html() : document->render_for_terminal(view_width);
printf("%s", res.characters()); out("{}", res);
} }

View file

@ -1,6 +1,6 @@
/* /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * 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 * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -61,7 +61,7 @@ int main(int argc, char** argv)
} }
} else { } else {
if (!S_ISDIR(st.st_mode)) { 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; has_errors = true;
break; break;
} }

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/stat.h> #include <sys/stat.h>
@ -16,7 +17,7 @@ constexpr unsigned encoded_device(unsigned major, unsigned minor)
static int usage() static int usage()
{ {
printf("usage: mknod <name> <c|b|p> [<major> <minor>]\n"); warnln("usage: mknod <name> <c|b|p> [<major> <minor>]");
return 0; return 0;
} }

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <fcntl.h> #include <fcntl.h>
#include <stdio.h> #include <stdio.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
@ -13,11 +14,11 @@ static int key_fd;
static void wait_for_key() static void wait_for_key()
{ {
printf("\033[7m--[ more ]--\033[0m"); out("\033[7m--[ more ]--\033[0m");
fflush(stdout); fflush(stdout);
char dummy; char dummy;
[[maybe_unused]] auto rc = read(key_fd, &dummy, 1); [[maybe_unused]] auto rc = read(key_fd, &dummy, 1);
printf("\n"); outln();
} }
int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) 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); auto* str = fgets(buffer, sizeof(buffer), stdin);
if (!str) if (!str)
break; break;
printf("%s", str); out("{}", str);
++lines_printed; ++lines_printed;
if ((lines_printed % (ws.ws_row - 1)) == 0) { if ((lines_printed % (ws.ws_row - 1)) == 0) {
wait_for_key(); wait_for_key();

View file

@ -36,7 +36,7 @@ static int parse_options(const StringView& options)
else if (part == "remount") else if (part == "remount")
flags |= MS_REMOUNT; flags |= MS_REMOUNT;
else else
fprintf(stderr, "Ignoring invalid option: %s\n", part.to_string().characters()); warnln("Ignoring invalid option: {}", part);
} }
return flags; return flags;
} }
@ -69,7 +69,7 @@ static bool mount_all()
auto fstab = Core::File::construct("/etc/fstab"); auto fstab = Core::File::construct("/etc/fstab");
if (!fstab->open(Core::OpenMode::ReadOnly)) { 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; return false;
} }
@ -83,7 +83,7 @@ static bool mount_all()
Vector<String> parts = line.split('\t'); Vector<String> parts = line.split('\t');
if (parts.size() < 3) { if (parts.size() < 3) {
fprintf(stderr, "Invalid fstab entry: %s\n", line.characters()); warnln("Invalid fstab entry: {}", line);
all_ok = false; all_ok = false;
continue; continue;
} }
@ -105,7 +105,7 @@ static bool mount_all()
int rc = mount(fd, mountpoint, fstype, flags); int rc = mount(fd, mountpoint, fstype, flags);
if (rc != 0) { 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; all_ok = false;
continue; continue;
} }
@ -119,7 +119,7 @@ static bool print_mounts()
// Output info about currently mounted filesystems. // Output info about currently mounted filesystems.
auto df = Core::File::construct("/proc/df"); auto df = Core::File::construct("/proc/df");
if (!df->open(Core::OpenMode::ReadOnly)) { 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; return false;
} }
@ -135,23 +135,23 @@ static bool print_mounts()
auto readonly = fs_object.get("readonly").to_bool(); auto readonly = fs_object.get("readonly").to_bool();
auto mount_flags = fs_object.get("mount_flags").to_int(); 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) if (readonly || mount_flags & MS_RDONLY)
printf("ro"); out("ro");
else else
printf("rw"); out("rw");
if (mount_flags & MS_NODEV) if (mount_flags & MS_NODEV)
printf(",nodev"); out(",nodev");
if (mount_flags & MS_NOEXEC) if (mount_flags & MS_NOEXEC)
printf(",noexec"); out(",noexec");
if (mount_flags & MS_NOSUID) if (mount_flags & MS_NOSUID)
printf(",nosuid"); out(",nosuid");
if (mount_flags & MS_BIND) if (mount_flags & MS_BIND)
printf(",bind"); out(",bind");
printf(")\n"); outln(")");
}); });
return true; return true;

View file

@ -79,14 +79,14 @@ int main(int argc, char** argv)
} }
rc = unlink(old_path); rc = unlink(old_path);
if (rc < 0) if (rc < 0)
fprintf(stderr, "mv: unlink '%s': %s\n", old_path, strerror(errno)); warnln("mv: unlink '{}': {}", old_path, strerror(errno));
} else { } else {
warnln("mv: cannot move '{}' : {}", old_path, strerror(errno)); warnln("mv: cannot move '{}' : {}", old_path, strerror(errno));
} }
} }
if (verbose && rc == 0) if (verbose && rc == 0)
printf("renamed '%s' -> '%s'\n", old_path, new_path); outln("renamed '{}' -> '{}'", old_path, new_path);
} }
return 0; return 0;

View file

@ -7,7 +7,7 @@
#include <AK/String.h> #include <AK/String.h>
#include <AK/Vector.h> #include <AK/Vector.h>
#include <LibCore/ArgsParser.h> #include <LibCore/ArgsParser.h>
#include <errno.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
@ -61,7 +61,7 @@ int main(int argc, char** argv)
for (auto& file : files) { for (auto& file : files) {
FILE* file_pointer = fopen(file, "r"); FILE* file_pointer = fopen(file, "r");
if (!file_pointer) { if (!file_pointer) {
fprintf(stderr, "unable to open %s\n", file); warnln("Failed to open {}: {}", file, strerror(errno));
continue; continue;
} }
file_pointers.append(file_pointer); file_pointers.append(file_pointer);
@ -78,20 +78,20 @@ int main(int argc, char** argv)
if (previous_character == 0 || previous_character == '\n') { if (previous_character == 0 || previous_character == '\n') {
if (next_character == '\n' && number_style != NumberAllLines) { if (next_character == '\n' && number_style != NumberAllLines) {
// Skip printing line count on empty lines. // Skip printing line count on empty lines.
printf("\n"); outln();
continue; continue;
} }
if (number_style != NumberNoLines) if (number_style != NumberNoLines)
printf("%*d%s", number_width, (line_number += increment), separator); out("{1:{0}}{2}", number_width, (line_number += increment), separator);
else else
printf("%*s", number_width, ""); out("{1:{0}}", number_width, "");
} }
putchar(next_character); putchar(next_character);
previous_character = next_character; previous_character = next_character;
} }
fclose(file_pointer); fclose(file_pointer);
if (previous_character != '\n') 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; return 0;
} }

View file

@ -15,20 +15,20 @@ static int handle_show_all()
{ {
Core::DirIterator di("/res/wallpapers", Core::DirIterator::SkipDots); Core::DirIterator di("/res/wallpapers", Core::DirIterator::SkipDots);
if (di.has_error()) { if (di.has_error()) {
fprintf(stderr, "DirIterator: %s\n", di.error_string()); warnln("DirIterator: {}", di.error_string());
return 1; return 1;
} }
while (di.has_next()) { while (di.has_next()) {
String name = di.next_path(); String name = di.next_path();
printf("%s\n", name.characters()); outln("{}", name);
} }
return 0; return 0;
} }
static int handle_show_current() static int handle_show_current()
{ {
printf("%s\n", GUI::Desktop::the().wallpaper().characters()); outln("{}", GUI::Desktop::the().wallpaper());
return 0; return 0;
} }
@ -39,7 +39,7 @@ static int handle_set_pape(const String& name)
builder.append(name); builder.append(name);
String path = builder.to_string(); String path = builder.to_string();
if (!GUI::Desktop::the().set_wallpaper(path)) { 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 1;
} }
return 0; return 0;

View file

@ -23,7 +23,7 @@ static int pid_of(const String& process_name, bool single_shot, bool omit_pid, p
for (auto& it : processes.value()) { for (auto& it : processes.value()) {
if (it.name == process_name) { if (it.name == process_name) {
if (!omit_pid || it.pid != pid) { 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; displayed_at_least_one = true;
if (single_shot) 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) if (displayed_at_least_one)
printf("\n"); outln();
return 0; return 0;
} }
@ -58,7 +58,7 @@ int main(int argc, char** argv)
} else { } else {
auto number = StringView(omit_pid_value).to_uint(); auto number = StringView(omit_pid_value).to_uint();
if (!number.has_value()) { if (!number.has_value()) {
fprintf(stderr, "Invalid value for -o\n"); warnln("Invalid value for -o");
args_parser.print_usage(stderr, argv[0]); args_parser.print_usage(stderr, argv[0]);
return 1; return 1;
} }

View file

@ -45,7 +45,7 @@ int main(int argc, char** argv)
} }
if (setgid(getgid()) || setuid(getuid())) { if (setgid(getgid()) || setuid(getuid())) {
fprintf(stderr, "Failed to drop privileges.\n"); warnln("Failed to drop privileges.");
return 1; return 1;
} }
@ -66,7 +66,7 @@ int main(int argc, char** argv)
auto* hostent = gethostbyname(host); auto* hostent = gethostbyname(host);
if (!hostent) { if (!hostent) {
printf("Lookup failed for '%s'\n", host); warnln("Lookup failed for '{}'", host);
return 1; return 1;
} }
@ -101,17 +101,18 @@ int main(int argc, char** argv)
sighandler_t ret = signal(SIGINT, [](int) { sighandler_t ret = signal(SIGINT, [](int) {
int packet_loss = 100; int packet_loss = 100;
printf("\n--- %s ping statistics ---\n", host); outln();
outln("--- {} ping statistics ---", host);
if (total_pings) if (total_pings)
packet_loss -= 100.0f * successful_pings / 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); total_pings, successful_pings, packet_loss);
int average_ms = 0; int average_ms = 0;
if (successful_pings) if (successful_pings)
average_ms = total_ms / 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); 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); rc = recvfrom(fd, &pong_packet, sizeof(PongPacket), 0, (struct sockaddr*)&peer_address, &peer_address_size);
if (rc < 0) { if (rc < 0) {
if (errno == EAGAIN) { 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; break;
} }
perror("recvfrom"); perror("recvfrom");
@ -190,7 +191,7 @@ int main(int argc, char** argv)
max_ms = ms; max_ms = ms;
char addr_buf[INET_ADDRSTRLEN]; 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)), 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.id),
ntohs(pong_packet.header.un.echo.sequence), ntohs(pong_packet.header.un.echo.sequence),

View file

@ -37,16 +37,16 @@ int main(int argc, char** argv)
auto file = Core::File::construct(String::formatted("/proc/{}/vm", pid)); auto file = Core::File::construct(String::formatted("/proc/{}/vm", pid));
if (!file->open(Core::OpenMode::ReadOnly)) { 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; return 1;
} }
printf("%s:\n", pid); outln("{}:", pid);
if (extended) { 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 { } else {
printf("Address Size Access Name\n"); outln("Address Size Access Name");
} }
auto file_contents = file->read_all(); auto file_contents = file->read_all();
@ -70,8 +70,8 @@ int main(int argc, char** argv)
(map.get("shared").to_bool() ? "s" : "-"), (map.get("shared").to_bool() ? "s" : "-"),
(map.get("syscall").to_bool() ? "c" : "-")); (map.get("syscall").to_bool() ? "c" : "-"));
printf("%08x ", address); out("{:08x} ", address);
printf("%10s ", size.characters()); out("{:>10} ", size);
if (extended) { if (extended) {
auto resident = map.get("amount_resident").to_string(); auto resident = map.get("amount_resident").to_string();
auto dirty = map.get("amount_dirty").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); vmobject = vmobject.substring(0, vmobject.length() - 8);
auto purgeable = map.get("purgeable").to_string(); auto purgeable = map.get("purgeable").to_string();
auto cow_pages = map.get("cow_pages").to_string(); auto cow_pages = map.get("cow_pages").to_string();
printf("%10s ", resident.characters()); out("{:>10} ", resident);
printf("%10s ", dirty.characters()); out("{:>10} ", dirty);
printf("%-6s ", access.characters()); out("{:6} ", access);
printf("%-14s ", vmobject.characters()); out("{:14} ", vmobject);
printf("%-10s ", purgeable.characters()); out("{:10} ", purgeable);
printf("%10s ", cow_pages.characters()); out("{:>10} ", cow_pages);
} else { } else {
printf("%-6s ", access.characters()); out("{:6} ", access);
} }
auto name = map.get("name").to_string(); auto name = map.get("name").to_string();
printf("%-20s", name.characters()); out("{:20}", name);
printf("\n"); outln();
} }
return 0; return 0;

View file

@ -179,7 +179,7 @@ int main(int argc, char** argv)
URL url(url_str); URL url(url_str);
if (!url.is_valid()) { 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; 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 {}); auto request = protocol_client->start_request(method, url.to_string(), request_headers, data ? StringView { data }.bytes() : ReadonlyBytes {});
if (!request) { if (!request) {
fprintf(stderr, "Failed to start request for '%s'\n", url_str); warnln("Failed to start request for '{}'", url_str);
return 1; return 1;
} }
@ -201,12 +201,12 @@ int main(int argc, char** argv)
bool received_actual_headers = false; bool received_actual_headers = false;
request->on_progress = [&](Optional<u32> maybe_total_size, u32 downloaded_size) { 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()) { if (maybe_total_size.has_value()) {
fprintf(stderr, "\033]9;%d;%d;\033\\", downloaded_size, maybe_total_size.value()); warn("\033]9;{};{};\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("Download progress: {} / {}", human_readable_size(downloaded_size), human_readable_size(maybe_total_size.value()));
} else { } else {
fprintf(stderr, "Download progress: %s / ???", human_readable_size(downloaded_size).characters()); warn("Download progress: {} / ???", human_readable_size(downloaded_size));
} }
gettimeofday(&current_time, nullptr); gettimeofday(&current_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 time_diff_ms = time_diff.tv_sec * 1000 + time_diff.tv_usec / 1000;
auto size_diff = downloaded_size - previous_downloaded_size; 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) { if (time_diff_ms >= download_speed_rolling_average_time_in_ms) {
previous_downloaded_size = previous_midpoint_downloaded_size; previous_downloaded_size = previous_midpoint_downloaded_size;
@ -264,10 +264,10 @@ int main(int argc, char** argv)
}; };
} }
request->on_finish = [&](bool success, auto) { request->on_finish = [&](bool success, auto) {
fprintf(stderr, "\033]9;-1;\033\\"); warn("\033]9;-1;\033\\");
fprintf(stderr, "\n"); warnln();
if (!success) if (!success)
fprintf(stderr, "Request failed :(\n"); warnln("Request failed :(");
loop.quit(0); loop.quit(0);
}; };

View file

@ -74,7 +74,7 @@ int main(int argc, char** argv)
if (pid_argument || all_processes) { if (pid_argument || all_processes) {
if (!(enable ^ disable ^ wait ^ free)) { 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; return 1;
} }

View file

@ -85,18 +85,18 @@ int main(int argc, char** argv)
auto print_column = [](auto& column, auto& string) { auto print_column = [](auto& column, auto& string) {
if (!column.width) { if (!column.width) {
printf("%s", string.characters()); out("{}", string);
return; return;
} }
if (column.alignment == Alignment::Right) if (column.alignment == Alignment::Right)
printf("%*s ", column.width, string.characters()); out("{1:>{0}} ", column.width, string);
else else
printf("%-*s ", column.width, string.characters()); out("{1:{0}} ", column.width, string);
}; };
for (auto& column : columns) for (auto& column : columns)
print_column(column, column.title); print_column(column, column.title);
printf("\n"); outln();
auto processes = Core::ProcessStatisticsReader::get_all(); auto processes = Core::ProcessStatisticsReader::get_all();
if (!processes.has_value()) if (!processes.has_value())
@ -132,7 +132,7 @@ int main(int argc, char** argv)
for (auto& column : columns) for (auto& column : columns)
print_column(column, column.buffer); print_column(column, column.buffer);
printf("\n"); outln();
} }
return 0; return 0;

View file

@ -33,6 +33,6 @@ int main(int argc, char** argv)
perror("purge"); perror("purge");
return 1; return 1;
} }
printf("Purged page count: %d\n", purged_page_count); outln("Purged page count: {}", purged_page_count);
return 0; return 0;
} }

View file

@ -413,14 +413,14 @@ int main(int argc, char** argv)
ELF::Image elf_image(elf_image_data); ELF::Image elf_image(elf_image_data);
if (!elf_image.is_valid()) { 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; return -1;
} }
String interpreter_path; 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)) { 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; return -1;
} }
@ -431,7 +431,7 @@ int main(int argc, char** argv)
if (elf_image.is_dynamic()) { if (elf_image.is_dynamic()) {
if (interpreter_path.is_null()) { if (interpreter_path.is_null()) {
interpreter_path = "/usr/lib/Loader.so"; 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); 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); ELF::Image interpreter_image(interpreter_image_data);
if (!interpreter_image.is_valid()) { if (!interpreter_image.is_valid()) {
fprintf(stderr, "ELF interpreter image is invalid\n"); warnln("ELF interpreter image is invalid");
return -1; return -1;
} }
@ -475,91 +475,92 @@ int main(int argc, char** argv)
} }
if (display_elf_header) { 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) }) { for (char i : StringView { header.e_ident, sizeof(header.e_ident) }) {
if (isprint(i)) { if (isprint(i)) {
printf("%c ", i); out("{:c} ", i);
} else { } else {
printf("%02x ", i); out("{:02x} ", i);
} }
} }
printf("\n"); outln();
printf(" Type: %d (%s)\n", header.e_type, object_file_type_to_string(header.e_type)); outln(" Type: {} ({})", 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)); outln(" Machine: {} ({})", header.e_machine, object_machine_type_to_string(header.e_machine));
printf(" Version: 0x%x\n", header.e_version); outln(" Version: {:#x}", header.e_version);
printf(" Entry point address: 0x%x\n", header.e_entry); outln(" Entry point address: {:#x}", header.e_entry);
printf(" Start of program headers: %u (bytes into file)\n", header.e_phoff); outln(" Start of program headers: {} (bytes into file)", header.e_phoff);
printf(" Start of section headers: %u (bytes into file)\n", header.e_shoff); outln(" Start of section headers: {} (bytes into file)", header.e_shoff);
printf(" Flags: 0x%x\n", header.e_flags); outln(" Flags: {:#x}", header.e_flags);
printf(" Size of this header: %u (bytes)\n", header.e_ehsize); outln(" Size of this header: {} (bytes)", header.e_ehsize);
printf(" Size of program headers: %u (bytes)\n", header.e_phentsize); outln(" Size of program headers: {} (bytes)", header.e_phentsize);
printf(" Number of program headers: %u\n", header.e_phnum); outln(" Number of program headers: {}", header.e_phnum);
printf(" Size of section headers: %u (bytes)\n", header.e_shentsize); outln(" Size of section headers: {} (bytes)", header.e_shentsize);
printf(" Number of section headers: %u\n", header.e_shnum); outln(" Number of section headers: {}", header.e_shnum);
printf(" Section header string table index: %u\n", header.e_shstrndx); outln(" Section header string table index: {}", header.e_shstrndx);
printf("\n"); outln();
} }
if (display_section_headers) { if (display_section_headers) {
if (!display_all) { if (!display_all) {
printf("There are %u section headers, starting at offset 0x%x:\n", header.e_shnum, header.e_shoff); outln("There are {} section headers, starting at offset {:#x}:", header.e_shnum, header.e_shoff);
printf("\n"); outln();
} }
if (!elf_image.section_count()) { if (!elf_image.section_count()) {
printf("There are no sections in this file.\n"); outln("There are no sections in this file.");
} else { } else {
printf("Section Headers:\n"); outln("Section Headers:");
printf(" Name Type Address Offset Size Flags\n"); outln(" Name Type Address Offset Size Flags");
elf_image.for_each_section([](const ELF::Image::Section& section) { elf_image.for_each_section([](const ELF::Image::Section& section) {
printf(" %-19s ", StringView(section.name()).to_string().characters()); out(" {:19} ", section.name());
printf("%-15s ", object_section_header_type_to_string(section.type())); out("{:15} ", object_section_header_type_to_string(section.type()));
printf("%08x ", section.address()); out("{:08x} ", section.address());
printf("%08x ", section.offset()); out("{:08x} ", section.offset());
printf("%08x ", section.size()); out("{:08x} ", section.size());
printf("%u", section.flags()); out("{}", section.flags());
printf("\n"); outln();
}); });
} }
printf("\n"); outln();
} }
if (display_program_headers) { if (display_program_headers) {
if (!display_all) { if (!display_all) {
printf("Elf file type is %d (%s)\n", header.e_type, object_file_type_to_string(header.e_type)); outln("ELF file type is {} ({})", header.e_type, object_file_type_to_string(header.e_type));
printf("Entry point 0x%x\n", header.e_entry); outln("Entry point {:#x}\n", header.e_entry);
printf("There are %u program headers, starting at offset %u\n", header.e_phnum, header.e_phoff); outln("There are {} program headers, starting at offset {}", header.e_phnum, header.e_phoff);
printf("\n"); outln();
} }
if (!elf_image.program_header_count()) { 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 { } else {
printf("Program Headers:\n"); outln("Program Headers:");
printf(" Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align\n"); outln(" Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align");
elf_image.for_each_program_header([](const ELF::Image::ProgramHeader& program_header) { elf_image.for_each_program_header([](const ELF::Image::ProgramHeader& program_header) {
printf(" %-14s ", object_program_header_type_to_string(program_header.type())); out(" ");
printf("0x%08x ", program_header.offset()); out("{:14} ", object_program_header_type_to_string(program_header.type()));
printf("%p ", program_header.vaddr().as_ptr()); out("{:#08x} ", program_header.offset());
printf("%p ", program_header.vaddr().as_ptr()); // FIXME: assumes PhysAddr = VirtAddr out("{:p} ", program_header.vaddr().as_ptr());
printf("0x%08x ", program_header.size_in_image()); out("{:p} ", program_header.vaddr().as_ptr()); // FIXME: assumes PhysAddr = VirtAddr
printf("0x%08x ", program_header.size_in_memory()); out("{:#08x} ", program_header.size_in_image());
printf("%04x ", program_header.flags()); out("{:#08x} ", program_header.size_in_memory());
printf("0x%08x", program_header.alignment()); out("{:04x} ", program_header.flags());
printf("\n"); out("{:#08x}", program_header.alignment());
outln();
if (program_header.type() == PT_INTERP) 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 // TODO: Display section to segment mapping
printf("\n"); outln();
} }
if (display_dynamic_section) { if (display_dynamic_section) {
@ -572,9 +573,9 @@ int main(int argc, char** argv)
found_dynamic_section = true; found_dynamic_section = true;
if (section.entry_count()) { 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 { } 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; return IterationDecision::Break;
@ -582,77 +583,77 @@ int main(int argc, char** argv)
Vector<String> libraries; Vector<String> libraries;
object->for_each_needed_library([&libraries](StringView entry) { object->for_each_needed_library([&libraries](StringView entry) {
libraries.append(String::formatted("{}", entry).characters()); libraries.append(String::formatted("{}", entry));
}); });
auto library_index = 0; 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) { object->for_each_dynamic_entry([&library_index, &libraries, &object](const ELF::DynamicObject::DynamicEntry& entry) {
printf(" 0x%08x ", entry.tag()); out(" {:#08x} ", entry.tag());
printf("%-17s ", object_tag_to_string(entry.tag())); out("{:17} ", object_tag_to_string(entry.tag()));
if (entry.tag() == DT_NEEDED) { if (entry.tag() == DT_NEEDED) {
printf("Shared library: %s\n", String(libraries[library_index]).characters()); outln("Shared library: {}", libraries[library_index]);
library_index++; library_index++;
} else if (entry.tag() == DT_RPATH) { } 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) { } 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) { } else if (entry.tag() == DT_SONAME) {
printf("Library soname: %s\n", String(object->soname()).characters()); outln("Library soname: {}", object->soname());
} else { } else {
printf("0x%08x\n", entry.val()); outln("{:#08x}", entry.val());
} }
}); });
} }
if (!found_dynamic_section) 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 (display_relocations) {
if (elf_image.is_dynamic()) { if (elf_image.is_dynamic()) {
if (!object->relocation_section().entry_count()) { 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 { } 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()); outln("Relocation section '{}' at offset {:#08x} contains {} entries:", object->relocation_section().name(), object->relocation_section().offset(), object->relocation_section().entry_count());
printf(" Offset Type Sym Value Sym Name\n"); outln(" Offset Type Sym Value Sym Name");
object->relocation_section().for_each_relocation([](const ELF::DynamicObject::Relocation& reloc) { object->relocation_section().for_each_relocation([](const ELF::DynamicObject::Relocation& reloc) {
printf(" 0x%08x ", reloc.offset()); out(" {:#08x} ", reloc.offset());
printf(" %-17s ", object_relocation_type_to_string(reloc.type())); out(" {:17} ", object_relocation_type_to_string(reloc.type()));
printf(" 0x%08x ", reloc.symbol().value()); out(" {:#08x} ", reloc.symbol().value());
printf(" %s", reloc.symbol().name().to_string().characters()); out(" {}", reloc.symbol().name());
printf("\n"); outln();
}); });
} }
printf("\n"); outln();
if (!object->plt_relocation_section().entry_count()) { 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 { } 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()); outln("Relocation section '{}' at offset {:#08x} contains {} entries:", object->plt_relocation_section().name(), object->plt_relocation_section().offset(), object->plt_relocation_section().entry_count());
printf(" Offset Type Sym Value Sym Name\n"); outln(" Offset Type Sym Value Sym Name");
object->plt_relocation_section().for_each_relocation([](const ELF::DynamicObject::Relocation& reloc) { object->plt_relocation_section().for_each_relocation([](const ELF::DynamicObject::Relocation& reloc) {
printf(" 0x%08x ", reloc.offset()); out(" {:#08x} ", reloc.offset());
printf(" %-17s ", object_relocation_type_to_string(reloc.type())); out(" {:17} ", object_relocation_type_to_string(reloc.type()));
printf(" 0x%08x ", reloc.symbol().value()); out(" {:#08x} ", reloc.symbol().value());
printf(" %s", reloc.symbol().name().to_string().characters()); out(" {}", reloc.symbol().name());
printf("\n"); outln();
}); });
} }
} else { } else {
printf("No relocations in this file.\n"); outln("No relocations in this file.");
} }
printf("\n"); outln();
} }
if (display_unwind_info) { if (display_unwind_info) {
// TODO: 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)); outln("Decoding of unwind sections for machine type {} is not supported.", object_machine_type_to_string(header.e_machine));
printf("\n"); outln();
} }
if (display_core_notes) { if (display_core_notes) {
@ -663,16 +664,16 @@ int main(int argc, char** argv)
found_notes = true; 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. // 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) 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) { if (display_dynamic_symbol_table || display_symbol_table) {
@ -686,9 +687,9 @@ int main(int argc, char** argv)
found_dynamic_symbol_table = true; found_dynamic_symbol_table = true;
if (!section.entry_count()) { if (!section.entry_count()) {
printf("Symbol table '%s' contains zero entries.\n", ELF_DYNSYM); outln("Symbol table '{}' contains zero entries.", ELF_DYNSYM);
} else { } 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; return IterationDecision::Break;
@ -696,48 +697,48 @@ int main(int argc, char** argv)
if (object->symbol_count()) { if (object->symbol_count()) {
// FIXME: Add support for init/fini/start/main sections // 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) { object->for_each_symbol([](const ELF::DynamicObject::Symbol& sym) {
printf(" %4u: ", sym.index()); out(" {:>4}: ", sym.index());
printf("%08x ", sym.value()); out("{:08x} ", sym.value());
printf("%08x ", sym.size()); out("{:08x} ", sym.size());
printf("%-8s ", object_symbol_type_to_string(sym.type())); out("{:8} ", object_symbol_type_to_string(sym.type()));
printf("%-8s ", object_symbol_binding_to_string(sym.bind())); out("{:8} ", object_symbol_binding_to_string(sym.bind()));
printf("%s", StringView(sym.name()).to_string().characters()); out("{}", sym.name());
printf("\n"); outln();
}); });
} }
} }
if (!found_dynamic_symbol_table) 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 (display_symbol_table) {
if (elf_image.symbol_count()) { if (elf_image.symbol_count()) {
printf("Symbol table '%s' contains %u entries:\n", ELF_SYMTAB, elf_image.symbol_count()); outln("Symbol table '{}' contains {} entries:", ELF_SYMTAB, elf_image.symbol_count());
printf(" Num: Value Size Type Bind Name\n"); outln(" Num: Value Size Type Bind Name");
elf_image.for_each_symbol([](const ELF::Image::Symbol& sym) { elf_image.for_each_symbol([](const ELF::Image::Symbol& sym) {
printf(" %4u: ", sym.index()); out(" {:>4}: ", sym.index());
printf("%08x ", sym.value()); out("{:08x} ", sym.value());
printf("%08x ", sym.size()); out("{:08x} ", sym.size());
printf("%-8s ", object_symbol_type_to_string(sym.type())); out("{:8} ", object_symbol_type_to_string(sym.type()));
printf("%-8s ", object_symbol_binding_to_string(sym.bind())); out("{:8} ", object_symbol_binding_to_string(sym.bind()));
printf("%s", StringView(sym.name()).to_string().characters()); out("{}", sym.name());
printf("\n"); outln();
}); });
} else { } 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) { if (display_hardening) {
printf("Security Hardening:\n"); outln("Security Hardening:");
printf("RELRO Stack Canary NX PIE RPATH RUNPATH Symbols \n"); outln("RELRO Stack Canary NX PIE RPATH RUNPATH Symbols ");
bool relro = false; bool relro = false;
elf_image.for_each_program_header([&relro](const ELF::Image::ProgramHeader& program_header) { 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; return IterationDecision::Continue;
}); });
if (full_relro) if (full_relro)
printf("\033[0;32m%-13s\033[0m ", "Full RELRO"); out("\033[0;32m{:13}\033[0m ", "Full RELRO");
else else
printf("\033[0;33m%-13s\033[0m ", "Partial RELRO"); out("\033[0;33m{:13}\033[0m ", "Partial RELRO");
} else { } else {
printf("\033[0;31m%-13s\033[0m ", "No RELRO"); out("\033[0;31m{:13}\033[0m ", "No RELRO");
} }
bool canary = false; bool canary = false;
@ -775,9 +776,9 @@ int main(int argc, char** argv)
}); });
if (canary) if (canary)
printf("\033[0;32m%-12s\033[0m ", "Canary found"); out("\033[0;32m{:12}\033[0m ", "Canary found");
else else
printf("\033[0;31m%-12s\033[0m ", "No canary"); out("\033[0;31m{:12}\033[0m ", "No canary");
bool nx = false; bool nx = false;
elf_image.for_each_program_header([&nx](const ELF::Image::ProgramHeader& program_header) { 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) if (nx)
printf("\033[0;32m%-12s\033[0m ", "NX enabled"); out("\033[0;32m{:12}\033[0m ", "NX enabled");
else else
printf("\033[0;31m%-12s\033[0m ", "NX disabled"); out("\033[0;31m{:12}\033[0m ", "NX disabled");
bool pie = false; bool pie = false;
if (header.e_type == ET_REL || header.e_type == ET_DYN) if (header.e_type == ET_REL || header.e_type == ET_DYN)
pie = true; pie = true;
if (pie) if (pie)
printf("\033[0;32m%-12s\033[0m ", "PIE enabled"); out("\033[0;32m{:12}\033[0m ", "PIE enabled");
else else
printf("\033[0;31m%-12s\033[0m ", "No PIE"); out("\033[0;31m{:12}\033[0m ", "No PIE");
StringView rpath; StringView rpath;
if (elf_image.is_dynamic()) if (elf_image.is_dynamic())
rpath = object->rpath(); rpath = object->rpath();
if (rpath.is_empty()) if (rpath.is_empty())
printf("\033[0;32m%-12s\033[0m ", "No RPATH"); out("\033[0;32m{:12}\033[0m ", "No RPATH");
else else
printf("\033[0;31m%-12s\033[0m ", rpath.to_string().characters()); out("\033[0;31m{:12}\033[0m ", rpath);
StringView runpath; StringView runpath;
if (elf_image.is_dynamic()) if (elf_image.is_dynamic())
runpath = object->runpath(); runpath = object->runpath();
if (runpath.is_empty()) if (runpath.is_empty())
printf("\033[0;32m%-12s\033[0m ", "No RUNPATH"); out("\033[0;32m{:12}\033[0m ", "No RUNPATH");
else 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()); out("{} symbols", elf_image.symbol_count());
printf("\n"); outln();
} }
return 0; return 0;

View file

@ -30,9 +30,9 @@ int main(int argc, char** argv)
perror(path); perror(path);
return 1; return 1;
} }
printf("%s", destination.characters()); out("{}", destination);
if (!no_newline) if (!no_newline)
putchar('\n'); outln();
} }
return 0; return 0;

View file

@ -28,7 +28,7 @@ int main(int argc, char** argv)
perror("realpath"); perror("realpath");
return 1; return 1;
} }
printf("%s\n", value); outln("{}", value);
free(value); free(value);
return 0; return 0;
} }

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <AK/StdLibExtras.h> #include <AK/StdLibExtras.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@ -28,7 +29,7 @@ static double get_double(const char* name, const char* d_string, int* number_of_
char* end; char* end;
double d = strtod(d_string, &end); double d = strtod(d_string, &end);
if (d == 0 && end == d_string) { 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); print_usage(stderr);
exit(1); exit(1);
} }
@ -73,18 +74,18 @@ int main(int argc, const char* argv[])
end = get_double(argv[0], argv[3], &number_of_end_decimals); end = get_double(argv[0], argv[3], &number_of_end_decimals);
break; break;
default: default:
fprintf(stderr, "%s: unexpected number of arguments\n", argv[0]); warnln("{}: unexpected number of arguments", argv[0]);
print_usage(stderr); print_usage(stderr);
return 1; return 1;
} }
if (step == 0) { if (step == 0) {
fprintf(stderr, "%s: increment must not be 0\n", argv[0]); warnln("{}: increment must not be 0", argv[0]);
return 1; return 1;
} }
if (__builtin_isnan(start) || __builtin_isnan(step) || __builtin_isnan(end)) { 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; return 1;
} }
@ -101,7 +102,7 @@ int main(int argc, const char* argv[])
else if ((dot - buf) + 1 + number_of_decimals < (int)sizeof(buf)) else if ((dot - buf) + 1 + number_of_decimals < (int)sizeof(buf))
dot[1 + number_of_decimals] = '\0'; dot[1 + number_of_decimals] = '\0';
} }
printf("%s\n", buf); outln("{}", buf);
d += step; d += step;
} }

View file

@ -41,7 +41,7 @@ int main(int argc, char** argv)
? Core::Account::from_name(user) ? Core::Account::from_name(user)
: Core::Account::from_uid(0); : Core::Account::from_uid(0);
if (account_or_error.is_error()) { 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; return 1;
} }

View file

@ -19,12 +19,12 @@ static String read_var(const String& name)
auto path = builder.to_string(); auto path = builder.to_string();
auto f = Core::File::construct(path); auto f = Core::File::construct(path);
if (!f->open(Core::OpenMode::ReadOnly)) { 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); exit(1);
} }
const auto& b = f->read_all(); const auto& b = f->read_all();
if (f->error() < 0) { if (f->error() < 0) {
fprintf(stderr, "read: %s\n", f->error_string()); warnln("Failed to read: {}", f->error_string());
exit(1); exit(1);
} }
return String((const char*)b.data(), b.size(), Chomp); 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 path = builder.to_string();
auto f = Core::File::construct(path); auto f = Core::File::construct(path);
if (!f->open(Core::OpenMode::WriteOnly)) { if (!f->open(Core::OpenMode::WriteOnly)) {
fprintf(stderr, "open: %s\n", f->error_string()); warnln("Failed to open: {}", f->error_string());
exit(1); exit(1);
} }
f->write(value); f->write(value);
if (f->error() < 0) { if (f->error() < 0) {
fprintf(stderr, "write: %s\n", f->error_string()); warnln("Failed to write: {}", f->error_string());
exit(1); exit(1);
} }
} }
@ -52,13 +52,13 @@ static int handle_show_all()
{ {
Core::DirIterator di("/proc/sys", Core::DirIterator::SkipDots); Core::DirIterator di("/proc/sys", Core::DirIterator::SkipDots);
if (di.has_error()) { if (di.has_error()) {
fprintf(stderr, "DirIterator: %s\n", di.error_string()); outln("DirIterator: {}", di.error_string());
return 1; return 1;
} }
while (di.has_next()) { while (di.has_next()) {
String variable_name = di.next_path(); 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; return 0;
} }
@ -71,13 +71,13 @@ static int handle_var(const String& var)
bool is_write = parts.size() > 1; bool is_write = parts.size() > 1;
if (!is_write) { if (!is_write) {
printf("%s = %s\n", variable_name.characters(), read_var(variable_name).characters()); outln("{} = {}", variable_name, read_var(variable_name));
return 0; 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]); write_var(variable_name, parts[1]);
printf(" -> %s\n", read_var(variable_name).characters()); outln(" -> {}", read_var(variable_name));
return 0; return 0;
} }

View file

@ -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. // stopping when we've found the number of lines we want.
off_t pos = 0; off_t pos = 0;
if (!file.seek(0, Core::SeekMode::FromEndPosition, &pos)) { 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; return 1;
} }
@ -91,7 +91,7 @@ int main(int argc, char* argv[])
auto f = Core::File::construct(file); auto f = Core::File::construct(file);
if (!f->open(Core::OpenMode::ReadOnly)) { 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); exit(1);
} }

View file

@ -94,15 +94,15 @@ static void print_buffer(ReadonlyBytes buffer, int split)
for (size_t i = 0; i < buffer.size(); ++i) { for (size_t i = 0; i < buffer.size(); ++i) {
if (split > 0) { if (split > 0) {
if (i % split == 0 && i) { if (i % split == 0 && i) {
printf(" "); out(" ");
for (size_t j = i - split; j < i; ++j) { for (size_t j = i - split; j < i; ++j) {
auto ch = buffer[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(""); puts("");
} }
@ -130,16 +130,16 @@ static int run(Function<void(const char*, size_t)> fn)
} }
} else { } else {
if (filename == nullptr) { if (filename == nullptr) {
puts("must specify a filename"); warnln("must specify a filename");
return 1; return 1;
} }
if (!Core::File::exists(filename)) { if (!Core::File::exists(filename)) {
puts("File does not exist"); warnln("File does not exist");
return 1; return 1;
} }
auto file = Core::File::open(filename, Core::OpenMode::ReadOnly); auto file = Core::File::open(filename, Core::OpenMode::ReadOnly);
if (file.is_error()) { if (file.is_error()) {
printf("That's a weird file man...\n"); warnln("Failed to open {}: {}", filename, file.error());
return 1; return 1;
} }
auto buffer = file.value()->read_all(); 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) { tls->on_tls_ready_to_read = [](auto& tls) {
auto buffer = tls.read(); auto buffer = tls.read();
if (buffer.has_value()) 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&) { tls->on_tls_ready_to_write = [&](auto&) {
if (write.size()) { if (write.size()) {
@ -196,7 +196,7 @@ static void aes_cbc(const char* message, size_t len)
cipher.encrypt(buffer, enc_span, iv); cipher.encrypt(buffer, enc_span, iv);
if (binary) if (binary)
printf("%.*s", (int)enc_span.size(), enc_span.data()); out("{}", StringView { enc_span.data(), enc_span.size() });
else else
print_buffer(enc_span, Crypto::Cipher::AESCipher::block_size()); print_buffer(enc_span, Crypto::Cipher::AESCipher::block_size());
} else { } 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 = cipher.create_aligned_buffer(buffer.size());
auto dec_span = dec.bytes(); auto dec_span = dec.bytes();
cipher.decrypt(buffer, dec_span, iv); 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) static void adler32(const char* message, size_t len)
{ {
auto checksum = Crypto::Checksum::Adler32({ (const u8*)message, 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) static void crc32(const char* message, size_t len)
{ {
auto checksum = Crypto::Checksum::CRC32({ (const u8*)message, 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) static void md5(const char* message, size_t len)
{ {
auto digest = Crypto::Hash::MD5::hash((const u8*)message, len); auto digest = Crypto::Hash::MD5::hash((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)Crypto::Hash::MD5::digest_size(), digest.data); out("{}", StringView { digest.data, Crypto::Hash::MD5::digest_size() });
else else
print_buffer({ digest.data, Crypto::Hash::MD5::digest_size() }, -1); 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); Crypto::Authentication::HMAC<Crypto::Hash::MD5> hmac(secret_key);
auto mac = hmac.process((const u8*)message, len); auto mac = hmac.process((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)hmac.digest_size(), mac.data); out("{}", StringView { mac.data, hmac.digest_size() });
else else
print_buffer({ mac.data, hmac.digest_size() }, -1); 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); auto digest = Crypto::Hash::SHA1::hash((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)Crypto::Hash::SHA1::digest_size(), digest.data); out("{}", StringView { digest.data, Crypto::Hash::SHA1::digest_size() });
else else
print_buffer({ digest.data, Crypto::Hash::SHA1::digest_size() }, -1); 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); auto digest = Crypto::Hash::SHA256::hash((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)Crypto::Hash::SHA256::digest_size(), digest.data); out("{}", StringView { digest.data, Crypto::Hash::SHA256::digest_size() });
else else
print_buffer({ digest.data, Crypto::Hash::SHA256::digest_size() }, -1); 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); Crypto::Authentication::HMAC<Crypto::Hash::SHA256> hmac(secret_key);
auto mac = hmac.process((const u8*)message, len); auto mac = hmac.process((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)hmac.digest_size(), mac.data); out("{}", StringView { mac.data, hmac.digest_size() });
else else
print_buffer({ mac.data, hmac.digest_size() }, -1); 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); auto digest = Crypto::Hash::SHA384::hash((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)Crypto::Hash::SHA384::digest_size(), digest.data); out("{}", StringView { digest.data, Crypto::Hash::SHA384::digest_size() });
else else
print_buffer({ digest.data, Crypto::Hash::SHA384::digest_size() }, -1); 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); auto digest = Crypto::Hash::SHA512::hash((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)Crypto::Hash::SHA512::digest_size(), digest.data); out("{}", StringView { digest.data, Crypto::Hash::SHA512::digest_size() });
else else
print_buffer({ digest.data, Crypto::Hash::SHA512::digest_size() }, -1); 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); Crypto::Authentication::HMAC<Crypto::Hash::SHA512> hmac(secret_key);
auto mac = hmac.process((const u8*)message, len); auto mac = hmac.process((const u8*)message, len);
if (binary) if (binary)
printf("%.*s", (int)hmac.digest_size(), mac.data); out("{}", StringView { mac.data, hmac.digest_size() });
else else
print_buffer({ mac.data, hmac.digest_size() }, -1); print_buffer({ mac.data, hmac.digest_size() }, -1);
} }
@ -319,18 +319,18 @@ auto main(int argc, char** argv) -> int
StringView mode_sv { mode }; StringView mode_sv { mode };
if (mode_sv == "list") { if (mode_sv == "list") {
puts("test-crypto modes"); outln("test-crypto modes");
puts("\tdigest - Access digest (authentication) functions"); outln("\tdigest - Access digest (authentication) functions");
puts("\thash - Access hash functions"); outln("\thash - Access hash functions");
puts("\tchecksum - Access checksum functions"); outln("\tchecksum - Access checksum functions");
puts("\tencrypt -- Access encryption functions"); outln("\tencrypt -- Access encryption functions");
puts("\tdecrypt -- Access decryption functions"); outln("\tdecrypt -- Access decryption functions");
puts("\ttls -- Connect to a peer over TLS 1.2"); outln("\ttls -- Connect to a peer over TLS 1.2");
puts("\tlist -- List all known modes"); outln("\tlist -- List all known modes");
puts("these modes only contain tests"); outln("these modes only contain tests");
puts("\ttest -- Run every test suite"); outln("\ttest -- Run every test suite");
puts("\tbigint -- Run big integer test suite"); outln("\tbigint -- Run big integer test suite");
puts("\tpk -- Run Public-key system tests"); outln("\tpk -- Run Public-key system tests");
return 0; return 0;
} }
@ -364,7 +364,7 @@ auto main(int argc, char** argv) -> int
return sha512_tests(); return sha512_tests();
return run(sha512); return run(sha512);
} }
printf("unknown hash function '%s'\n", suite); warnln("unknown hash function '{}'", suite);
return 1; return 1;
} }
if (mode_sv == "checksum") { if (mode_sv == "checksum") {
@ -382,7 +382,7 @@ auto main(int argc, char** argv) -> int
return adler32_tests(); return adler32_tests();
return run(adler32); return run(adler32);
} }
printf("unknown checksum function '%s'\n", suite); warnln("unknown checksum function '{}'", suite);
return 1; return 1;
} }
if (mode_sv == "digest") { if (mode_sv == "digest") {
@ -413,7 +413,7 @@ auto main(int argc, char** argv) -> int
if (run_tests) if (run_tests)
return ghash_tests(); return ghash_tests();
} }
printf("unknown hash function '%s'\n", suite); warnln("unknown hash function '{}'", suite);
return 1; return 1;
} }
if (mode_sv == "pk") { if (mode_sv == "pk") {
@ -507,11 +507,11 @@ auto main(int argc, char** argv) -> int
return aes_cbc_tests(); return aes_cbc_tests();
if (!Crypto::Cipher::AESCipher::KeyType::is_valid_key_size(key_bits)) { 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; return 1;
} }
if (strlen(secret_key) != (size_t)key_bits / 8) { 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 1;
} }
return run(aes_cbc); return run(aes_cbc);
@ -522,39 +522,39 @@ auto main(int argc, char** argv) -> int
return 1; return 1;
} else { } else {
printf("Unknown cipher suite '%s'\n", suite); warnln("Unknown cipher suite '{}'", suite);
return 1; 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; return 1;
} }
#define I_TEST(thing) \ #define I_TEST(thing) \
{ \ { \
printf("Testing " #thing "... "); \ out("Testing " #thing "... "); \
fflush(stdout); \ fflush(stdout); \
gettimeofday(&start_time, nullptr); \ gettimeofday(&start_time, nullptr); \
} }
#define PASS \ #define PASS \
{ \ { \
struct timeval end_time { \ struct timeval end_time { \
0, 0 \ 0, 0 \
}; \ }; \
gettimeofday(&end_time, nullptr); \ gettimeofday(&end_time, nullptr); \
time_t interval_s = end_time.tv_sec - start_time.tv_sec; \ time_t interval_s = end_time.tv_sec - start_time.tv_sec; \
suseconds_t interval_us = end_time.tv_usec; \ suseconds_t interval_us = end_time.tv_usec; \
if (interval_us < start_time.tv_usec) { \ if (interval_us < start_time.tv_usec) { \
interval_s -= 1; \ interval_s -= 1; \
interval_us += 1000000; \ interval_us += 1000000; \
} \ } \
interval_us -= start_time.tv_usec; \ interval_us -= start_time.tv_usec; \
printf("PASS %llds %lldus\n", (long long)interval_s, (long long)interval_us); \ outln("PASS {}s {}us", (long long)interval_s, (long long)interval_us); \
} }
#define FAIL(reason) \ #define FAIL(reason) \
do { \ do { \
printf("FAIL: " #reason "\n"); \ outln("FAIL: " #reason); \
g_some_test_failed = true; \ g_some_test_failed = true; \
} while (0) } while (0)
static ByteBuffer operator""_b(const char* string, size_t length) 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); cipher.decrypt(in, out_span, iv);
if (out_span.size() != strlen(true_value)) { if (out_span.size() != strlen(true_value)) {
FAIL(size mismatch); 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) { } else if (memcmp(out_span.data(), true_value, strlen(true_value)) != 0) {
FAIL(invalid data); FAIL(invalid data);
print_buffer(out_span, Crypto::Cipher::AESCipher::block_size()); 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); cipher.encrypt(in, out_span, ivec);
if (out_expected.size() != out_actual.size()) { if (out_expected.size() != out_actual.size()) {
FAIL(size mismatch); 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()); print_buffer(out_span, Crypto::Cipher::AESCipher::block_size());
} else if (memcmp(out_expected.data(), out_span.data(), out_expected.size()) != 0) { } else if (memcmp(out_expected.data(), out_span.data(), out_expected.size()) != 0) {
FAIL(invalid data); FAIL(invalid data);
@ -1002,7 +1002,7 @@ static void aes_ctr_test_decrypt()
cipher.decrypt(in, out_span, ivec); cipher.decrypt(in, out_span, ivec);
if (out_expected.size() != out_span.size()) { if (out_expected.size() != out_span.size()) {
FAIL(size mismatch); 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()); print_buffer(out_span, Crypto::Cipher::AESCipher::block_size());
} else if (memcmp(out_expected.data(), out_span.data(), out_expected.size()) != 0) { } else if (memcmp(out_expected.data(), out_span.data(), out_expected.size()) != 0) {
FAIL(invalid data); FAIL(invalid data);
@ -1547,7 +1547,7 @@ static void sha1_test_name()
Crypto::Hash::SHA1 sha; Crypto::Hash::SHA1 sha;
if (sha.class_name() != "SHA1") { if (sha.class_name() != "SHA1") {
FAIL(Invalid class name); FAIL(Invalid class name);
printf("%s\n", sha.class_name().characters()); outln("{}", sha.class_name());
} else } else
PASS; PASS;
} }
@ -1619,7 +1619,7 @@ static void sha256_test_name()
Crypto::Hash::SHA256 sha; Crypto::Hash::SHA256 sha;
if (sha.class_name() != "SHA256") { if (sha.class_name() != "SHA256") {
FAIL(Invalid class name); FAIL(Invalid class name);
printf("%s\n", sha.class_name().characters()); outln("{}", sha.class_name());
} else } else
PASS; PASS;
} }
@ -1730,7 +1730,7 @@ static void sha384_test_name()
Crypto::Hash::SHA384 sha; Crypto::Hash::SHA384 sha;
if (sha.class_name() != "SHA384") { if (sha.class_name() != "SHA384") {
FAIL(Invalid class name); FAIL(Invalid class name);
printf("%s\n", sha.class_name().characters()); outln("{}", sha.class_name());
} else } else
PASS; PASS;
} }
@ -1776,7 +1776,7 @@ static void sha512_test_name()
Crypto::Hash::SHA512 sha; Crypto::Hash::SHA512 sha;
if (sha.class_name() != "SHA512") { if (sha.class_name() != "SHA512") {
FAIL(Invalid class name); FAIL(Invalid class name);
printf("%s\n", sha.class_name().characters()); outln("{}", sha.class_name());
} else } else
PASS; PASS;
} }
@ -2561,8 +2561,11 @@ static void bigint_theory_modular_power()
PASS; PASS;
} else { } else {
FAIL(Wrong result); FAIL(Wrong result);
printf("b: %s\ne: %s\nm: %s\nexpect: %s\nactual: %s\n", outln("b: {}", test_case.base.to_base10());
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("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; PASS;
} else { } else {
FAIL(Wrong primality guess); FAIL(Wrong primality guess);
printf("The number %s is %sa prime, but the test said it is %sa prime!\n", outln("The number {} is {}a prime, but the test said it is {}a prime!",
test_case.candidate.to_base10().characters(), test_case.expected_result ? "" : "not ", actual_result ? "" : "not "); 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); auto actual_result = Crypto::NumberTheory::random_number(test_case.min, test_case.max);
if (actual_result < test_case.min) { if (actual_result < test_case.min) {
FAIL(Too small); 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)) { } else if (!(actual_result < test_case.max)) {
FAIL(Too large); 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 { } else {
PASS; PASS;
} }
@ -2639,10 +2642,10 @@ static void bigint_theory_random_number()
"100000000000000000000000000000"_bigint); // 10**29 "100000000000000000000000000000"_bigint); // 10**29
if (actual_result < "100000000000000000000"_bigint) { // 10**20 if (actual_result < "100000000000000000000"_bigint) { // 10**20
FAIL(Too small); 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 } else if ("99999999900000000000000000000"_bigint < actual_result) { // 10**29 - 10**20
FAIL(Too large); 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 { } else {
PASS; PASS;
} }

View file

@ -5,6 +5,7 @@
*/ */
#include <AK/Assertions.h> #include <AK/Assertions.h>
#include <AK/Format.h>
#include <AK/Types.h> #include <AK/Types.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
@ -12,28 +13,28 @@
#include <sys/mman.h> #include <sys/mman.h>
#include <unistd.h> #include <unistd.h>
#define EXPECT_OK(syscall, address, size) \ #define EXPECT_OK(syscall, address, size) \
do { \ do { \
rc = syscall(fd, (void*)(address), (size_t)(size)); \ rc = syscall(fd, (void*)(address), (size_t)(size)); \
if (rc < 0) { \ if (rc < 0) { \
fprintf(stderr, "Expected success: " #syscall "(%p, %zu), got rc=%d, errno=%d\n", (void*)(address), (size_t)(size), rc, errno); \ warnln("Expected success: " #syscall "({:p}, {}), got rc={}, errno={}", (void*)(address), (size_t)(size), rc, errno); \
} \ } \
} while (0) } while (0)
#define EXPECT_EFAULT(syscall, address, size) \ #define EXPECT_EFAULT(syscall, address, size) \
do { \ do { \
rc = syscall(fd, (void*)(address), (size_t)(size)); \ rc = syscall(fd, (void*)(address), (size_t)(size)); \
if (rc >= 0 || errno != EFAULT) { \ 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); \ warnln("Expected EFAULT: " #syscall "({:p}, {}), got rc={}, errno={}", (void*)(address), (size_t)(size), rc, errno); \
} \ } \
} while (0) } while (0)
#define EXPECT_EFAULT_NO_FD(syscall, address, size) \ #define EXPECT_EFAULT_NO_FD(syscall, address, size) \
do { \ do { \
rc = syscall((address), (size_t)(size)); \ rc = syscall((address), (size_t)(size)); \
if (rc >= 0 || errno != EFAULT) { \ 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); \ warnln("Expected EFAULT: " #syscall "({:p}, {}), got rc={}, errno={}", (void*)(address), (size_t)(size), rc, errno); \
} \ } \
} while (0) } while (0)
int main(int, char**) int main(int, char**)

View file

@ -5,6 +5,7 @@
*/ */
#include <AK/Assertions.h> #include <AK/Assertions.h>
#include <AK/Format.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -14,11 +15,11 @@ static void assert_env(const char* name, const char* value)
char* result = getenv(name); char* result = getenv(name);
if (!result) { if (!result) {
perror("getenv"); 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); VERIFY(false);
} }
if (strcmp(result, value) != 0) { if (strcmp(result, value) != 0) {
printf("Expected '%s', got '%s' instead.\n", value, result); outln("Expected '{}', got '{}' instead.", value, result);
VERIFY(false); VERIFY(false);
} }
} }
@ -77,17 +78,17 @@ static void test_settenv_overwrite_empty()
int main(int, char**) int main(int, char**)
{ {
#define RUNTEST(x) \ #define RUNTEST(x) \
{ \ { \
printf("Running " #x " ...\n"); \ outln("Running " #x " ..."); \
x(); \ x(); \
printf("Success!\n"); \ outln("Success!"); \
} }
RUNTEST(test_getenv_preexisting); RUNTEST(test_getenv_preexisting);
RUNTEST(test_puttenv); RUNTEST(test_puttenv);
RUNTEST(test_settenv); RUNTEST(test_settenv);
RUNTEST(test_settenv_overwrite_empty); RUNTEST(test_settenv_overwrite_empty);
printf("PASS\n"); outln("PASS");
return 0; return 0;
} }

View file

@ -15,20 +15,20 @@
#include <sys/uio.h> #include <sys/uio.h>
#include <unistd.h> #include <unistd.h>
#define EXPECT_ERROR_2(err, syscall, arg1, arg2) \ #define EXPECT_ERROR_2(err, syscall, arg1, arg2) \
do { \ do { \
rc = syscall(arg1, arg2); \ rc = syscall(arg1, arg2); \
if (rc >= 0 || errno != err) { \ 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); \ warnln(__FILE__ ":{}: Expected " #err ": " #syscall "({:p}, {:p}), got rc={}, errno={}", __LINE__, (const void*)(arg1), (const void*)arg2, rc, errno); \
} \ } \
} while (0) } while (0)
#define EXPECT_ERROR_3(err, syscall, arg1, arg2, arg3) \ #define EXPECT_ERROR_3(err, syscall, arg1, arg2, arg3) \
do { \ do { \
rc = syscall(arg1, arg2, arg3); \ rc = syscall(arg1, arg2, arg3); \
if (rc >= 0 || errno != err) { \ 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); \ 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) } while (0)
static void test_read_from_directory() static void test_read_from_directory()
@ -92,7 +92,7 @@ static void test_read_past_eof()
if (rc < 0) if (rc < 0)
perror("read"); perror("read");
if (rc > 0) if (rc > 0)
fprintf(stderr, "read %d bytes past EOF\n", rc); warnln("read {} bytes past EOF", rc);
rc = close(fd); rc = close(fd);
VERIFY(rc == 0); VERIFY(rc == 0);
} }
@ -121,11 +121,11 @@ static void test_mmap_directory()
VERIFY(fd >= 0); VERIFY(fd >= 0);
auto* ptr = mmap(nullptr, 4096, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0); auto* ptr = mmap(nullptr, 4096, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0);
if (ptr != MAP_FAILED) { if (ptr != MAP_FAILED) {
fprintf(stderr, "Boo! mmap() of a directory succeeded!\n"); warnln("Boo! mmap() of a directory succeeded!");
return; return;
} }
if (errno != ENODEV) { 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; return;
} }
close(fd); close(fd);
@ -145,7 +145,7 @@ static void test_tmpfs_read_past_end()
char buffer[16]; char buffer[16];
int nread = read(fd, buffer, sizeof(buffer)); int nread = read(fd, buffer, sizeof(buffer));
if (nread != 0) { 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); close(fd);
} }
@ -161,7 +161,7 @@ static void test_procfs_read_past_end()
char buffer[16]; char buffer[16];
int nread = read(fd, buffer, sizeof(buffer)); int nread = read(fd, buffer, sizeof(buffer));
if (nread != 0) { 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); close(fd);
} }
@ -178,7 +178,7 @@ static void test_open_create_device()
} }
if (st.st_mode != 0100600) { 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"); unlink("/tmp/fakedevice");
close(fd); close(fd);
@ -198,7 +198,7 @@ static void test_unlink_symlink()
rc = unlink("/tmp/linky"); rc = unlink("/tmp/linky");
if (rc < 0) { if (rc < 0) {
perror("unlink"); 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]; char buffer[16];
rc = read(fd, buffer, sizeof(buffer)); rc = read(fd, buffer, sizeof(buffer));
if (rc >= 0 || errno != EOVERFLOW) { 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)); rc = write(fd, buffer, sizeof(buffer));
if (rc >= 0 || errno != EOVERFLOW) { 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); close(fd);
} }
@ -235,7 +235,7 @@ static void test_rmdir_while_inside_dir()
int fd = open("x", O_CREAT | O_RDWR, 0600); int fd = open("x", O_CREAT | O_RDWR, 0600);
if (fd >= 0 || errno != ENOENT) { 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"); rc = chdir("/home/anon");
@ -258,14 +258,14 @@ static void test_writev()
VERIFY_NOT_REACHED(); VERIFY_NOT_REACHED();
} }
if (nwritten != 12) { 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(); VERIFY_NOT_REACHED();
} }
char buffer[32]; char buffer[32];
int nread = read(pipefds[0], buffer, sizeof(buffer)); int nread = read(pipefds[0], buffer, sizeof(buffer));
if (nread != 12 || memcmp(buffer, "HelloFriends", 12)) { 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(); VERIFY_NOT_REACHED();
} }

View file

@ -48,11 +48,11 @@ int main(int argc, char** argv)
return 1; return 1;
} }
printf("Hello from the first thread!\n"); outln("Hello from the first thread!");
pthread_t thread_id; pthread_t thread_id;
int rc = pthread_create( int rc = pthread_create(
&thread_id, nullptr, [](void*) -> void* { &thread_id, nullptr, [](void*) -> void* {
printf("Hi there, from the second thread!\n"); outln("Hi there, from the second thread!");
pthread_exit((void*)0xDEADBEEF); pthread_exit((void*)0xDEADBEEF);
return nullptr; return nullptr;
}, },
@ -67,7 +67,7 @@ int main(int argc, char** argv)
perror("pthread_join"); perror("pthread_join");
return 1; return 1;
} }
printf("Okay, joined and got retval=%p\n", retval); outln("Okay, joined and got retval={}", retval);
return 0; return 0;
} }
@ -83,12 +83,12 @@ int mutex_test()
pthread_t thread_id; pthread_t thread_id;
rc = pthread_create( rc = pthread_create(
&thread_id, nullptr, [](void*) -> void* { &thread_id, nullptr, [](void*) -> void* {
printf("I'm the secondary thread :^)\n"); outln("I'm the secondary thread :^)");
for (;;) { for (;;) {
pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex);
printf("Second thread stole mutex\n"); outln("Second thread stole mutex");
sleep(1); sleep(1);
printf("Second thread giving back mutex\n"); outln("Second thread giving back mutex");
pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex);
sleep(1); sleep(1);
} }
@ -102,7 +102,7 @@ int mutex_test()
} }
for (;;) { for (;;) {
pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex);
printf("Obnoxious spam!\n"); outln("Obnoxious spam!");
pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex);
usleep(10000); usleep(10000);
} }
@ -114,57 +114,57 @@ int detached_test()
pthread_attr_t attributes; pthread_attr_t attributes;
int rc = pthread_attr_init(&attributes); int rc = pthread_attr_init(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_init: %s\n", strerror(rc)); outln("pthread_attr_init: {}", strerror(rc));
return 1; return 1;
} }
int detach_state = 99; // clearly invalid int detach_state = 99; // clearly invalid
rc = pthread_attr_getdetachstate(&attributes, &detach_state); rc = pthread_attr_getdetachstate(&attributes, &detach_state);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_getdetachstate: %s\n", strerror(rc)); outln("pthread_attr_getdetachstate: {}", strerror(rc));
return 2; 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; detach_state = PTHREAD_CREATE_DETACHED;
rc = pthread_attr_setdetachstate(&attributes, detach_state); rc = pthread_attr_setdetachstate(&attributes, detach_state);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_setdetachstate: %s\n", strerror(rc)); outln("pthread_attr_setdetachstate: {}", strerror(rc));
return 3; 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; pthread_t thread_id;
rc = pthread_create( rc = pthread_create(
&thread_id, &attributes, [](void*) -> void* { &thread_id, &attributes, [](void*) -> void* {
printf("I'm the secondary thread :^)\n"); outln("I'm the secondary thread :^)");
sleep(1); sleep(1);
pthread_exit((void*)0xDEADBEEF); pthread_exit((void*)0xDEADBEEF);
return nullptr; return nullptr;
}, },
nullptr); nullptr);
if (rc != 0) { if (rc != 0) {
printf("pthread_create: %s\n", strerror(rc)); outln("pthread_create: {}", strerror(rc));
return 4; return 4;
} }
void* ret_val; void* ret_val;
rc = pthread_join(thread_id, &ret_val); rc = pthread_join(thread_id, &ret_val);
if (rc != 0 && rc != EINVAL) { if (rc != 0 && rc != EINVAL) {
printf("pthread_join: %s\n", strerror(rc)); outln("pthread_join: {}", strerror(rc));
return 5; return 5;
} }
if (rc != EINVAL) { if (rc != EINVAL) {
printf("Expected EINVAL! Thread was joinable?\n"); outln("Expected EINVAL! Thread was joinable?");
return 6; return 6;
} }
sleep(2); 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); rc = pthread_attr_destroy(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_destroy: %s\n", strerror(rc)); outln("pthread_attr_destroy: {}", strerror(rc));
return 7; return 7;
} }
@ -176,30 +176,30 @@ int priority_test()
pthread_attr_t attributes; pthread_attr_t attributes;
int rc = pthread_attr_init(&attributes); int rc = pthread_attr_init(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_init: %s\n", strerror(rc)); outln("pthread_attr_init: {}", strerror(rc));
return 1; return 1;
} }
struct sched_param sched_params; struct sched_param sched_params;
rc = pthread_attr_getschedparam(&attributes, &sched_params); rc = pthread_attr_getschedparam(&attributes, &sched_params);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_getschedparam: %s\n", strerror(rc)); outln("pthread_attr_getschedparam: {}", strerror(rc));
return 2; return 2;
} }
printf("Default priority: %d\n", sched_params.sched_priority); outln("Default priority: {}", sched_params.sched_priority);
sched_params.sched_priority = 3; sched_params.sched_priority = 3;
rc = pthread_attr_setschedparam(&attributes, &sched_params); rc = pthread_attr_setschedparam(&attributes, &sched_params);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_setschedparam: %s\n", strerror(rc)); outln("pthread_attr_setschedparam: {}", strerror(rc));
return 3; return 3;
} }
printf("Set thread priority to 3\n"); outln("Set thread priority to 3");
pthread_t thread_id; pthread_t thread_id;
rc = pthread_create( rc = pthread_create(
&thread_id, &attributes, [](void*) -> void* { &thread_id, &attributes, [](void*) -> void* {
printf("I'm the secondary thread :^)\n"); outln("I'm the secondary thread :^)");
sleep(1); sleep(1);
pthread_exit((void*)0xDEADBEEF); pthread_exit((void*)0xDEADBEEF);
return nullptr; return nullptr;
@ -218,7 +218,7 @@ int priority_test()
rc = pthread_attr_destroy(&attributes); rc = pthread_attr_destroy(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_destroy: %s\n", strerror(rc)); outln("pthread_attr_destroy: {}", strerror(rc));
return 6; return 6;
} }
@ -230,30 +230,30 @@ int stack_size_test()
pthread_attr_t attributes; pthread_attr_t attributes;
int rc = pthread_attr_init(&attributes); int rc = pthread_attr_init(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_init: %s\n", strerror(rc)); outln("pthread_attr_init: {}", strerror(rc));
return 1; return 1;
} }
size_t stack_size; size_t stack_size;
rc = pthread_attr_getstacksize(&attributes, &stack_size); rc = pthread_attr_getstacksize(&attributes, &stack_size);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_getstacksize: %s\n", strerror(rc)); outln("pthread_attr_getstacksize: {}", strerror(rc));
return 2; return 2;
} }
printf("Default stack size: %zu\n", stack_size); outln("Default stack size: {}", stack_size);
stack_size = 8 * 1024 * 1024; stack_size = 8 * 1024 * 1024;
rc = pthread_attr_setstacksize(&attributes, stack_size); rc = pthread_attr_setstacksize(&attributes, stack_size);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_setstacksize: %s\n", strerror(rc)); outln("pthread_attr_setstacksize: {}", strerror(rc));
return 3; return 3;
} }
printf("Set thread stack size to 8 MiB\n"); outln("Set thread stack size to 8 MiB");
pthread_t thread_id; pthread_t thread_id;
rc = pthread_create( rc = pthread_create(
&thread_id, &attributes, [](void*) -> void* { &thread_id, &attributes, [](void*) -> void* {
printf("I'm the secondary thread :^)\n"); outln("I'm the secondary thread :^)");
sleep(1); sleep(1);
pthread_exit((void*)0xDEADBEEF); pthread_exit((void*)0xDEADBEEF);
return nullptr; return nullptr;
@ -272,7 +272,7 @@ int stack_size_test()
rc = pthread_attr_destroy(&attributes); rc = pthread_attr_destroy(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_destroy: %s\n", strerror(rc)); outln("pthread_attr_destroy: {}", strerror(rc));
return 6; return 6;
} }
@ -284,11 +284,11 @@ int staying_alive_test()
pthread_t thread_id; pthread_t thread_id;
int rc = pthread_create( int rc = pthread_create(
&thread_id, nullptr, [](void*) -> void* { &thread_id, nullptr, [](void*) -> void* {
printf("I'm the secondary thread :^)\n"); outln("I'm the secondary thread :^)");
sleep(20); sleep(20);
printf("Secondary thread is still alive\n"); outln("Secondary thread is still alive");
sleep(3520); sleep(3520);
printf("Secondary thread exiting\n"); outln("Secondary thread exiting");
pthread_exit((void*)0xDEADBEEF); pthread_exit((void*)0xDEADBEEF);
return nullptr; return nullptr;
}, },
@ -299,10 +299,10 @@ int staying_alive_test()
} }
sleep(1); sleep(1);
printf("I'm the main thread :^)\n"); outln("I'm the main thread :^)");
sleep(3600); sleep(3600);
printf("Main thread exiting\n"); outln("Main thread exiting");
return 0; return 0;
} }
@ -311,7 +311,7 @@ int set_stack_test()
pthread_attr_t attributes; pthread_attr_t attributes;
int rc = pthread_attr_init(&attributes); int rc = pthread_attr_init(&attributes);
if (rc < 0) { if (rc < 0) {
printf("pthread_attr_init: %s\n", strerror(rc)); outln("pthread_attr_init: {}", strerror(rc));
return 1; return 1;
} }
@ -325,29 +325,29 @@ int set_stack_test()
rc = pthread_attr_setstack(&attributes, stack_addr, stack_size); rc = pthread_attr_setstack(&attributes, stack_addr, stack_size);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_setstack: %s\n", strerror(rc)); outln("pthread_attr_setstack: {}", strerror(rc));
return 2; 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; size_t stack_size_verify;
void* stack_addr_verify; void* stack_addr_verify;
rc = pthread_attr_getstack(&attributes, &stack_addr_verify, &stack_size_verify); rc = pthread_attr_getstack(&attributes, &stack_addr_verify, &stack_size_verify);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_getstack: %s\n", strerror(rc)); outln("pthread_attr_getstack: {}", strerror(rc));
return 3; return 3;
} }
if (stack_addr != stack_addr_verify || stack_size != stack_size_verify) { 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; return 4;
} }
pthread_t thread_id; pthread_t thread_id;
rc = pthread_create( rc = pthread_create(
&thread_id, &attributes, [](void*) -> void* { &thread_id, &attributes, [](void*) -> void* {
printf("I'm the secondary thread :^)\n"); outln("I'm the secondary thread :^)");
sleep(1); sleep(1);
pthread_exit((void*)0xDEADBEEF); pthread_exit((void*)0xDEADBEEF);
return nullptr; return nullptr;
@ -366,7 +366,7 @@ int set_stack_test()
rc = pthread_attr_destroy(&attributes); rc = pthread_attr_destroy(&attributes);
if (rc != 0) { if (rc != 0) {
printf("pthread_attr_destroy: %s\n", strerror(rc)); outln("pthread_attr_destroy: {}", strerror(rc));
return 7; return 7;
} }

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
@ -14,6 +15,6 @@ int main(int, char**)
perror("Error"); perror("Error");
return 1; return 1;
} }
printf("%s\n", tty); outln("{}", tty);
return 0; return 0;
} }

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Format.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
@ -35,24 +36,25 @@ int main(int, char**)
unsigned seconds; unsigned seconds;
sscanf(buffer, "%u", &seconds); sscanf(buffer, "%u", &seconds);
printf("Up "); out("Up ");
if (seconds / 86400 > 0) { if (seconds / 86400 > 0) {
printf("%d day%s, ", seconds / 86400, (seconds / 86400) == 1 ? "" : "s"); out("{} day{}, ", seconds / 86400, (seconds / 86400) == 1 ? "" : "s");
seconds %= 86400; seconds %= 86400;
} }
if (seconds / 3600 > 0) { if (seconds / 3600 > 0) {
printf("%d hour%s, ", seconds / 3600, (seconds / 3600) == 1 ? "" : "s"); out("{} hour{}, ", seconds / 3600, (seconds / 3600) == 1 ? "" : "s");
seconds %= 3600; seconds %= 3600;
} }
if (seconds / 60 > 0) { if (seconds / 60 > 0) {
printf("%d minute%s, ", seconds / 60, (seconds / 60) == 1 ? "" : "s"); out("{} minute{}, ", seconds / 60, (seconds / 60) == 1 ? "" : "s");
seconds %= 60; seconds %= 60;
} }
printf("%d second%s\n", seconds, seconds == 1 ? "" : "s"); out("{} second{}", seconds, seconds == 1 ? "" : "s");
outln();
fclose(fp); fclose(fp);
return 0; return 0;

View file

@ -54,25 +54,25 @@ int main(int argc, char** argv)
// Let's run a quick sanity check on username // Let's run a quick sanity check on username
if (strpbrk(username, "\\/!@#$%^&*()~+=`:\n")) { if (strpbrk(username, "\\/!@#$%^&*()~+=`:\n")) {
fprintf(stderr, "invalid character in username, %s\n", username); warnln("invalid character in username, {}", username);
return 1; return 1;
} }
// Disallow names starting with _ and - // Disallow names starting with _ and -
if (username[0] == '_' || username[0] == '-' || !isalpha(username[0])) { if (username[0] == '_' || username[0] == '-' || !isalpha(username[0])) {
fprintf(stderr, "invalid username, %s\n", username); warnln("invalid username, {}", username);
return 1; return 1;
} }
if (uid < 0) { if (uid < 0) {
fprintf(stderr, "invalid uid %d!\n", uid); warnln("invalid uid {}!", uid);
return 3; return 3;
} }
// First, let's sort out the uid for the user // First, let's sort out the uid for the user
if (uid > 0) { if (uid > 0) {
if (getpwuid(static_cast<uid_t>(uid))) { if (getpwuid(static_cast<uid_t>(uid))) {
fprintf(stderr, "uid %u already exists!\n", uid); warnln("uid {} already exists!", uid);
return 4; return 4;
} }
@ -82,7 +82,7 @@ int main(int argc, char** argv)
} }
if (gid < 0) { if (gid < 0) {
fprintf(stderr, "invalid gid %d\n", gid); warnln("invalid gid {}", gid);
return 3; return 3;
} }

View file

@ -64,8 +64,7 @@ int main()
auto now = time(nullptr); auto now = time(nullptr);
printf("\033[1m%-10s %-12s %-16s %-6s %s\033[0m\n", outln("\033[1m{:10} {:12} {:16} {:6} {}\033[0m", "USER", "TTY", "LOGIN@", "IDLE", "WHAT");
"USER", "TTY", "LOGIN@", "IDLE", "WHAT");
json.value().as_object().for_each_member([&](auto& tty, auto& value) { json.value().as_object().for_each_member([&](auto& tty, auto& value) {
const JsonObject& entry = value.as_object(); const JsonObject& entry = value.as_object();
auto uid = entry.get("uid").to_u32(); auto uid = entry.get("uid").to_u32();
@ -99,12 +98,7 @@ int main()
what = process.name; what = process.name;
} }
printf("%-10s %-12s %-16s %-6s %s\n", outln("{:10} {:12} {:16} {:6} {}", username, tty, login_at, idle_string, what);
username.characters(),
tty.characters(),
login_at.characters(),
idle_string.characters(),
what.characters());
}); });
return 0; return 0;
} }

View file

@ -27,15 +27,15 @@ static void print_buffer(ReadonlyBytes buffer, int split)
for (size_t i = 0; i < buffer.size(); ++i) { for (size_t i = 0; i < buffer.size(); ++i) {
if (split > 0) { if (split > 0) {
if (i % split == 0 && i) { if (i % split == 0 && i) {
printf(" "); out(" ");
for (size_t j = i - split; j < i; ++j) { for (size_t j = i - split; j < i; ++j) {
auto ch = buffer[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(""); puts("");
} }

View file

@ -130,17 +130,18 @@ int main(int argc, char** argv)
usecs_to_sleep = usecs_from(now, next_run_time); usecs_to_sleep = usecs_from(now, next_run_time);
} }
// Clear the screen, then reset the cursor position to the top left. // 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. // Print the header.
if (!flag_noheader) { if (!flag_noheader) {
fprintf(stderr, "%s\n\n", header.characters()); warnln("{}", header);
warnln();
} else { } else {
fflush(stderr); fflush(stderr);
} }
if (run_command(command) != 0) { if (run_command(command) != 0) {
exit_code = 1; exit_code = 1;
if (flag_beep_on_fail) { if (flag_beep_on_fail) {
fprintf(stderr, "\a"); warnln("\a");
fflush(stderr); fflush(stderr);
} }
} }

View file

@ -69,7 +69,7 @@ int main(int argc, char** argv)
size_t max_lines = max(max_lines_for_one_command, 0); size_t max_lines = max(max_lines_for_one_command, 0);
if (!split_with_nulls && strlen(specified_delimiter) > 1) { 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; return 1;
} }
@ -205,8 +205,7 @@ bool run_command(Vector<char*>&& child_argv, bool verbose, bool is_stdin, int de
if (verbose) { if (verbose) {
StringBuilder builder; StringBuilder builder;
builder.join(" ", child_argv); builder.join(" ", child_argv);
fprintf(stderr, "xargs: %s\n", builder.to_string().characters()); warnln("xargs: {}", builder.to_string());
fflush(stderr);
} }
auto pid = fork(); auto pid = fork();