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" 10*1a92cc5aSJoseph Huber #include "config/app.h" 11aa59c981SGuillaume Chatelet #include "src/__support/CPP/string_view.h" 12f2a7f835SRaman Tenneti #include "src/__support/common.h" 135ff3ff33SPetr Hosek #include "src/__support/macros/config.h" 14f2a7f835SRaman Tenneti 15f2a7f835SRaman Tenneti #include <stddef.h> // For size_t. 16f2a7f835SRaman Tenneti 175ff3ff33SPetr Hosek namespace LIBC_NAMESPACE_DECL { 18f2a7f835SRaman Tenneti 19f2a7f835SRaman Tenneti LLVM_LIBC_FUNCTION(char *, getenv, (const char *name)) { 20a0eda109SSchrodinger ZHU Yifan char **env_ptr = reinterpret_cast<char **>(LIBC_NAMESPACE::app.env_ptr); 21f2a7f835SRaman Tenneti 22f2a7f835SRaman Tenneti if (name == nullptr || env_ptr == nullptr) 23f2a7f835SRaman Tenneti return nullptr; 24f2a7f835SRaman Tenneti 25b6bc9d72SGuillaume Chatelet LIBC_NAMESPACE::cpp::string_view env_var_name(name); 26f2a7f835SRaman Tenneti if (env_var_name.size() == 0) 27f2a7f835SRaman Tenneti return nullptr; 28f2a7f835SRaman Tenneti for (char **env = env_ptr; *env != nullptr; env++) { 29b6bc9d72SGuillaume Chatelet LIBC_NAMESPACE::cpp::string_view cur(*env); 30f2a7f835SRaman Tenneti if (!cur.starts_with(env_var_name)) 31f2a7f835SRaman Tenneti continue; 32f2a7f835SRaman Tenneti 33f2a7f835SRaman Tenneti if (cur[env_var_name.size()] != '=') 34f2a7f835SRaman Tenneti continue; 35f2a7f835SRaman Tenneti 368aad330eSJeff Bailey // Remove the name and the equals sign. 378aad330eSJeff Bailey cur.remove_prefix(env_var_name.size() + 1); 388aad330eSJeff Bailey // We know that data is null terminated, so this is safe. 398aad330eSJeff Bailey return const_cast<char *>(cur.data()); 40f2a7f835SRaman Tenneti } 41f2a7f835SRaman Tenneti 42f2a7f835SRaman Tenneti return nullptr; 43f2a7f835SRaman Tenneti } 44f2a7f835SRaman Tenneti 455ff3ff33SPetr Hosek } // namespace LIBC_NAMESPACE_DECL 46