[libc-commits] [libc] [libc] Implement basename and dirname in libgen.h (PR #204554)

Pavel Labath via libc-commits libc-commits at lists.llvm.org
Thu Jun 18 09:10:14 PDT 2026


================
@@ -0,0 +1,46 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation of basename.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/libgen/basename.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(char *, basename, (char *path)) {
+  if (path == nullptr || path[0] == '\0') {
+    static char dot[] = ".";
----------------
labath wrote:

I get that, and I think a static buffer (one for each value) is fine. The thing I want to avoid is the possibility of a user modifying this buffer. Right now, if a user (maybe accidentally) does something like `basename(nullptr)[0] = 'X';`, then this will modify this static buffer, and corrupt all subsequent calls to the `basename` function.

OTOH, if you implement this as `return const_cast<char *>(".");`, then the above line would crash because the string would be allocated in the read-only section (plus, it would get merged with any other "." literals in the application)

https://github.com/llvm/llvm-project/pull/204554


More information about the libc-commits mailing list