1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "common/libs/utils/environment.h"
18
19 #include <sys/utsname.h>
20
21 #include <cstdio>
22 #include <cstdlib>
23 #include <memory>
24 #include <ostream>
25 #include <string>
26
27 #include <android-base/logging.h>
28 #include <android-base/no_destructor.h>
29 #include <android-base/strings.h>
30
31 #include "common/libs/utils/files.h"
32
33 namespace cuttlefish {
34
StringFromEnv(const std::string & varname,const std::string & defval)35 std::string StringFromEnv(const std::string& varname,
36 const std::string& defval) {
37 const char* const valstr = getenv(varname.c_str());
38 if (!valstr) {
39 return defval;
40 }
41 return valstr;
42 }
43
44 /** Returns e.g. aarch64, x86_64, etc */
HostArchStr()45 const std::string& HostArchStr() {
46 static android::base::NoDestructor<std::string> arch([] {
47 utsname buf;
48 CHECK_EQ(uname(&buf), 0) << strerror(errno);
49 return std::string(buf.machine);
50 }());
51 return *arch;
52 }
53
HostArch()54 Arch HostArch() {
55 std::string arch_str = HostArchStr();
56 if (arch_str == "aarch64" || arch_str == "arm64") {
57 return Arch::Arm64;
58 } else if (arch_str == "arm") {
59 return Arch::Arm;
60 } else if (arch_str == "riscv64") {
61 return Arch::RiscV64;
62 } else if (arch_str == "x86_64") {
63 return Arch::X86_64;
64 } else if (arch_str.size() == 4 && arch_str[0] == 'i' && arch_str[2] == '8' &&
65 arch_str[3] == '6') {
66 return Arch::X86;
67 } else {
68 LOG(FATAL) << "Unknown host architecture: " << arch_str;
69 return Arch::X86;
70 }
71 }
72
IsHostCompatible(Arch arch)73 bool IsHostCompatible(Arch arch) {
74 Arch host_arch = HostArch();
75 return arch == host_arch || (arch == Arch::Arm && host_arch == Arch::Arm64) ||
76 (arch == Arch::X86 && host_arch == Arch::X86_64);
77 }
78
IsRunningInDocker()79 static bool IsRunningInDocker() {
80 // if /.dockerenv exists, it's inside a docker container
81 static std::string docker_env_path("/.dockerenv");
82 static bool ret =
83 FileExists(docker_env_path) || DirectoryExists(docker_env_path);
84 return ret;
85 }
86
IsRunningInContainer()87 bool IsRunningInContainer() {
88 // TODO: add more if we support other containers than docker
89 return IsRunningInDocker();
90 }
91
92 } // namespace cuttlefish
93