Commit Graph
193 Commits
Author SHA1 Message Date
Jackson Stogel 88a3488c8a [libc][realpath] Implement symbolic path resolution (#204467)
This PR contains an incremental implementation of `realpath` that just
simplifies path traversals (e.g. `"/a/./../b"` -> `"/b"`). The complete
implementation would perform `getcwd`/`statx`/`readlinkat` to actually
resolve symlinks, validate paths, etc. This PR aims to add as much
functionality/error handling as possible without making any syscalls.

This implementation lives in `libc/src/stdlib/linux/`, since follow-on
PRs will rely on linux-specific syscalls. For testing purposes, I've
added the entrypoint for x86-64 linux when
`LLVM_LIBC_ENABLE_EXPERIMENTAL_ENTRYPOINTS` is enabled.

Follow-on PRs to add: path validation (e.g.
paths must exist), support for cwd-relative paths, and symlink
resolution.
2026-07-01 15:58:08 -07:00
Jeff Bailey bef95e5467 [libc][stdlib] Add unsetenv (#202422)
Added the POSIX unsetenv() function and its internal support.

Implemented EnvironmentManager::unset() to remove a variable by name,
free the string if allocated, and compact the array.

Updated EnvironmentManager to synchronize the public global environ
pointer when transitioning to managed storage.

Registered for x86_64, aarch64, and riscv. Integration tests cover basic
operations and edge cases.

Assisted-by: Automated tooling, human reviewed.
2026-06-25 15:07:08 +01:00
Victor Campos 25ae6ce480 [libc] Refactor qsort code (#198781)
This patch makes the following changes:
 - Refactor the internal sorting functions to reduce code duplication.
- Move the testing machinery done for the testing of `qsort_r` to a
shared place.

These changes are done in anticipation to the introduction of Annex K's
`qsort_s`. This function shares most of its semantics with `qsort_r`,
therefore most of the testing logic can be shared between the two.
Besides, `qsort`, `qsort_r` and `qsort_s` are all very similar, hence we
can attempt to reduce duplication a bit more.
2026-06-24 09:33:58 +01:00
Hardik Chona c9b25a6437 [libc] implement mkstemp (#199220)
Fixes #191266
Implements `mkstemp` as specified in POSIX
Currently Linux-only since it relies on the Linux syscall wrappers for
`getrandom` and `open`
2026-06-12 15:14:16 -07:00
Mikhail R. Gadelha 0d1ed9383d [libc] Tag cpp::byte with gnu::may_alias (#200462)
Clang's TBAA grants the [basic.lval]/11.3 char-aliasing privilege only
to the named ::std::byte type (Type::isStdByteType() requires the enum
to be declared in the std namespace). LIBC_NAMESPACE::cpp::byte lives in
libc's cpp namespace, so it gets its own TBAA node disjoint from char
even though it has the same shape as std::byte.

That mismatch lets the optimizer reorder typed loads past raw-byte
writes through cpp::byte *, miscompiling HeapSort on rv64/Release
(UnsortedThreeElementArray{1,2,3}, UnsortedTwoElementArray1 in
SortingTest.h). The same hazard is latent in every cpp::byte *-based
raw-aliasing site: memory_utils Ptr/CPtr, lsearch/lfind, block.h and
freelist_heap.h allocator metadata.

Tag the type with gnu::may_alias so accesses through cpp::byte * share
the universal char-aliasing TBAA node, fixing all of the above in one
place. This patch also reverts PR #194171, as the may_alias attribute
fixes it too.
2026-05-30 12:39:58 -03:00
Alexey Samsonov 934e5610eb [libc] Don't touch str_end in strto* and wcsto* functions when base is incorrect (#200073)
Updates the behavior of `stro*` and `wcsto*` endpoints to not touch
`str_end` pointer when the provided value of `base` is incorrect and
errno is set to `EINVAL`.

`strto*` and `wcsto*` functions accept `base` as an input argument,
which can only be 0 or lie in [2,36] range. In case of invalid argument,
the functions should return 0 and set errno accordingly. Should the
"output argument" of `str_end` be updated in this case to point to the
beginning of the input string?
* C standard is unclear about it -
is says that `str` should be stored in `str_end` **if `str` is empty or
does not have the expected form** -- but there is no "expected form" for
invalid base values.
* POSIX standard explicitly mentions that for incorrect base value errno
should be set to `EINVAL` and points out that the value of `str_end`
is **unspecified** in this case.

Known implementations don't have a universal agreement about it:
* musl sets `str_end` unconditionally
* glibc doesn't do that in `EINVAL` case
* newlib doesn't do that either.

LLVM-libc used to unconditionally set `str_end` even in `EINVAL` case,
which is changed in this PR. This would not only help with portability,
but makes sense by itself - if input arguments are clearly invalid,
let's not touch output arguments either.

Assisted by: Gemini, human-reviewed
2026-05-28 10:05:27 -07:00
Alexey Samsonov b996b4eebb [libc] Implement pthread_sigmask (#198682)
* Extract `rt_sigprocmask` syscall wrapper into the
libc/src/__support/OSUtil/linux/syscall_wrappers/ directory
* Convert all existing users of this syscall, and simplify the logic
where applicable.
* Implement `pthread_sigmask`, which is effectively another POSIX
wrapper around `rt_sigprocmask` syscall similar to `sigprocmask`
2026-05-20 22:25:53 +00:00
Michael Jones 61750f4629 [libc] move mblen to stdlib (#198642)
Move mblen from wchar to stdlib to conform with C standard. Also update
headers to match new style.

Assisted-by: Automated tooling, human reviewed.
2026-05-20 10:53:13 -07:00
Mikhail R. Gadelha a1403139d0 [libc] Make cpp::byte alias-safe (#194171)
Change LIBC_NAMESPACE::cpp::byte from an enum-backed type to unsigned
char so libc’s raw-memory utilities and sorting code can legally access
object representations without violating C++ strict-aliasing rules.
2026-05-15 20:36:02 -04:00
Jeff Bailey b152ea80ba [libc] Disable GCC 12 waccess passes to fix ICE in environ_internal (#197916)
The waccess pass in GCC 12 consistently segmentation faults when
analyzing the memory allocations in environ_internal.cpp. This change
disables the relevant tree-waccess passes for this specific file,
avoiding the ICE without requiring intrusive code refactoring.

Assisted-by: Automated tooling, human reviewed.
2026-05-15 12:24:01 +00:00
Jeff BaileyandMichael Jones 5c7854c8ed [libc][stdlib] Add setenv (#163018)
Add the POSIX setenv() function, with EnvironmentManager::set()
handling environment array management and ownership tracking.

Registered for x86_64, aarch64, and riscv architectures. Integration
tests cover overwrite/no-overwrite semantics, empty/invalid names,
empty values, and repeated replacement.

Assisted-by: Automated tooling, human reviewed.

---------

Co-authored-by: Michael Jones <michaelrj@google.com>
2026-05-11 06:57:00 +01:00
lntue 1db47f8d8c [libc][NFC] Workaround for environ_internal when building with gcc-12. (#196471) 2026-05-08 05:37:39 +00:00
Jeff Bailey 3637547de1 [libc][stdlib] Use structure bindings instead of output params (#196169)
Refactored alloc_and_copy to return cpp::optional<AllocResult> instead
of using reference-to-pointer output parameters. The combination of char
**& parameters with array new/delete is known to trigger a segfault in
GCC 12's waccess GIMPLE pass.

The AllocResult struct holds the two allocated arrays (storage and
ownership). Call sites use structured bindings to unpack the result
after checking for nullopt.

Hopefully fixes the build failure in PR #195260 on the
libc-x86_64-debian-gcc-fullbuild-dbg builder.

Assisted-by: Automated tooling, human reviewed.
2026-05-06 22:40:58 +01:00
Jeff Bailey ce4cef8d3a [libc][stdlib] Add EnvironmentManager (#195260)
Introduced an EnvironmentManager singleton that centralises environment
variable state: the environ array, per-string ownership tracking, and
capacity management. The manager exposes a minimal public API (get,
begin/end iterators) and keeps all internal state private.

Refactored getenv to delegate to EnvironmentManager::get() rather than
directly iterating app.env_ptr.

The ownership tracking and capacity management are preparatory
infrastructure for setenv.

Assisted-by: Automated tooling, human reviewed.
2026-05-06 20:00:06 +01:00
Schrodinger ZHU Yifan b7d6438450 [libc] implement recursive mutex and fix wrong initializer (#193992)
Fix #193892.

This is found during libc++ bringing up process. This patch:
- implement recursive mutex support for real.
- fix the issue that pthread mutex initializer and public mutex
interface misalign with internal representation. this was the root cause
that hangs the libc++ test as padding bytes effectively pollute the
futex state if default initializer was used.
- additionally, we changed the field to bitfield to allow encoding more
data. (e.g. the error checking flag that is not yet added). timed bit is
removed as we always support it anyway. PI bit is added instead.
2026-04-28 16:55:04 -04:00
Schrodinger ZHU Yifan 3b6557f178 [libc][stdlib] move abort to a header library and cleanup its usage (#190845)
This PR moves abort implementation to a header library so that internal
dependency no longer relies on the entrypoint object.
Additionally, it clean up prior dependency to the entrypoint object and
update staled tests.

Assisted-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 18:50:11 -04:00
Schrodinger ZHU Yifan 463f6cb576 [libc] update abort implementation and lift it for internal usage (#189756) 2026-04-03 18:40:52 -04:00
Zorojuro a9c6f38e8d [libc] Fixes all guard comments of libc (#188701)
This PR intends to fix ALL the wrong guard comments for libc


Script used:
[guard_checker](https://github.com/Sukumarsawant/guard_checker/blob/main/check_headers.py)
2026-03-26 15:23:49 -04:00
Alexey Samsonov a8c6cce956 [libc] Add posix_memalign as external entrypoint on Linux x86/ARM. (#185310)
`posix_memalign` is provided by Scudo allocator and is a part of POSIX
standard, so we can safely declare it in the `<stdlib.h>` header on
Linux systems.
2026-03-12 21:57:07 -07:00
Joseph Huber d85576d368 [libc] Replace RPC 'close()' mechanism with RAII handler (#181690)
Summary:
Closing ports was previously done manually, This makes the protocol more
error prone as unclosed ports will leak and eventually the locks will
run out. I believe the original fear was that the RAII portion would
negatively impact code generation but I have not noticed anything
significant.
2026-02-16 15:14:30 -06:00
Austin JiangandLouis Dionne e6cdfb75ac Fix typos and spelling errors across codebase (#156270)
Corrected various spelling mistakes such as 'occurred', 'receiver',
'initialized', 'length', and others in comments, variable names,
function names, and documentation throughout the project. These
changes improve code readability and maintain consistency in naming
and documentation.

Co-authored-by: Louis Dionne <ldionne.2@gmail.com>
2026-01-13 11:52:46 -05:00
Petr Hosek 2d26a7b74e [libc] Provide empty weak definition for __cxa_thread_finalize (#174373)
This avoids the GOT slot being generated which is undesirable when using
static linking. A better solution would be to reorganize the code to
avoid the use of weak symbols altogether.

Fixes #173409
2026-01-06 11:31:48 -08:00
Petr Hosek f54dd47e1d [libc] Delete teardown_main_tls and all its uses (#174374)
teardown_main_tls is called right before the main process exit to unmap
the TLS but that's unnecesary since the process is terminating anyway,
this just introduces extra system call. This can be potentially harmful
in case one of the other threads tries the access the memory that has
been unmapped. Other C library implementations don't unmap TLS either so
this makes LLVM libc's behavior more consistent.

Fixes #173409
2026-01-05 17:38:02 -08:00
Alexey Samsonov 5e63167965 [libc] Refactor static polymorphism in WriteBuffer (NFC). (#169089)
There are three flavors of WriteBuffer currently, all of which could be
passed into `printf_core::Writer` class. It's a tricky class, since it
chooses a flavor-specific logic either based on runtime dispatch (to
save code size and prevent generating three versions of the entirety of
printf_core), or based on template arguments (to avoid dealing with
function pointers in codegen for `FILL_BUFF_AND_DROP_OVERFLOW` path).

Refactor this somewhat convoluted logic to have three concrete
subclasses inheriting from the templated base class, and use static
polymorphism with `reinterpret_cast` to implement dispatching above. Now
we can actually have flavor-specific fields, constructors, and methods
(e.g. `flush_to_stream` is now a method of `FlushingBuffer`), and the
code on the user side is cleaner: the complexity of enabling/disabling
runtime-dispatch and using proper template arguments is now localized in
`writer.h`.

This code will need to be further templatized to support buffers of type
`wchar_t` to implement `swprintf()` and friends. This change would make
it (ever so slightly) easier.
2025-12-11 15:31:21 -08:00
Alexey Samsonov da61dd28c6 [libc] Move mbtowc, mbstowcs and inverse functions to stdlib.h (#168455)
These functions should be declared in `stdlib.h`, not `wchar.h`, as
confusing as it is. Move them to the proper header file and matching
directories in src/ and test/ trees.

This was discovered while testing libc++ build against llvm-libc, which
re-declares functions like mbtowc in std-namespace in `<cstdlib>`
header, and then uses those functions in its locale implementation.
2025-11-17 15:43:42 -08:00
Marcell Leleszi 9e2f73fe90 [libc] Add printf error handling (with fixes #2) (#166517)
https://github.com/llvm/llvm-project/issues/159474

Another try of trying to land
https://github.com/llvm/llvm-project/pull/166382
- Fix some leftover tests checking for specific  errnos
- Guard errno checking tests to not run on the GPU

@michaelrj-google
2025-11-05 16:09:53 -05:00
Alexey Samsonov 120689e466 [libc] Migrate ctype_utils to use char instead of int where applicable. (#166225)
Functions like isalpha / tolower can operate on chars internally. This
allows us to get rid of unnecessary casts and open a way to creating
wchar_t overloads with the same names (e.g. for isalpha), that would
simplify templated code for conversion functions (see
315dfe5865).

Add the int->char converstion to public entrypoints implementation
instead. We also need to introduce bounds check on the input argument
values - these functions' behavior is unspecified if the argument is
neither EOF nor fits in "unsigned char" range, but the tests we've had
verified that they always return false for small negative values. To
preserve this behavior, cover it explicitly.
2025-11-05 11:02:28 -08:00
Kewen Meng c5aaee0bb0 Revert commit d8e5698 and 15b19c7 (#166498) 2025-11-04 19:43:16 -08:00
Marcell Leleszi d8e56988f8 [libc] Add printf error handling (with fixes) (#166382)
https://github.com/llvm/llvm-project/issues/159474

Resubmitting https://github.com/llvm/llvm-project/pull/162876 with fixes
as it broke some buildbots:
 - Fix comparisons of integer expressions of different signedness
- Not check for specific errnos in tests, as they might not be available
on all platforms
2025-11-04 16:20:51 -08:00
Kewen Meng 346da3dfd3 Revert "[libc] Add printf error handling" (#166232) 2025-11-03 12:50:11 -08:00
Marcell Leleszi 0c707c9713 [libc] Add printf error handling (#162876)
[#159474](https://github.com/llvm/llvm-project/issues/159474)

- All printf variants set errno and consistently return -1 on error,
instead of returning various predefined error codes
- Return value overflow handling is added
2025-11-03 11:15:14 -08:00
lntue f019e2368b [libc] Change __builtin_memcpy to inline_memcpy. (#158345) 2025-09-12 17:57:08 -04:00
Joseph Huber 8bdaa12b7c [libc] Fix undefined exit symbol for the NVPTX build
Summary:
NVPTX does not support external weak symbols being defined, disable this
to get the bots working.
2025-09-04 12:11:11 -05:00
Schrodinger ZHU Yifan 71641049a9 [libc] ensure tls dtors are called in main thread (#133641)
This is a part of allocator patch since I want to make sure the TLS for
allocators are correctly handled.

TLS dtors are not invoked on exit previously. This departures from major
libc implementations.

This PR fixes the issue by aligning the behavior with bionic.


https://android.googlesource.com/platform/bionic/+/refs/heads/main/libc/bionic/exit.cpp

I believe the finalization order is also consistent with glibc now:

On main thread exiting:

- pthread_key dtors are not called (unless exiting with `pthread_exit`)
- `__cxa` based tls dtors are called
- `::__cxa_atexit` and `::atexit` dtors are called
- `.fini` dtors are called


![image](https://github.com/user-attachments/assets/737c4845-cab6-47a9-aa00-32997be141bd)
2025-09-03 09:02:03 -04:00
lntue 66603dd1f1 [libc][NFC] Add stdint.h proxy header to fix dependency issue with <stdint.h> includes. (#150303)
https://github.com/llvm/llvm-project/issues/149993
2025-07-23 20:19:52 -04:00
Joseph Huber 24828c8c45 [libc] Efficiently implement aligned_alloc for AMDGPU (#146585)
Summary:
This patch uses the actual allocator interface to implement
`aligned_alloc`. We do this by simply rounding up the amount allocated.
Because of how index calculation works, any offset within an allocated
pointer will still map to the same chunk, so we can just adjust
internally and it will free all the same.
2025-07-02 09:25:57 -05:00
Joseph Huber 10445acfa6 [libc] Efficiently implement 'realloc' for AMDGPU devices (#145960)
Summary:
Now that we have `malloc` we can implement `realloc` efficiently. This
uses the known chunk sizes to avoid unnecessary allocations. We just
return nullptr for NVPTX. I'd remove the list for the entrypoint but
then the libc++ code would stop working. When someone writes the NVPTX
support this will be trivial.
2025-06-30 08:39:40 -05:00
lntue d87eea35fa [libc] Move libc_errno.h to libc/src/__support and make LIBC_ERRNO_MODE_SYSTEM to be header-only. (#143187)
This is the first step in preparation for:
https://discourse.llvm.org/t/rfc-make-clang-builtin-math-functions-constexpr-with-llvm-libc-to-support-c-23-constexpr-math-functions/86450
2025-06-11 16:25:27 -04:00
enh-google 673047ea2b qsort_r.h: qsort_r() is POSIX now. (#138545) 2025-05-05 16:19:58 -04:00
Mohamed EmadandJoseph Huber 4840895467 [libc] implement memalignment (#132493)
This patch adds the `memalignment` function to LLVM-libc, following its
description in [WG14 N3220,
§7.24.2.1](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#page=387).

- [x] Add the implementation of `memalignment` in
[`/src/stdlib`](https://github.com/llvm/llvm-project/tree/main/libc/src/stdlib)
- [x] Add tests for `memalignment` in
[`/test/src/stdlib`](https://github.com/llvm/llvm-project/tree/main/libc/test/src/stdlib)
- [x] Add `memalignment` to
[`entrypoints.txt`](https://github.com/llvm/llvm-project/blob/main/libc/config/linux/x86_64/entrypoints.txt)
for at least x86_64 and whatever you're building on
- [x] Add `memalignment` to
[`include/stdlib.yaml`](https://github.com/llvm/llvm-project/blob/main/libc/include/stdlib.yaml)




Closes #132300

---------

Co-authored-by: Joseph Huber <huberjn@outlook.com>
2025-03-28 16:07:57 -07:00
Joseph Huber 598e882ee8 [libc] Template the writing mode for the writer class (#111559)
Summary:
Currently we dispatch the writing mode off of a runtime enum passed in
by the constructor. This causes very unfortunate codegen for the GPU
targets where we get worst-case codegen because of the unused function
pointer for `sprintf`. Instead, this patch moves all of this to a
template so it can be masked out. This results in no dynamic stack and
uses 60 VGPRs instead of 117. It also compiles about 5x as fast.
2025-03-12 13:51:44 -05:00
Vinay Deshmukh 257e483715 [libc] Add -Wno-sign-conversion & re-attempt -Wconversion (#129811)
Relates to
https://github.com/llvm/llvm-project/issues/119281#issuecomment-2699470459
2025-03-10 11:57:09 -04:00
Augie Fackler da61b0ddc5 Revert "[libc] Enable -Wconversion for tests. (#127523)"
This reverts commit 1e6e845d49 because it
changed the 1st parameter of adjust() to be unsigned, but libc itself
calls adjust() with a negative argument in align_backward() in
op_generic.h.
2025-03-05 16:42:40 -05:00
Vinay Deshmukh 1e6e845d49 [libc] Enable -Wconversion for tests. (#127523)
Relates to: #119281
2025-03-04 10:24:35 -05:00
Dmitri Gribenko 9084d2a0a1 [libc] Add a missing include
This is a fixup for
https://github.com/llvm/llvm-project/commit/da6d5fa79a558b66c281bed3f5ce848a69a65208.
2025-03-04 08:54:46 +01:00
Lukas Bergdoll da6d5fa79a Add missing LIBC_INLINE to qsort_pivot.h (#126249)
Fixes #111495
2025-03-03 10:33:02 -05:00
Michael Jones 64ae0a102f [libc] implement l64a (#129099)
Adds l64a, which generates the base 64 string expected by a64l.
2025-02-27 12:48:39 -08:00
Michael Jones 8beec9fc48 [libc] implement a64l (#128758)
Implement the posix function a64l.
Standard:
https://pubs.opengroup.org/onlinepubs/9799919799/functions/a64l.html
2025-02-25 13:57:13 -08:00
Joseph Huber 256f40d0e6 [libc] Use the NVIDIA device allocator for GPU malloc (#124277)
Summary:
This is a blocker on another patch in the OpenMP runtime. The problem is
that NVIDIA truly doesn't handle RPC-based allocations very well. It
cannot reliably update the MMU while a kernel is running and it will
usually deadlock if called from a separate thread due to internal use of
TLS.

This patch just removes the definition of `malloc` and `free` for NVPTX.
The result here is that they will be undefined, which is the cue for the
`nvlink` linker to define them for us. So, as far as `libc` is concerned
it still implements malloc.
2025-01-24 10:17:20 -06:00
Joseph Huber db6b7a84e6 [libc][NFC] Strip all training whitespace and missing newlines (#124163) 2025-01-23 12:02:54 -06:00