Joseph Huber 1a92cc5a0a
[libc] Implement 'getenv' on the GPU target (#102376)
Summary:
This patch implements 'getenv'. I was torn on how to implement this,
since realistically we only have access to this environment pointer in
the "loader" interface. An alternative would be to use an RPC call every
time, but I think that's overkill for what this will be used for. A
better solution is just to emit a common `DataEnvironment` that contains
all of the host visible resources to initialize. Right now this is the
`env_ptr`, `clock_freq`, and `rpc_client`.

I did this by making the `app.h` interface that Linux uses more general,
could possibly move that into a separate patch, but I figured it's
easier to see with the usage.
2024-08-08 06:45:42 -05:00

46 lines
1.4 KiB
C++

//===-- Implementation of getenv ------------------------------------------===//
//
// 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/getenv.h"
#include "config/app.h"
#include "src/__support/CPP/string_view.h"
#include "src/__support/common.h"
#include "src/__support/macros/config.h"
#include <stddef.h> // For size_t.
namespace LIBC_NAMESPACE_DECL {
LLVM_LIBC_FUNCTION(char *, getenv, (const char *name)) {
char **env_ptr = reinterpret_cast<char **>(LIBC_NAMESPACE::app.env_ptr);
if (name == nullptr || env_ptr == nullptr)
return nullptr;
LIBC_NAMESPACE::cpp::string_view env_var_name(name);
if (env_var_name.size() == 0)
return nullptr;
for (char **env = env_ptr; *env != nullptr; env++) {
LIBC_NAMESPACE::cpp::string_view cur(*env);
if (!cur.starts_with(env_var_name))
continue;
if (cur[env_var_name.size()] != '=')
continue;
// Remove the name and the equals sign.
cur.remove_prefix(env_var_name.size() + 1);
// We know that data is null terminated, so this is safe.
return const_cast<char *>(cur.data());
}
return nullptr;
}
} // namespace LIBC_NAMESPACE_DECL