180814287SRaphael Isemann //===-- Environment.cpp ---------------------------------------------------===//
262930e57SPavel Labath //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
662930e57SPavel Labath //
762930e57SPavel Labath //===----------------------------------------------------------------------===//
862930e57SPavel Labath 
962930e57SPavel Labath #include "lldb/Utility/Environment.h"
1062930e57SPavel Labath 
1162930e57SPavel Labath using namespace lldb_private;
1262930e57SPavel Labath 
make_entry(llvm::StringRef Key,llvm::StringRef Value)1362930e57SPavel Labath char *Environment::Envp::make_entry(llvm::StringRef Key,
1462930e57SPavel Labath                                     llvm::StringRef Value) {
1562930e57SPavel Labath   const size_t size = Key.size() + 1 /*=*/ + Value.size() + 1 /*\0*/;
1665fdb342SRaphael Isemann   char *Result = static_cast<char *>(
1762930e57SPavel Labath       Allocator.Allocate(sizeof(char) * size, alignof(char)));
1862930e57SPavel Labath   char *Next = Result;
1962930e57SPavel Labath 
2062930e57SPavel Labath   Next = std::copy(Key.begin(), Key.end(), Next);
2162930e57SPavel Labath   *Next++ = '=';
2262930e57SPavel Labath   Next = std::copy(Value.begin(), Value.end(), Next);
2362930e57SPavel Labath   *Next++ = '\0';
2462930e57SPavel Labath 
2562930e57SPavel Labath   return Result;
2662930e57SPavel Labath }
2762930e57SPavel Labath 
Envp(const Environment & Env)2862930e57SPavel Labath Environment::Envp::Envp(const Environment &Env) {
2965fdb342SRaphael Isemann   Data = static_cast<char **>(
3062930e57SPavel Labath       Allocator.Allocate(sizeof(char *) * (Env.size() + 1), alignof(char *)));
3162930e57SPavel Labath   char **Next = Data;
3262930e57SPavel Labath   for (const auto &KV : Env)
3362930e57SPavel Labath     *Next++ = make_entry(KV.first(), KV.second);
3462930e57SPavel Labath   *Next++ = nullptr;
3562930e57SPavel Labath }
3662930e57SPavel Labath 
Environment(const char * const * Env)3762930e57SPavel Labath Environment::Environment(const char *const *Env) {
3862930e57SPavel Labath   if (!Env)
3962930e57SPavel Labath     return;
4062930e57SPavel Labath   while (*Env)
4162930e57SPavel Labath     insert(*Env++);
4262930e57SPavel Labath }
4362930e57SPavel Labath 
insert(iterator first,iterator last)44*7f544f76SNico Weber void Environment::insert(iterator first, iterator last) {
4562930e57SPavel Labath   while (first != last) {
4662930e57SPavel Labath     try_emplace(first->first(), first->second);
4762930e57SPavel Labath     ++first;
4862930e57SPavel Labath   }
4962930e57SPavel Labath }
50