Debian Codegraph @

src/Main/bootstrap.cxx

raw symbols SCIP
1 // bootstrap.cxx -- bootstrap routines: main()
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 //
21 // $Id$
22
23 #include <config.h>
24
25 #include <simgear/compiler.h>
26
27 #if defined(SG_WINDOWS)
28 #include <windows.h>
29
30 #include <io.h> // isatty()
31 #define isatty _isatty
32 #else
33 #include <unistd.h> // for gethostname()
34 #endif
35
36 #if defined(__linux__)
37 // set link for setting _GNU_SOURCE before including fenv.h
38 // http://man7.org/linux/man-pages/man3/fenv.3.html
39
40 #ifndef _GNU_SOURCE
41 #define _GNU_SOURCE
42 #endif
43
44 #include <fenv.h>
45 #endif
46
47
48 #include <iostream>
49 #include <cerrno>
50 #include <csignal>
51 #include <cstdlib>
52 #include <cstdio>
53 #include <cstring>
54 #include <clocale>
55
56 #include <simgear/compiler.h>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/scene/tgdb/GroundLightManager.hxx>
59
60 #include <osg/BufferObject>
61 #include <osg/Texture>
62 #include <osg/Version>
63 #include <osgText/Font>
64
65 #include "main.hxx"
66 #include <GUI/MessageBox.hxx>
67 #include <Main/fg_init.hxx>
68 #include <Main/fg_props.hxx>
69 #include <Main/globals.hxx>
70 #include <Main/options.hxx>
71 #include <Main/sentryIntegration.hxx>
72 #include <Navaids/NavDataCache.hxx>
73 #include <Viewer/fgviewer.hxx>
74 #include <flightgearBuildId.h>
75
76 #include "fg_os.hxx"
77
78 #if defined(HAVE_QT)
79 #include <GUI/QtLauncher.hxx>
80 #endif
81
82 using std::cerr;
83 using std::endl;
84
85 std::string homedir;
86 std::string hostname;
87
88 // forward declaration.
89 void fgExitCleanup();
90
91 static void initFPE(bool enableExceptions);
92
93 #if defined(__linux__)
94
95 static void handleFPE(int);
96 static void
97 initFPE (bool fpeAbort)
98 {
99 if (fpeAbort) {
100 int except = fegetexcept();
101 feenableexcept(except | FE_DIVBYZERO | FE_INVALID);
102 } else {
103 signal(SIGFPE, handleFPE);
104 }
105 }
106
107 static void handleFPE(int)
108 {
109 feclearexcept(FE_ALL_EXCEPT);
110 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
111 signal(SIGFPE, handleFPE);
112 }
113 #elif defined (SG_WINDOWS)
114
115 static void initFPE(bool fpeAbort)
116 {
117 // Enable floating-point exceptions for Windows
118 if (fpeAbort) {
119 // set following link for what this does (note it does set SSE
120 // flags too, it's not just for the x87 FPU)
121 // http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx
122 _control87( _EM_INEXACT, _MCW_EM );
123 }
124 }
125
126 #else
127 static void initFPE(bool)
128 {
129 // Ignore floating-point exceptions on FreeBSD, OS-X, other Unices
130 signal(SIGFPE, SIG_IGN);
131 }
132 #endif
133
134 #if defined(SG_WINDOWS)
135 int main ( int argc, char **argv );
136 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
137 LPSTR lpCmdLine, int nCmdShow)
138 {
139 // convert wchar_t args to UTF-8 which is what we expect cross-platform
140 int numArgs = 0;
141 LPWSTR* wideArgs = CommandLineToArgvW(GetCommandLineW(), &numArgs);
142
143 std::vector<char*> utf8Args;
144 utf8Args.resize(numArgs);
145
146 for (int a = 0; a < numArgs; ++a) {
147 const auto s = simgear::strutils::convertWStringToUtf8(wideArgs[a]);
148 // note we leak these (strudp calls malloc) but not a big concern
149 utf8Args[a] = strdup(s.c_str());
150 }
151
152 main(numArgs, utf8Args.data());
153 }
154
155 // see https://stackoverflow.com/questions/35572792/setlocale-stuck-on-windows
156 // for why we need this
157 bool checkUniversalCRTVersion()
158 {
159 DWORD dwSize = 0;
160 VS_FIXEDFILEINFO *pFileInfo = NULL;
161 UINT puLenFileInfo = 0;
162
163 // Get the version information for the file requested
164 dwSize = GetFileVersionInfoSizeA("ucrtbase.dll", NULL);
165 if (dwSize == 0) {
166 return false;
167 }
168
169 std::vector<BYTE> versionInfo;
170 versionInfo.resize(dwSize);
171
172 if (!GetFileVersionInfoA("ucrtbase.dll", 0, dwSize, versionInfo.data())) {
173 return false;
174 }
175
176 if (!VerQueryValue(versionInfo.data(), TEXT("\\"), (LPVOID*)&pFileInfo, &puLenFileInfo)) {
177 return false;
178 }
179
180 const WORD majorVersion = pFileInfo->dwFileVersionMS >> 16;
181 const WORD minorVersion = pFileInfo->dwFileVersionMS & 0xffff;
182 const WORD buildVersion = pFileInfo->dwFileVersionLS >> 16;
183 const WORD releaseVersion = pFileInfo->dwFileVersionLS & 0xffff;
184
185 // char buffer[256];
186 // snprintf(buffer, 256, "File Version: %d.%d.%d.%d\n",
187 // majorVersion, minorVersion, buildVersion, releaseVersion);
188 // OutputDebugString(buffer);
189 return (buildVersion > 10586);
190 }
191
192 #endif
193
194 #if defined(__GNUC__)
195 #include <execinfo.h>
196 #include <cxxabi.h>
197 void segfault_handler(int signo) {
198
199 fprintf(stderr, "Error: caught signal %d:\n", signo);
200
201 #ifndef __OpenBSD__
202 void *array[128];
203 size_t size;
204 size = backtrace(array, 128);
205 if (size) {
206 char** list = backtrace_symbols(array, size);
207 size_t fnlen = 256;
208 char* fname = (char*)malloc(fnlen);
209
210 for (size_t i=1; i<size; i++) {
211 char *begin = 0, *offset = 0, *end = 0;
212 for (char *p = list[i]; *p; ++p) {
213 if (*p == '(') begin = p;
214 else if (*p == '+') offset = p;
215 else if (*p == ')' && offset) {
216 end = p;
217 break;
218 }
219 }
220
221 if (begin && offset && end && begin<offset) {
222 *begin++ = '\0'; *offset++ = '\0'; *end = '\0';
223
224 int status;
225 char* ret = abi::__cxa_demangle(begin, fname, &fnlen, &status);
226 if (status == 0) {
227 fname = ret;
228 fprintf(stderr, " %s : %s+%s\n", list[i], fname, offset);
229 }
230 else
231 fprintf(stderr, " %s : %s()+%s\n", list[i], begin, offset);
232 }
233 else
234 fprintf(stderr, " %s\n", list[i]);
235 }
236
237 free(fname);
238 free(list);
239 }
240 #endif
241
242 std::abort();
243 }
244 #endif
245
246 [[noreturn]] static void fg_terminate()
247 {
248 cerr << "Running FlightGear's terminate handler. The program is going to "
249 "exit due to a fatal error condition, sorry." << std::endl;
250 std::abort();
251 }
252
253 // Detect SSE2 support for x86, it is always available for x86_64
254 #if defined(__i386__)
255 # if defined(SG_WINDOWS)
256 # include <intrin.h>
257 # define get_cpuid(a,b) __cpuid(a,b)
258 # else
259 # include <cpuid.h>
260 # define get_cpuid(a,b) __cpuid(b,a[0],a[1],a[2],a[3])
261 # endif
262 # define CPUID_GETFEATURES 1
263 # define CPUID_FEAT_EDX_SSE2 (1 << 26)
264 bool detectSIMD()
265 {
266 static int regs[4] = {0,0,0,0};
267 get_cpuid(regs, CPUID_GETFEATURES);
268 return (regs[3] & CPUID_FEAT_EDX_SSE2);
269 }
270 #else
271 bool detectSIMD() { return true; }
272 #endif
273
274 int _bootstrap_OSInit;
275
276 // Main entry point; catch any exceptions that have made it this far.
277 int main ( int argc, char **argv )
278 {
279 // we don't want to accidently show a GUI box and block startup in
280 // non_GUI setups, so check this value early here, before options are
281 // processed
282 const bool headless = flightgear::Options::checkForArgDisable(argc, argv, "gui");
283 flightgear::setHeadlessMode(headless);
284
285 #ifdef ENABLE_SIMD
286 if (!detectSIMD()) {
287 flightgear::fatalMessageBoxThenExit(
288 "Fatal error",
289 "SSE2 support not detected, but this version of FlightGear requires "
290 "SSE2 hardware support.");
291 }
292 #endif
293
294 #if defined(SG_WINDOWS)
295 // Don't show blocking "no disk in drive" error messages on Windows 7,
296 // silently return errors to application instead.
297 // See Microsoft MSDN #ms680621: "GUI apps should specify SEM_NOOPENFILEERRORBOX"
298 SetErrorMode(SEM_NOOPENFILEERRORBOX);
299
300 hostname = ::getenv( "COMPUTERNAME" );
301
302 if (!checkUniversalCRTVersion()) {
303 flightgear::fatalMessageBoxThenExit(
304 "Fatal error",
305 "The Microsoft Universal CRT on this computer is too old to run FlightGear. "
306 "Please use Windows Update to install a more recent Universal CRT version.");
307 }
308 #else
309 // Unix(alike) systems
310 char _hostname[256];
311 gethostname(_hostname, 256);
312 hostname = _hostname;
313 signal(SIGPIPE, SIG_IGN);
314 #endif
315
316 _bootstrap_OSInit = 0;
317
318 // if we're not using the normal crash-reported, install our
319 // custom segfault handler on Linux, in debug builds.
320 // NB On OpenBSD this seems to lose info about where the signal
321 // happened, so is disabled.
322 #if !defined(SG_WINDOWS) && !defined(NDEBUG) && !defined(__OpenBSD__)
323 if (!flightgear::isSentryEnabled()) {
324 signal(SIGSEGV, segfault_handler);
325 }
326 #endif
327
328 initFPE(flightgear::Options::checkForArgEnable(argc, argv, "fpe"));
329
330 // pick up all user locale settings, but force C locale for numerical/sorting
331 // conversions because we have lots of code which assumes standard
332 // formatting
333 setlocale(LC_ALL, "");
334 setlocale(LC_NUMERIC, "C");
335 setlocale(LC_COLLATE, "C");
336
337 if (flightgear::Options::checkForArg(argc, argv, "uninstall")) {
338 return fgUninstall();
339 }
340
341 // ensure that we don't log anything to stderr if we're showing version, json-report, help
342 const bool earlyExit = flightgear::Options::checkForEarlyExitArg(argc, argv);
343 if (earlyExit) {
344 // if the user has redirected stderr, assume they know what they are doing :)
345 if (isatty(2)) {
346 logstream::disableStderrLogging();
347 }
348 }
349
350 #if defined(HAVE_SENTRY)
351 const bool noSentry = flightgear::Options::checkForArgDisable(argc, argv, "sentry");
352 if (!noSentry) {
353 flightgear::initSentry(earlyExit);
354 }
355 #endif
356
357 bool fgviewer = flightgear::Options::checkForArg(argc, argv, "fgviewer");
358 int exitStatus = EXIT_FAILURE;
359 try {
360 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1231
361 // ensure sglog is inited before atexit() is registered, so logging
362 // is possible inside fgExitCleanup
363 sglog();
364
365
366 #if OSG_VERSION_LESS_THAN(3, 5, 0)
367 // similar to above, ensure some static maps inside OSG exist before
368 // we register our at-exit handler, otherwise the statics are gone
369 // when fg_terminate runs, which causes crashes.
370 osg::Texture::getTextureObjectManager(0);
371 osg::GLBufferObjectManager::getGLBufferObjectManager(0);
372
373 // ensure this is called early (and hence deleted) late,
374 // otherwise fgExitCleanup crahses: see
375 // Sentry FLIGHTEAR-M68
376 osgText::Font::getDefaultFont();
377 #endif
378 std::set_terminate(fg_terminate);
379 atexit(fgExitCleanup);
380
381 if (fgviewer) {
382 exitStatus = fgviewerMain(argc, argv);
383 } else {
384 exitStatus = fgMainInit(argc, argv);
385 }
386
387 } catch (const sg_throwable &t) {
388 std::string info;
389 if (std::strlen(t.getOrigin()) != 0)
390 info = std::string("received from ") + t.getOrigin();
391 flightgear::fatalMessageBoxWithoutExit(
392 "Fatal exception", t.getFormattedMessage(), info);
393 } catch (const std::bad_alloc&) {
394 flightgear::fatalMessageBoxWithoutExit("Out of memory",
395 "FlightGear ran out of memory and must exit.", "Consider adjusting your settings or closing other applications.");
396 } catch (const std::exception &e ) {
397 flightgear::fatalMessageBoxWithoutExit("Fatal exception", e.what());
398 } catch (const std::string &s) {
399 flightgear::fatalMessageBoxWithoutExit("Fatal exception", s);
400 } catch (const flightgear::FatalErrorException&) {
401 // we already showed the message box, just carry on to exit
402 } catch (const char *s) {
403 std::cerr << "Fatal error (const char*): " << s << std::endl;
404 } catch (...) {
405 flightgear::sentryReportException("Unknown main loop exception");
406 std::cerr << "Unknown exception in the main loop. Aborting..." << std::endl;
407 if (errno)
408 perror("Possible cause");
409 }
410
411 #if defined(HAVE_QT)
412 flightgear::shutdownQtApp();
413 #endif
414 return exitStatus;
415 }
416
417 // do some clean up on exit. Specifically we want to delete the sound-manager,
418 // so OpenAL device and context are released cleanly
419 void fgExitCleanup()
420 {
421 flightgear::addSentryBreadcrumb("starting fgExitCleanup", "info");
422
423 if (_bootstrap_OSInit != 0) {
424 fgOSCloseWindow();
425 }
426
427 // you might imagine we'd call shutdownQtApp here, but it's not safe to do
428 // so in an atexit handler, and crashes on Mac. Thiago states this explicitly:
429 // https://bugreports.qt.io/browse/QTBUG-48709
430
431 // on the common exit path globals is already deleted, and NULL,
432 // so this only happens on error paths.
433 delete globals;
434
435 flightgear::addSentryBreadcrumb("finished deleting globals", "info");
436
437 // important we do this *after* deleting globals, since in
438 // the error case, globals will shutdown+unbind all the subsystems, and that
439 // can need a working nav-cache.
440 flightgear::NavDataCache::shutdown();
441
442 // avoid crash on exit (https://sourceforge.net/p/flightgear/codetickets/1935/)
443 simgear::GroundLightManager::instance()->getRunwayLightStateSet()->clear();
444 simgear::GroundLightManager::instance()->getTaxiLightStateSet()->clear();
445 simgear::GroundLightManager::instance()->getGroundLightStateSet()->clear();
446
447 simgear::shutdownLogging();
448 flightgear::shutdownSentry();
449 }