1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 15:27:35 +00:00

Everywhere: Explicitly specify the size in StringView constructors

This commit moves the length calculations out to be directly on the
StringView users. This is an important step towards the goal of removing
StringView(char const*), as it moves the responsibility of calculating
the size of the string to the user of the StringView (which will prevent
naive uses causing OOB access).
This commit is contained in:
sin-ack 2022-07-11 19:53:29 +00:00 committed by Andreas Kling
parent e3da0adfe6
commit c70f45ff44
75 changed files with 264 additions and 203 deletions

View file

@ -65,12 +65,13 @@ ErrorOr<void> parse_args(Main::Arguments arguments, Vector<String>& files, DuOpt
"time",
0,
"time-type",
[&du_option](StringView s) {
if (s == "mtime"sv || s == "modification"sv)
[&du_option](auto const* option_ptr) {
StringView option { option_ptr, strlen(option_ptr) };
if (option == "mtime"sv || option == "modification"sv)
du_option.time_type = DuOption::TimeType::Modification;
else if (s == "ctime"sv || s == "status"sv || s == "use"sv)
else if (option == "ctime"sv || option == "status"sv || option == "use"sv)
du_option.time_type = DuOption::TimeType::Status;
else if (s == "atime"sv || s == "access"sv)
else if (option == "atime"sv || option == "access"sv)
du_option.time_type = DuOption::TimeType::Access;
else
return false;

View file

@ -31,7 +31,7 @@ template<typename Fmt, typename... Args>
[[noreturn]] void fail(Fmt&& fmt, Args&&... args)
{
warn("ERROR: \e[31m");
warnln(StringView { fmt }, args...);
warnln(StringView { fmt, strlen(fmt) }, args...);
warn("\e[0m");
exit(2);
}

View file

@ -19,7 +19,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
}
for (;;) {
char buffer[4096];
auto str = StringView(fgets(buffer, sizeof(buffer), stdin));
fgets(buffer, sizeof(buffer), stdin);
auto str = StringView { buffer, strlen(buffer) };
if (str.contains(arguments.strings[1]))
TRY(Core::System::write(1, str.bytes()));
if (feof(stdin))

View file

@ -112,8 +112,8 @@ class TypeCommand final : public Command {
public:
TypeCommand(char const* arg)
{
StringView type = arg;
if (type.length() != 1 || !StringView("bcdlpfs").contains(type[0]))
StringView type { arg, strlen(arg) };
if (type.length() != 1 || !"bcdlpfs"sv.contains(type[0]))
fatal_error("Invalid mode: \033[1m{}", arg);
m_type = type[0];
}
@ -157,7 +157,7 @@ class LinksCommand final : public StatCommand {
public:
LinksCommand(char const* arg)
{
auto number = StringView(arg).to_uint();
auto number = StringView { arg, strlen(arg) }.to_uint();
if (!number.has_value())
fatal_error("Invalid number: \033[1m{}", arg);
m_links = number.value();
@ -180,7 +180,7 @@ public:
m_uid = passwd->pw_uid;
} else {
// Attempt to parse it as decimal UID.
auto number = StringView(arg).to_uint();
auto number = StringView { arg, strlen(arg) }.to_uint();
if (!number.has_value())
fatal_error("Invalid user: \033[1m{}", arg);
m_uid = number.value();
@ -204,7 +204,7 @@ public:
m_gid = gr->gr_gid;
} else {
// Attempt to parse it as decimal GID.
auto number = StringView(arg).to_int();
auto number = StringView { arg, strlen(arg) }.to_int();
if (!number.has_value())
fatal_error("Invalid group: \033[1m{}", arg);
m_gid = number.value();
@ -224,7 +224,7 @@ class SizeCommand final : public StatCommand {
public:
SizeCommand(char const* arg)
{
StringView view = arg;
StringView view { arg, strlen(arg) };
if (view.ends_with('c')) {
m_is_bytes = true;
view = view.substring_view(0, view.length() - 1);
@ -252,7 +252,7 @@ private:
class NameCommand : public Command {
public:
NameCommand(char const* pattern, CaseSensitivity case_sensitivity)
: m_pattern(pattern)
: m_pattern(pattern, strlen(pattern))
, m_case_sensitivity(case_sensitivity)
{
}
@ -306,7 +306,7 @@ private:
// constness.
auto argv = const_cast<Vector<char*>&>(m_argv);
for (auto& arg : argv) {
if (StringView(arg) == "{}")
if (StringView { arg, strlen(arg) } == "{}")
arg = const_cast<char*>(file_data.full_path.string().characters());
}
argv.append(nullptr);
@ -374,11 +374,11 @@ static OwnPtr<Command> parse_simple_command(Vector<char*>& args)
return {};
char* raw_arg = args.take_first();
StringView arg = raw_arg;
StringView arg { raw_arg, strlen(raw_arg) };
if (arg == "(") {
auto command = parse_complex_command(args);
if (command && !args.is_empty() && StringView(args.first()) == ")")
if (command && !args.is_empty() && StringView { args.first(), strlen(args.first()) } == ")")
return command;
fatal_error("Unmatched \033[1m(");
} else if (arg == "-type") {
@ -438,7 +438,7 @@ static OwnPtr<Command> parse_complex_command(Vector<char*>& args)
while (command && !args.is_empty()) {
char* raw_arg = args.take_first();
StringView arg = raw_arg;
StringView arg { raw_arg, strlen(raw_arg) };
enum {
And,
@ -533,7 +533,7 @@ static void walk_tree(FileData& root_data, Command& command)
continue;
FileData file_data {
root_data.full_path.append(dirent->d_name),
root_data.full_path.append({ dirent->d_name, strlen(dirent->d_name) }),
dirfd,
dirent->d_name,
(struct stat) {},
@ -561,7 +561,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
while (!args.is_empty()) {
char* raw_arg = args.take_first();
StringView arg = raw_arg;
StringView arg { raw_arg, strlen(raw_arg) };
if (arg == "-L") {
g_follow_symlinks = true;
} else if (!arg.starts_with('-')) {

View file

@ -58,9 +58,10 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
// Create a temporary group file
char temp_group[] = "/etc/group.XXXXXX";
StringView temp_group_view { temp_group, strlen(temp_group) };
auto unlink_temp_files = [&] {
if (Core::System::unlink(temp_group).is_error())
if (Core::System::unlink(temp_group_view).is_error())
perror("unlink");
};
@ -92,8 +93,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
return 1;
}
TRY(Core::System::chmod(temp_group, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
TRY(Core::System::rename(temp_group, "/etc/group"));
TRY(Core::System::chmod(temp_group_view, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
TRY(Core::System::rename(temp_group_view, "/etc/group"sv));
unlink_temp_files_guard.disarm();

View file

@ -416,7 +416,7 @@ static int do_file_system_object_long(char const* path)
continue;
StringBuilder builder;
builder.append(path);
builder.append({ path, strlen(path) });
builder.append('/');
builder.append(metadata.name);
metadata.path = builder.to_string();
@ -460,7 +460,7 @@ static bool print_names(char const* path, size_t longest_name, Vector<FileMetada
for (size_t i = 0; i < files.size(); ++i) {
auto& name = files[i].name;
StringBuilder builder;
builder.append(path);
builder.append({ path, strlen(path) });
builder.append('/');
builder.append(name);
if (!print_filesystem_object_short(builder.to_string().characters(), name.characters(), &nprinted))
@ -528,7 +528,7 @@ int do_file_system_object_short(char const* path)
continue;
StringBuilder builder;
builder.append(path);
builder.append({ path, strlen(path) });
builder.append('/');
builder.append(metadata.name);
metadata.path = builder.to_string();

View file

@ -73,11 +73,13 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (target_directory.is_empty()) {
if (!file_template.is_empty()) { // If a custom template is specified we assume the target directory is the current directory
target_directory = getcwd(nullptr, 0);
// FIXME: Get rid of this minor memory leak.
auto const* cwd_ptr = getcwd(nullptr, 0);
target_directory = StringView { cwd_ptr, strlen(cwd_ptr) };
} else {
LexicalPath template_path(file_template);
char const* env_directory = getenv("TMPDIR");
target_directory = env_directory && *env_directory ? env_directory : "/tmp";
target_directory = env_directory && *env_directory ? StringView { env_directory, strlen(env_directory) } : "/tmp"sv;
}
}

View file

@ -185,7 +185,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto addr = from_string.value().to_in_addr_t();
auto* hostent = gethostbyaddr(&addr, sizeof(in_addr), AF_INET);
if (hostent != nullptr) {
auto host_name = StringView(hostent->h_name);
auto host_name = StringView { hostent->h_name, strlen(hostent->h_name) };
if (!host_name.is_empty())
peer_address = host_name;
}
@ -195,7 +195,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (!flag_numeric) {
auto service = getservbyport(htons(if_object.get("peer_port").to_u32()), "tcp");
if (service != nullptr) {
auto s_name = StringView(service->s_name);
auto s_name = StringView { service->s_name, strlen(service->s_name) };
if (!s_name.is_empty())
peer_port = s_name;
}
@ -207,7 +207,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto addr = from_string.value().to_in_addr_t();
auto* hostent = gethostbyaddr(&addr, sizeof(in_addr), AF_INET);
if (hostent != nullptr) {
auto host_name = StringView(hostent->h_name);
auto host_name = StringView { hostent->h_name, strlen(hostent->h_name) };
if (!host_name.is_empty())
local_address = host_name;
}
@ -217,7 +217,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (!flag_numeric) {
auto service = getservbyport(htons(if_object.get("local_port").to_u32()), "tcp");
if (service != nullptr) {
auto s_name = StringView(service->s_name);
auto s_name = StringView { service->s_name, strlen(service->s_name) };
if (!s_name.is_empty())
local_port = s_name;
}
@ -269,7 +269,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto addr = from_string.value().to_in_addr_t();
auto* hostent = gethostbyaddr(&addr, sizeof(in_addr), AF_INET);
if (hostent != nullptr) {
auto host_name = StringView(hostent->h_name);
auto host_name = StringView { hostent->h_name, strlen(hostent->h_name) };
if (!host_name.is_empty())
local_address = host_name;
}
@ -279,7 +279,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (!flag_numeric) {
auto service = getservbyport(htons(if_object.get("local_port").to_u32()), "udp");
if (service != nullptr) {
auto s_name = StringView(service->s_name);
auto s_name = StringView { service->s_name, strlen(service->s_name) };
if (!s_name.is_empty())
local_port = s_name;
}
@ -291,7 +291,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto addr = from_string.value().to_in_addr_t();
auto* hostent = gethostbyaddr(&addr, sizeof(in_addr), AF_INET);
if (hostent != nullptr) {
auto host_name = StringView(hostent->h_name);
auto host_name = StringView { hostent->h_name, strlen(hostent->h_name) };
if (!host_name.is_empty())
peer_address = host_name;
}
@ -301,7 +301,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (!flag_numeric) {
auto service = getservbyport(htons(if_object.get("peer_port").to_u32()), "udp");
if (service != nullptr) {
auto s_name = StringView(service->s_name);
auto s_name = StringView { service->s_name, strlen(service->s_name) };
if (!s_name.is_empty())
peer_port = s_name;
}

View file

@ -27,7 +27,7 @@ static void spawn_command(Span<StringView> command, ByteBuffer const& data, char
MUST(Core::System::dup2(pipefd[0], 0));
MUST(Core::System::close(pipefd[0]));
MUST(Core::System::close(pipefd[1]));
MUST(Core::System::setenv("CLIPBOARD_STATE", state, true));
MUST(Core::System::setenv("CLIPBOARD_STATE"sv, { state, strlen(state) }, true));
MUST(Core::System::exec(command[0], command, Core::System::SearchInPath::Yes));
perror("exec");
exit(1);

View file

@ -63,7 +63,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
if (!strcmp(omit_pid_value, "%PPID")) {
pid_to_omit = getppid();
} else {
auto number = StringView(omit_pid_value).to_uint();
auto number = StringView { omit_pid_value, strlen(omit_pid_value) }.to_uint();
if (!number.has_value()) {
warnln("Invalid value for -o");
args_parser.print_usage(stderr, args.argv[0]);

View file

@ -49,7 +49,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
Vector<StringView> exec_environment;
for (size_t i = 0; environ[i]; ++i) {
StringView env_view { environ[i] };
StringView env_view { environ[i], strlen(environ[i]) };
auto maybe_needle = env_view.find('=');
if (!maybe_needle.has_value())

View file

@ -170,7 +170,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
.short_name = 'H',
.value_name = "header-value",
.accept_value = [&](auto* s) {
StringView header { s };
StringView header { s, strlen(s) };
auto split = header.find(':');
if (!split.has_value())
return false;
@ -316,7 +316,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
request->stream_into(output_stream);
};
request = protocol_client->start_request(method, url, request_headers, data ? StringView { data }.bytes() : ReadonlyBytes {}, proxy_data);
request = protocol_client->start_request(method, url, request_headers, data ? StringView { data, strlen(data) }.bytes() : ReadonlyBytes {}, proxy_data);
setup_request();
dbgln("started request with id {}", request->id());

View file

@ -836,7 +836,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto parse_syscalls = [](char const* option, auto& hash_table) {
if (option != nullptr) {
for (auto syscall : StringView(option).split_view(','))
for (auto syscall : StringView { option, strlen(option) }.split_view(','))
hash_table.set(syscall);
}
};

View file

@ -295,7 +295,7 @@ Result<void, int> apply_modes(size_t parameter_count, char** raw_parameters, ter
Vector<StringView> parameters;
parameters.ensure_capacity(parameter_count);
for (size_t i = 0; i < parameter_count; ++i)
parameters.append(StringView(raw_parameters[i]));
parameters.append(StringView { raw_parameters[i], strlen(raw_parameters[i]) });
auto parse_baud = [&](size_t idx) -> Optional<speed_t> {
auto maybe_numeric_value = parameters[idx].to_uint<uint32_t>();

View file

@ -26,7 +26,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
.short_name = 'u',
.value_name = "path",
.accept_value = [&](auto* s) {
StringView path { s };
StringView path { s, strlen(s) };
if (path.is_empty())
return false;
auto maybe_error = Core::System::unveil(path, permissions);
@ -55,7 +55,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
.min_values = 0,
.max_values = INT_MAX,
.accept_value = [&](auto* s) {
auto maybe_error = Core::System::access(s, X_OK);
auto maybe_error = Core::System::access({ s, strlen(s) }, X_OK);
if (maybe_error.is_error())
warnln("'{}' - fail: {}", s, maybe_error.error());
else

View file

@ -324,7 +324,7 @@ static bool should_treat_expression_as_single_string(StringView arg_after)
static OwnPtr<Condition> parse_simple_expression(char* argv[])
{
StringView arg = argv[optind];
StringView arg { argv[optind], strlen(argv[optind]) };
if (arg.is_null()) {
return {};
}
@ -332,20 +332,24 @@ static OwnPtr<Condition> parse_simple_expression(char* argv[])
if (arg == "(") {
optind++;
auto command = parse_complex_expression(argv);
if (command && argv[optind] && StringView(argv[++optind]) == ")")
return command;
if (command && argv[optind]) {
auto const* next_option = argv[++optind];
if (StringView { next_option, strlen(next_option) } == ")")
return command;
}
fatal_error("Unmatched \033[1m(");
}
// Try to read a unary op.
if (arg.starts_with('-') && arg.length() == 2) {
optind++;
if (should_treat_expression_as_single_string(argv[optind])) {
if (should_treat_expression_as_single_string({ argv[optind], strlen(argv[optind]) })) {
--optind;
return make<StringCompare>(move(arg), "", StringCompare::NotEqual);
}
StringView value = argv[optind];
StringView value { argv[optind], strlen(argv[optind]) };
switch (arg[1]) {
case 'b':
return make<FileIsOfKind>(value, FileIsOfKind::BlockDevice);
@ -393,42 +397,49 @@ static OwnPtr<Condition> parse_simple_expression(char* argv[])
}
}
auto get_next_arg = [&argv]() -> StringView {
auto const* next_arg = argv[++optind];
if (next_arg == NULL)
return StringView {};
return StringView { next_arg, strlen(next_arg) };
};
// Try to read a binary op, this is either a <string> op <string>, <integer> op <integer>, or <file> op <file>.
auto lhs = arg;
arg = argv[++optind];
arg = get_next_arg();
if (arg == "=") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<StringCompare>(lhs, rhs, StringCompare::Equal);
} else if (arg == "!=") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<StringCompare>(lhs, rhs, StringCompare::NotEqual);
} else if (arg == "-eq") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<NumericCompare>(lhs, rhs, NumericCompare::Equal);
} else if (arg == "-ge") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<NumericCompare>(lhs, rhs, NumericCompare::GreaterOrEqual);
} else if (arg == "-gt") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<NumericCompare>(lhs, rhs, NumericCompare::Greater);
} else if (arg == "-le") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<NumericCompare>(lhs, rhs, NumericCompare::LessOrEqual);
} else if (arg == "-lt") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<NumericCompare>(lhs, rhs, NumericCompare::Less);
} else if (arg == "-ne") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<NumericCompare>(lhs, rhs, NumericCompare::NotEqual);
} else if (arg == "-ef") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<FileCompare>(lhs, rhs, FileCompare::Same);
} else if (arg == "-nt") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<FileCompare>(lhs, rhs, FileCompare::ModificationTimestampGreater);
} else if (arg == "-ot") {
StringView rhs = argv[++optind];
StringView rhs = get_next_arg();
return make<FileCompare>(lhs, rhs, FileCompare::ModificationTimestampLess);
} else if (arg == "-o" || arg == "-a") {
// '-a' and '-o' are boolean ops, which are part of a complex expression
@ -460,7 +471,8 @@ static OwnPtr<Condition> parse_complex_expression(char* argv[])
if (!command && argv[optind])
fatal_error("expected an expression");
StringView arg = argv[++optind];
auto const* arg_ptr = argv[++optind];
StringView arg { arg_ptr, strlen(arg_ptr) };
enum {
AndOp,

View file

@ -144,7 +144,7 @@ static void parse_args(Main::Arguments arguments, TopOption& top_option)
's',
nullptr,
[&top_option](char const* s) {
StringView sort_by_option { s };
StringView sort_by_option { s, strlen(s) };
if (sort_by_option == "pid"sv)
top_option.sort_by = TopOption::SortBy::Pid;
else if (sort_by_option == "tid"sv)

View file

@ -62,7 +62,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (move_home) {
TRY(Core::System::unveil(target_account.home_directory().characters(), "c"));
TRY(Core::System::unveil(new_home_directory, "wc"));
TRY(Core::System::unveil({ new_home_directory, strlen(new_home_directory) }, "wc"));
}
unveil(nullptr, nullptr);

View file

@ -294,7 +294,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
.short_name = 'l',
.value_name = "file",
.accept_value = [&](char const* str) {
if (auto v = StringView { str }; !v.is_empty()) {
if (auto v = StringView { str, strlen(str) }; !v.is_empty()) {
modules_to_link_in.append(v);
return true;
}
@ -308,7 +308,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
.short_name = 0,
.value_name = "u64",
.accept_value = [&](char const* str) -> bool {
if (auto v = StringView { str }.to_uint<u64>(); v.has_value()) {
if (auto v = StringView { str, strlen(str) }.to_uint<u64>(); v.has_value()) {
values_to_push.append(v.value());
return true;
}

View file

@ -178,7 +178,7 @@ bool read_items(FILE* fp, char entry_separator, Function<Decision(StringView)> c
Decision decision;
do {
decision = callback(item);
decision = callback({ item, strlen(item) });
if (decision == Stop) {
free(item);
return true;