diff --git a/kernel/include/std/libgen.h b/kernel/include/std/libgen.h index d9a7ec48..1a3a0e4d 100644 --- a/kernel/include/std/libgen.h +++ b/kernel/include/std/libgen.h @@ -1,4 +1,7 @@ #pragma once char* basename(char* path); -char* dirname(char* path); \ No newline at end of file +char* dirname(char* path); + +char* better_basename(const char* path); +char* better_dirname(const char* path); \ No newline at end of file diff --git a/kernel/src/fs/VFS.cpp b/kernel/src/fs/VFS.cpp index 0c00e7db..9fe20d37 100644 --- a/kernel/src/fs/VFS.cpp +++ b/kernel/src/fs/VFS.cpp @@ -208,36 +208,30 @@ int VFS::do_mkdir(const char* path, const char* name, int uid, int gid, mode_t m int VFS::mkdir(const char* pathname) { - char* bstr = strdup(pathname); - char* dstr = strdup(pathname); - - char* base = basename(bstr); - char* dir = dirname(dstr); + char* base = better_basename(pathname); + char* dir = better_dirname(pathname); kdbgln("mkdir(): creating %s in directory %s", base, dir); int result = mkdir(dir, base); - kfree(bstr); - kfree(dstr); + kfree(base); + kfree(dir); return result; } int VFS::do_mkdir(const char* pathname, int uid, int gid, mode_t mode) { - char* bstr = strdup(pathname); - char* dstr = strdup(pathname); - - char* base = basename(bstr); - char* dir = dirname(dstr); + char* base = better_basename(pathname); + char* dir = better_dirname(pathname); kdbgln("mkdir(): creating %s in directory %s", base, dir); int result = do_mkdir(dir, base, uid, gid, mode); - kfree(bstr); - kfree(dstr); + kfree(base); + kfree(dir); return result; } diff --git a/kernel/src/std/libgen.cpp b/kernel/src/std/libgen.cpp index 908aee15..b0a46a98 100644 --- a/kernel/src/std/libgen.cpp +++ b/kernel/src/std/libgen.cpp @@ -1,4 +1,5 @@ #include "std/libgen.h" +#include "std/stdlib.h" #include "std/string.h" static char dot[] = "."; @@ -44,4 +45,23 @@ char* dirname(char* path) else *(end + 1) = 0; return path; +} + +char* better_basename(const char* path) +{ + char* mut = strdup(path); // create a mutable copy of path + char* ptr = basename(mut); // get a pointer to the start of the base name + char* result = strdup(ptr); // create a copy of it, so the caller can free the returned pointer directly + kfree(mut); // free the original mutable copy + return result; +} + +char* better_dirname(const char* path) +{ + // same as above + char* mut = strdup(path); + char* ptr = dirname(mut); + char* result = strdup(ptr); + kfree(mut); + return result; } \ No newline at end of file