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