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