[libc++][Android] Allow testing libc++ with clang-r536225 (#116149)
[llvm-project.git] / libc / src / stdlib / getenv.cpp
blobe6ef03fad5c51ef9984e3d6b23f16d651795fbf7
1 //===-- Implementation of getenv ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "src/stdlib/getenv.h"
10 #include "config/app.h"
11 #include "src/__support/CPP/string_view.h"
12 #include "src/__support/common.h"
13 #include "src/__support/macros/config.h"
15 #include <stddef.h> // For size_t.
17 namespace LIBC_NAMESPACE_DECL {
19 LLVM_LIBC_FUNCTION(char *, getenv, (const char *name)) {
20 char **env_ptr = reinterpret_cast<char **>(LIBC_NAMESPACE::app.env_ptr);
22 if (name == nullptr || env_ptr == nullptr)
23 return nullptr;
25 LIBC_NAMESPACE::cpp::string_view env_var_name(name);
26 if (env_var_name.size() == 0)
27 return nullptr;
28 for (char **env = env_ptr; *env != nullptr; env++) {
29 LIBC_NAMESPACE::cpp::string_view cur(*env);
30 if (!cur.starts_with(env_var_name))
31 continue;
33 if (cur[env_var_name.size()] != '=')
34 continue;
36 // Remove the name and the equals sign.
37 cur.remove_prefix(env_var_name.size() + 1);
38 // We know that data is null terminated, so this is safe.
39 return const_cast<char *>(cur.data());
42 return nullptr;
45 } // namespace LIBC_NAMESPACE_DECL