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