1 //
2 // Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // system_utils_osx.cpp: Implementation of OS-specific functions for OSX
8 
9 #include "system_utils.h"
10 
11 #include <unistd.h>
12 
13 #include <cstdlib>
14 #include <mach-o/dyld.h>
15 #include <vector>
16 
17 #include <array>
18 
19 namespace angle
20 {
21 
22 namespace
23 {
24 
GetExecutablePathImpl()25 std::string GetExecutablePathImpl()
26 {
27     std::string result;
28 
29     uint32_t size = 0;
30     _NSGetExecutablePath(nullptr, &size);
31 
32     std::vector<char> buffer;
33     buffer.resize(size + 1);
34 
35     _NSGetExecutablePath(buffer.data(), &size);
36     buffer[size] = '\0';
37 
38     if (!strrchr(buffer.data(), '/'))
39     {
40         return "";
41     }
42     return buffer.data();
43 }
44 
GetExecutableDirectoryImpl()45 std::string GetExecutableDirectoryImpl()
46 {
47     std::string executablePath = GetExecutablePath();
48     size_t lastPathSepLoc      = executablePath.find_last_of("/");
49     return (lastPathSepLoc != std::string::npos) ? executablePath.substr(0, lastPathSepLoc) : "";
50 }
51 
52 }  // anonymous namespace
53 
GetExecutablePath()54 const char *GetExecutablePath()
55 {
56     // TODO(jmadill): Make global static string thread-safe.
57     const static std::string &exePath = GetExecutablePathImpl();
58     return exePath.c_str();
59 }
60 
GetExecutableDirectory()61 const char *GetExecutableDirectory()
62 {
63     // TODO(jmadill): Make global static string thread-safe.
64     const static std::string &exeDir = GetExecutableDirectoryImpl();
65     return exeDir.c_str();
66 }
67 
GetSharedLibraryExtension()68 const char *GetSharedLibraryExtension()
69 {
70     return "dylib";
71 }
72 
GetCWD()73 Optional<std::string> GetCWD()
74 {
75     std::array<char, 4096> pathBuf;
76     char *result = getcwd(pathBuf.data(), pathBuf.size());
77     if (result == nullptr)
78     {
79         return Optional<std::string>::Invalid();
80     }
81     return std::string(pathBuf.data());
82 }
83 
SetCWD(const char * dirName)84 bool SetCWD(const char *dirName)
85 {
86     return (chdir(dirName) == 0);
87 }
88 
SetEnvironmentVar(const char * variableName,const char * value)89 bool SetEnvironmentVar(const char *variableName, const char *value)
90 {
91     return (setenv(variableName, value, 1) == 0);
92 }
93 
94 }  // namespace angle
95