b80bed250596a9e2094eebc4c99adb42d5ce2cc8
[platform/upstream/flatbuffers.git] / src / util.cpp
1 /*
2  * Copyright 2016 Google Inc. All rights reserved.
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 // clang-format off
18 // Dont't remove `format off`, it prevent reordering of win-includes.
19 #define _POSIX_C_SOURCE 200112L // For stat from stat/stat.h and fseeko() (POSIX extensions).
20 #ifdef _WIN32
21 #  ifndef WIN32_LEAN_AND_MEAN
22 #    define WIN32_LEAN_AND_MEAN
23 #  endif
24 #  ifndef NOMINMAX
25 #    define NOMINMAX
26 #  endif
27 #  ifdef _MSC_VER
28 #    include <crtdbg.h>
29 #  endif
30 #  include <windows.h>  // Must be included before <direct.h>
31 #  include <direct.h>
32 #  include <winbase.h>
33 #  undef interface  // This is also important because of reasons
34 #else
35 #  define _XOPEN_SOURCE 600 // For PATH_MAX from limits.h (SUSv2 extension) 
36 #  include <limits.h>
37 #endif
38 // clang-format on
39
40 #include "flatbuffers/base.h"
41 #include "flatbuffers/util.h"
42
43 #include <sys/stat.h>
44 #include <clocale>
45 #include <fstream>
46
47 namespace flatbuffers {
48
49 bool FileExistsRaw(const char *name) {
50   std::ifstream ifs(name);
51   return ifs.good();
52 }
53
54 bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
55   if (DirExists(name)) return false;
56   std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
57   if (!ifs.is_open()) return false;
58   if (binary) {
59     // The fastest way to read a file into a string.
60     ifs.seekg(0, std::ios::end);
61     auto size = ifs.tellg();
62     (*buf).resize(static_cast<size_t>(size));
63     ifs.seekg(0, std::ios::beg);
64     ifs.read(&(*buf)[0], (*buf).size());
65   } else {
66     // This is slower, but works correctly on all platforms for text files.
67     std::ostringstream oss;
68     oss << ifs.rdbuf();
69     *buf = oss.str();
70   }
71   return !ifs.bad();
72 }
73
74 static LoadFileFunction g_load_file_function = LoadFileRaw;
75 static FileExistsFunction g_file_exists_function = FileExistsRaw;
76
77 bool LoadFile(const char *name, bool binary, std::string *buf) {
78   FLATBUFFERS_ASSERT(g_load_file_function);
79   return g_load_file_function(name, binary, buf);
80 }
81
82 bool FileExists(const char *name) {
83   FLATBUFFERS_ASSERT(g_file_exists_function);
84   return g_file_exists_function(name);
85 }
86
87 bool DirExists(const char *name) {
88   // clang-format off
89
90   #ifdef _WIN32
91     #define flatbuffers_stat _stat
92     #define FLATBUFFERS_S_IFDIR _S_IFDIR
93   #else
94     #define flatbuffers_stat stat
95     #define FLATBUFFERS_S_IFDIR S_IFDIR
96   #endif
97   // clang-format on
98   struct flatbuffers_stat file_info;
99   if (flatbuffers_stat(name, &file_info) != 0) return false;
100   return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
101 }
102
103 LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
104   LoadFileFunction previous_function = g_load_file_function;
105   g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
106   return previous_function;
107 }
108
109 FileExistsFunction SetFileExistsFunction(
110     FileExistsFunction file_exists_function) {
111   FileExistsFunction previous_function = g_file_exists_function;
112   g_file_exists_function =
113       file_exists_function ? file_exists_function : FileExistsRaw;
114   return previous_function;
115 }
116
117 bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
118   std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
119   if (!ofs.is_open()) return false;
120   ofs.write(buf, len);
121   return !ofs.bad();
122 }
123
124 // We internally store paths in posix format ('/'). Paths supplied
125 // by the user should go through PosixPath to ensure correct behavior
126 // on Windows when paths are string-compared.
127
128 static const char kPathSeparatorWindows = '\\';
129 static const char *PathSeparatorSet = "\\/";  // Intentionally no ':'
130
131 std::string StripExtension(const std::string &filepath) {
132   size_t i = filepath.find_last_of('.');
133   return i != std::string::npos ? filepath.substr(0, i) : filepath;
134 }
135
136 std::string GetExtension(const std::string &filepath) {
137   size_t i = filepath.find_last_of('.');
138   return i != std::string::npos ? filepath.substr(i + 1) : "";
139 }
140
141 std::string StripPath(const std::string &filepath) {
142   size_t i = filepath.find_last_of(PathSeparatorSet);
143   return i != std::string::npos ? filepath.substr(i + 1) : filepath;
144 }
145
146 std::string StripFileName(const std::string &filepath) {
147   size_t i = filepath.find_last_of(PathSeparatorSet);
148   return i != std::string::npos ? filepath.substr(0, i) : "";
149 }
150
151 std::string ConCatPathFileName(const std::string &path,
152                                const std::string &filename) {
153   std::string filepath = path;
154   if (filepath.length()) {
155     char &filepath_last_character = string_back(filepath);
156     if (filepath_last_character == kPathSeparatorWindows) {
157       filepath_last_character = kPathSeparator;
158     } else if (filepath_last_character != kPathSeparator) {
159       filepath += kPathSeparator;
160     }
161   }
162   filepath += filename;
163   // Ignore './' at the start of filepath.
164   if (filepath[0] == '.' && filepath[1] == kPathSeparator) {
165     filepath.erase(0, 2);
166   }
167   return filepath;
168 }
169
170 std::string PosixPath(const char *path) {
171   std::string p = path;
172   std::replace(p.begin(), p.end(), '\\', '/');
173   return p;
174 }
175
176 void EnsureDirExists(const std::string &filepath) {
177   auto parent = StripFileName(filepath);
178   if (parent.length()) EnsureDirExists(parent);
179     // clang-format off
180
181   #ifdef _WIN32
182     (void)_mkdir(filepath.c_str());
183   #else
184     mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
185   #endif
186   // clang-format on
187 }
188
189 std::string AbsolutePath(const std::string &filepath) {
190   // clang-format off
191
192   #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
193     return filepath;
194   #else
195     #ifdef _WIN32
196       char abs_path[MAX_PATH];
197       return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr)
198     #else
199       char abs_path[PATH_MAX];
200       return realpath(filepath.c_str(), abs_path)
201     #endif
202       ? abs_path
203       : filepath;
204   #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
205   // clang-format on
206 }
207
208 // Locale-independent code.
209 #if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \
210     (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
211
212 // clang-format off
213 // Allocate locale instance at startup of application.
214 ClassicLocale ClassicLocale::instance_;
215
216 #ifdef _MSC_VER
217   ClassicLocale::ClassicLocale()
218     : locale_(_create_locale(LC_ALL, "C")) {}
219   ClassicLocale::~ClassicLocale() { _free_locale(locale_); }
220 #else
221   ClassicLocale::ClassicLocale()
222     : locale_(newlocale(LC_ALL, "C", nullptr)) {}
223   ClassicLocale::~ClassicLocale() { freelocale(locale_); }
224 #endif
225 // clang-format on
226
227 #endif  // !FLATBUFFERS_LOCALE_INDEPENDENT
228
229 std::string RemoveStringQuotes(const std::string &s) {
230   auto ch = *s.c_str();
231   return ((s.size() >= 2) && (ch == '\"' || ch == '\'') &&
232           (ch == string_back(s)))
233              ? s.substr(1, s.length() - 2)
234              : s;
235 }
236
237 bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
238   const auto the_locale = setlocale(LC_ALL, locale_name);
239   if (!the_locale) return false;
240   if (_value) *_value = std::string(the_locale);
241   return true;
242 }
243
244 bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
245   #ifdef _MSC_VER
246   __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS
247   #endif
248   auto env_str = std::getenv(var_name);
249   if (!env_str) return false;
250   if (_value) *_value = std::string(env_str);
251   return true;
252 }
253
254 void SetupDefaultCRTReportMode() {
255   // clang-format off
256
257   #ifdef _MSC_VER
258     // By default, send all reports to STDOUT to prevent CI hangs.
259     // Enable assert report box [Abort|Retry|Ignore] if a debugger is present.
260     const int dbg_mode = (_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG) |
261                          (IsDebuggerPresent() ? _CRTDBG_MODE_WNDW : 0);
262     (void)dbg_mode; // release mode fix
263     // CrtDebug reports to _CRT_WARN channel.
264     _CrtSetReportMode(_CRT_WARN, dbg_mode);
265     _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
266     // The assert from <assert.h> reports to _CRT_ERROR channel
267     _CrtSetReportMode(_CRT_ERROR, dbg_mode);
268     _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
269     // Internal CRT assert channel?
270     _CrtSetReportMode(_CRT_ASSERT, dbg_mode);
271     _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
272   #endif
273
274   // clang-format on
275 }
276
277 }  // namespace flatbuffers