LibCore: Be more BSD-friendly in Core::Environment

FreeBSD and NetBSD don't have secure_getenv(3), same as macOS.
FreeBSD 13 and lower also don't allow setting environ pointers to null.

Co-Authored-By: Robert Clausecker <fuz@FreeBSD.org>
This commit is contained in:
Andrew Kaster 2024-05-09 12:32:06 -06:00 committed by Andrew Kaster
parent 89092e98a4
commit 405ce6e5f5
Notes: sideshowbarker 2024-07-17 02:08:15 +09:00

View file

@ -13,7 +13,7 @@
#if defined(AK_OS_MACOS) || defined(AK_OS_IOS) #if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
# include <crt_externs.h> # include <crt_externs.h>
#else #else
extern char** environ; extern "C" char** environ;
#endif #endif
namespace Core::Environment { namespace Core::Environment {
@ -93,15 +93,16 @@ Optional<StringView> get(StringView name, [[maybe_unused]] SecureOnly secure)
builder.append('\0'); builder.append('\0');
// Note the explicit null terminators above. // Note the explicit null terminators above.
#if defined(AK_OS_MACOS) || defined(AK_OS_ANDROID) // FreeBSD < 14, Android, and generic BSDs do not support secure_getenv.
char* result = ::getenv(builder.string_view().characters_without_null_termination()); #if (defined(__FreeBSD__) && __FreeBSD__ >= 14) || (!defined(AK_OS_BSD_GENERIC) && !defined(AK_OS_ANDROID))
#else
char* result; char* result;
if (secure == SecureOnly::Yes) { if (secure == SecureOnly::Yes) {
result = ::secure_getenv(builder.string_view().characters_without_null_termination()); result = ::secure_getenv(builder.string_view().characters_without_null_termination());
} else { } else {
result = ::getenv(builder.string_view().characters_without_null_termination()); result = ::getenv(builder.string_view().characters_without_null_termination());
} }
#else
char* result = ::getenv(builder.string_view().characters_without_null_termination());
#endif #endif
if (result) if (result)
return StringView { result, strlen(result) }; return StringView { result, strlen(result) };
@ -153,7 +154,9 @@ ErrorOr<void> put(StringView env)
ErrorOr<void> clear() ErrorOr<void> clear()
{ {
#if defined(AK_OS_MACOS) #if (defined(__FreeBSD__) && __FreeBSD__ < 14)
environ = nullptr;
#elif defined(AK_OS_BSD_GENERIC) && !defined(AK_OS_FREEBSD)
auto environment = raw_environ(); auto environment = raw_environ();
for (size_t environ_size = 0; environment[environ_size]; ++environ_size) { for (size_t environ_size = 0; environment[environ_size]; ++environ_size) {
environment[environ_size] = NULL; environment[environ_size] = NULL;