sh: Do not leak memory when using cd
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-04-18 16:49:05 +02:00
parent 4baee3a91f
commit fbb7de7156
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -14,7 +14,7 @@
using os::File; using os::File;
static Result<Vector<char*>> split_command_into_argv(StringView cmd) static Result<Vector<char*>> split_command_into_argv(StringView cmd, char** out)
{ {
char* str = strdup(cmd.chars()); char* str = strdup(cmd.chars());
@ -33,13 +33,15 @@ static Result<Vector<char*>> split_command_into_argv(StringView cmd)
if (segment == NULL) return result; if (segment == NULL) return result;
} }
if (out) *out = str;
return result; return result;
} }
[[noreturn]] static void execute_command(StringView command) [[noreturn]] static void execute_command(StringView command)
{ {
Vector<char*> argv; Vector<char*> argv;
bool ok = split_command_into_argv(command).try_move_value_or_error(argv, errno); bool ok = split_command_into_argv(command, nullptr).try_move_value_or_error(argv, errno);
if (!ok) if (!ok)
{ {
perror("failed to parse command"); perror("failed to parse command");
@ -93,17 +95,21 @@ Result<int> luna_main(int argc, char** argv)
if (!strncmp(cmd.chars(), "cd", 2)) if (!strncmp(cmd.chars(), "cd", 2))
{ {
auto args = TRY(split_command_into_argv(cmd.view())); char* copy = nullptr;
auto args = TRY(split_command_into_argv(cmd.view(), &copy));
check("cd"_sv == args[0]); check("cd"_sv == args[0]);
if (args.size() == 2) if (args.size() == 2)
{ {
auto home = TRY(os::FileSystem::home_directory()); auto home = TRY(os::FileSystem::home_directory());
if (chdir(home.chars()) < 0) perror("cd"); if (chdir(home.chars()) < 0) perror("cd");
free(copy);
continue; continue;
} }
if (chdir(args[1]) < 0) perror("cd"); if (chdir(args[1]) < 0) perror("cd");
free(copy);
continue; continue;
} }