Files
llvm-tms34010/libc/src/stdlib/strtoul.cpp
T
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

31 lines
1.0 KiB
C++

//===-- Implementation of strtoul -----------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "src/stdlib/strtoul.h"
#include "src/__support/common.h"
#include "src/__support/libc_errno.h"
#include "src/__support/macros/config.h"
#include "src/__support/str_to_integer.h"
namespace LIBC_NAMESPACE_DECL {
LLVM_LIBC_FUNCTION(unsigned long, strtoul,
(const char *__restrict str, char **__restrict str_end,
int base)) {
auto result = internal::strtointeger<unsigned long>(str, base);
if (result.has_error())
libc_errno = result.error;
if (str_end != nullptr && result.error != EINVAL)
*str_end = const_cast<char *>(str + result.parsed_len);
return result;
}
} // namespace LIBC_NAMESPACE_DECL