From 7f25959fa2083ecd2a335a9809de509180c797ca Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 3 Aug 2019 08:32:07 +0200 Subject: [PATCH] LibCore: Make get_current_user_home_path() return String & close passwd This API was returning a "const char*" and it was unclear who took care of the underlying memory. Returning a String makes that obvious. Also make sure we close the /etc/passwd file when we're done with it. --- Applications/Launcher/main.cpp | 4 +++- Applications/Terminal/main.cpp | 3 ++- Libraries/LibCore/CUserInfo.cpp | 12 +++++------- Libraries/LibCore/CUserInfo.h | 6 +++++- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/Applications/Launcher/main.cpp b/Applications/Launcher/main.cpp index d6d2954f94..689942c75e 100644 --- a/Applications/Launcher/main.cpp +++ b/Applications/Launcher/main.cpp @@ -24,7 +24,9 @@ void handle_sigchld(int) int main(int argc, char** argv) { - chdir(get_current_user_home_path()); + if (chdir(get_current_user_home_path().characters()) < 0) + perror("chdir"); + GApplication app(argc, argv); signal(SIGCHLD, handle_sigchld); diff --git a/Applications/Terminal/main.cpp b/Applications/Terminal/main.cpp index 926a6c2a82..81b492e144 100644 --- a/Applications/Terminal/main.cpp +++ b/Applications/Terminal/main.cpp @@ -133,7 +133,8 @@ int main(int argc, char** argv) { GApplication app(argc, argv); - chdir(get_current_user_home_path()); + if (chdir(get_current_user_home_path().characters()) < 0) + perror("chdir"); int ptm_fd = open("/dev/ptmx", O_RDWR); if (ptm_fd < 0) { diff --git a/Libraries/LibCore/CUserInfo.cpp b/Libraries/LibCore/CUserInfo.cpp index d5308d454e..4a232c3752 100644 --- a/Libraries/LibCore/CUserInfo.cpp +++ b/Libraries/LibCore/CUserInfo.cpp @@ -3,15 +3,13 @@ #include #include -const char* get_current_user_home_path() +String get_current_user_home_path() { if (auto* home_env = getenv("HOME")) return home_env; - auto d = "/"; - uid_t uid = getuid(); - if (auto* pwd = getpwuid(uid)) - return pwd->pw_dir; - - return d; + auto* pwd = getpwuid(getuid()); + String path = pwd ? pwd->pw_dir : "/"; + endpwent(); + return path; } diff --git a/Libraries/LibCore/CUserInfo.h b/Libraries/LibCore/CUserInfo.h index b47cec4af1..2c172098e6 100644 --- a/Libraries/LibCore/CUserInfo.h +++ b/Libraries/LibCore/CUserInfo.h @@ -1 +1,5 @@ -const char* get_current_user_home_path(); +#pragma once + +#include + +String get_current_user_home_path();