1f2a7f835SRaman Tenneti //===-- Implementation of getenv ------------------------------------------===//
2f2a7f835SRaman Tenneti //
3f2a7f835SRaman Tenneti // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4f2a7f835SRaman Tenneti // See https://llvm.org/LICENSE.txt for license information.
5f2a7f835SRaman Tenneti // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f2a7f835SRaman Tenneti //
7f2a7f835SRaman Tenneti //===----------------------------------------------------------------------===//
8f2a7f835SRaman Tenneti 
9f2a7f835SRaman Tenneti #include "src/stdlib/getenv.h"
10f2a7f835SRaman Tenneti #include "config/linux/app.h"
11f2a7f835SRaman Tenneti #include "src/__support/CPP/StringView.h"
12f2a7f835SRaman Tenneti #include "src/__support/common.h"
13f2a7f835SRaman Tenneti 
14f2a7f835SRaman Tenneti #include <stddef.h> // For size_t.
15f2a7f835SRaman Tenneti 
16f2a7f835SRaman Tenneti namespace __llvm_libc {
17f2a7f835SRaman Tenneti 
18f2a7f835SRaman Tenneti LLVM_LIBC_FUNCTION(char *, getenv, (const char *name)) {
19f2a7f835SRaman Tenneti   char **env_ptr = reinterpret_cast<char **>(__llvm_libc::app.envPtr);
20f2a7f835SRaman Tenneti 
21f2a7f835SRaman Tenneti   if (name == nullptr || env_ptr == nullptr)
22f2a7f835SRaman Tenneti     return nullptr;
23f2a7f835SRaman Tenneti 
24f2a7f835SRaman Tenneti   __llvm_libc::cpp::StringView env_var_name(name);
25f2a7f835SRaman Tenneti   if (env_var_name.size() == 0)
26f2a7f835SRaman Tenneti     return nullptr;
27f2a7f835SRaman Tenneti   for (char **env = env_ptr; *env != nullptr; env++) {
28f2a7f835SRaman Tenneti     __llvm_libc::cpp::StringView cur(*env);
29f2a7f835SRaman Tenneti     if (!cur.starts_with(env_var_name))
30f2a7f835SRaman Tenneti       continue;
31f2a7f835SRaman Tenneti 
32f2a7f835SRaman Tenneti     if (cur[env_var_name.size()] != '=')
33f2a7f835SRaman Tenneti       continue;
34f2a7f835SRaman Tenneti 
35*8aad330eSJeff Bailey     // Remove the name and the equals sign.
36*8aad330eSJeff Bailey     cur.remove_prefix(env_var_name.size() + 1);
37*8aad330eSJeff Bailey     // We know that data is null terminated, so this is safe.
38*8aad330eSJeff Bailey     return const_cast<char *>(cur.data());
39f2a7f835SRaman Tenneti   }
40f2a7f835SRaman Tenneti 
41f2a7f835SRaman Tenneti   return nullptr;
42f2a7f835SRaman Tenneti }
43f2a7f835SRaman Tenneti 
44f2a7f835SRaman Tenneti } // namespace __llvm_libc
45