Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / src / stdlib / getenv.cpp
blob08397e0d805716181d71dab502dd45560070b8ac
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/linux/app.h"
11 #include "src/__support/CPP/string_view.h"
12 #include "src/__support/common.h"
14 #include <stddef.h> // For size_t.
16 namespace LIBC_NAMESPACE {
18 LLVM_LIBC_FUNCTION(char *, getenv, (const char *name)) {
19 char **env_ptr = reinterpret_cast<char **>(LIBC_NAMESPACE::app.envPtr);
21 if (name == nullptr || env_ptr == nullptr)
22 return nullptr;
24 LIBC_NAMESPACE::cpp::string_view env_var_name(name);
25 if (env_var_name.size() == 0)
26 return nullptr;
27 for (char **env = env_ptr; *env != nullptr; env++) {
28 LIBC_NAMESPACE::cpp::string_view cur(*env);
29 if (!cur.starts_with(env_var_name))
30 continue;
32 if (cur[env_var_name.size()] != '=')
33 continue;
35 // Remove the name and the equals sign.
36 cur.remove_prefix(env_var_name.size() + 1);
37 // We know that data is null terminated, so this is safe.
38 return const_cast<char *>(cur.data());
41 return nullptr;
44 } // namespace LIBC_NAMESPACE