]> git.saurik.com Git - wxWidgets.git/blob - src/common/init.cpp
check memory leaks sooner, when wxLog target is still available
[wxWidgets.git] / src / common / init.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/init.cpp
3 // Purpose: initialisation for the library
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 04.10.99
7 // RCS-ID: $Id$
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif //__BORLANDC__
25
26 #ifndef WX_PRECOMP
27 #include "wx/app.h"
28 #include "wx/debug.h"
29 #include "wx/filefn.h"
30 #include "wx/log.h"
31 #include "wx/thread.h"
32 #endif
33
34 #include "wx/init.h"
35
36 #include "wx/ptr_scpd.h"
37 #include "wx/module.h"
38
39 #if defined(__WXMSW__) && defined(__WXDEBUG__)
40 #include "wx/msw/msvcrt.h"
41
42 static struct EnableMemLeakChecking
43 {
44 EnableMemLeakChecking()
45 {
46 // do check for memory leaks on program exit (another useful flag
47 // is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free deallocated
48 // memory which may be used to simulate low-memory condition)
49 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
50 }
51 } gs_enableLeakChecks;
52 #endif // __WXMSW__ && __WXDEBUG__
53
54 // ----------------------------------------------------------------------------
55 // private classes
56 // ----------------------------------------------------------------------------
57
58 // we need a dummy app object if the user doesn't want to create a real one
59 class wxDummyConsoleApp : public wxAppConsole
60 {
61 public:
62 wxDummyConsoleApp() { }
63
64 virtual int OnRun() { wxFAIL_MSG( _T("unreachable code") ); return 0; }
65
66 DECLARE_NO_COPY_CLASS(wxDummyConsoleApp)
67 };
68
69 // we need a special kind of auto pointer to wxApp which not only deletes the
70 // pointer it holds in its dtor but also resets the global application pointer
71 wxDECLARE_SCOPED_PTR(wxAppConsole, wxAppPtrBase);
72 wxDEFINE_SCOPED_PTR(wxAppConsole, wxAppPtrBase);
73
74 class wxAppPtr : public wxAppPtrBase
75 {
76 public:
77 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
78 ~wxAppPtr()
79 {
80 if ( get() )
81 {
82 // the pointer is going to be deleted in the base class dtor, don't
83 // leave the dangling pointer!
84 wxApp::SetInstance(NULL);
85 }
86 }
87
88 void Set(wxAppConsole *ptr)
89 {
90 reset(ptr);
91
92 wxApp::SetInstance(ptr);
93 }
94
95 DECLARE_NO_COPY_CLASS(wxAppPtr)
96 };
97
98 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
99 // fails
100 class wxCallAppCleanup
101 {
102 public:
103 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
104 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
105
106 void Dismiss() { m_app = NULL; }
107
108 private:
109 wxAppConsole *m_app;
110 };
111
112 // another tiny class which simply exists to ensure that wxEntryCleanup is
113 // always called
114 class wxCleanupOnExit
115 {
116 public:
117 ~wxCleanupOnExit() { wxEntryCleanup(); }
118 };
119
120 // ----------------------------------------------------------------------------
121 // private functions
122 // ----------------------------------------------------------------------------
123
124 // suppress warnings about unused variables
125 static inline void Use(void *) { }
126
127 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
128
129 // ----------------------------------------------------------------------------
130 // initialization data
131 // ----------------------------------------------------------------------------
132
133 static struct InitData
134 {
135 InitData()
136 {
137 nInitCount = 0;
138
139 #if wxUSE_UNICODE
140 argc = 0;
141 // argv = NULL; -- not even really needed
142 #endif // wxUSE_UNICODE
143 }
144
145 // critical section protecting this struct
146 wxCRIT_SECT_DECLARE_MEMBER(csInit);
147
148 // number of times wxInitialize() was called minus the number of times
149 // wxUninitialize() was
150 size_t nInitCount;
151
152 #if wxUSE_UNICODE
153 int argc;
154
155 // if we receive the command line arguments as ASCII and have to convert
156 // them to Unicode ourselves (this is the case under Unix but not Windows,
157 // for example), we remember the converted argv here because we'll have to
158 // free it when doing cleanup to avoid memory leaks
159 wchar_t **argv;
160 #endif // wxUSE_UNICODE
161
162 DECLARE_NO_COPY_CLASS(InitData)
163 } gs_initData;
164
165 // ============================================================================
166 // implementation
167 // ============================================================================
168
169 // ----------------------------------------------------------------------------
170 // command line arguments ANSI -> Unicode conversion
171 // ----------------------------------------------------------------------------
172
173 #if wxUSE_UNICODE
174
175 static void ConvertArgsToUnicode(int argc, char **argv)
176 {
177 gs_initData.argv = new wchar_t *[argc + 1];
178 for ( int i = 0; i < argc; i++ )
179 {
180 gs_initData.argv[i] = wxStrdup(wxConvLocal.cMB2WX(argv[i]));
181 }
182
183 gs_initData.argv[argc] = NULL;
184 }
185
186 static void FreeConvertedArgs()
187 {
188 if ( gs_initData.argv )
189 {
190 for ( int i = 0; i < gs_initData.argc; i++ )
191 {
192 free(gs_initData.argv[i]);
193 }
194
195 delete [] gs_initData.argv;
196 gs_initData.argv = NULL;
197 }
198 }
199
200 #endif // wxUSE_UNICODE
201
202 // ----------------------------------------------------------------------------
203 // start up
204 // ----------------------------------------------------------------------------
205
206 // initialization which is always done (not customizable) before wxApp creation
207 static bool DoCommonPreInit()
208 {
209 wxClassInfo::InitializeClasses();
210
211 return true;
212 }
213
214 // non customizable initialization done after wxApp creation and initialization
215 static bool DoCommonPostInit()
216 {
217 wxModule::RegisterModules();
218
219 return wxModule::InitializeModules();
220 }
221
222 bool wxEntryStart(int& argc, wxChar **argv)
223 {
224 // do minimal, always necessary, initialization
225 // --------------------------------------------
226
227 // initialize wxRTTI
228 if ( !DoCommonPreInit() )
229 {
230 return false;
231 }
232
233
234 // first of all, we need an application object
235 // -------------------------------------------
236
237 // the user might have already created it himself somehow
238 wxAppPtr app(wxTheApp);
239 if ( !app.get() )
240 {
241 // if not, he might have used IMPLEMENT_APP() to give us a function to
242 // create it
243 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
244
245 if ( fnCreate )
246 {
247 // he did, try to create the custom wxApp object
248 app.Set((*fnCreate)());
249 }
250 }
251
252 if ( !app.get() )
253 {
254 // either IMPLEMENT_APP() was not used at all or it failed -- in any
255 // case we still need something
256 app.Set(new wxDummyConsoleApp);
257 }
258
259
260 // wxApp initialization: this can be customized
261 // --------------------------------------------
262
263 if ( !app->Initialize(argc, argv) )
264 {
265 return false;
266 }
267
268 wxCallAppCleanup callAppCleanup(app.get());
269
270 // for compatibility call the old initialization function too
271 if ( !app->OnInitGui() )
272 return false;
273
274
275 // common initialization after wxTheApp creation
276 // ---------------------------------------------
277
278 if ( !DoCommonPostInit() )
279 return false;
280
281
282 // prevent the smart pointer from destroying its contents
283 app.release();
284
285 // and the cleanup object from doing cleanup
286 callAppCleanup.Dismiss();
287
288 return true;
289 }
290
291 #if wxUSE_UNICODE
292
293 // we provide a wxEntryStart() wrapper taking "char *" pointer too
294 bool wxEntryStart(int& argc, char **argv)
295 {
296 ConvertArgsToUnicode(argc, argv);
297
298 if ( !wxEntryStart(argc, gs_initData.argv) )
299 {
300 FreeConvertedArgs();
301
302 return false;
303 }
304
305 return true;
306 }
307
308 #endif // wxUSE_UNICODE
309
310 // ----------------------------------------------------------------------------
311 // clean up
312 // ----------------------------------------------------------------------------
313
314 // cleanup done before destroying wxTheApp
315 static void DoCommonPreCleanup()
316 {
317 #if wxUSE_LOG
318 // flush the logged messages if any and install a 'safer' log target: the
319 // default one (wxLogGui) can't be used after the resources are freed just
320 // below and the user supplied one might be even more unsafe (using any
321 // wxWindows GUI function is unsafe starting from now)
322 wxLog::DontCreateOnDemand();
323
324 // this will flush the old messages if any
325 delete wxLog::SetActiveTarget(new wxLogStderr);
326 #endif // wxUSE_LOG
327
328 wxModule::CleanUpModules();
329 }
330
331 // cleanup done after destroying wxTheApp
332 static void DoCommonPostCleanup()
333 {
334 wxClassInfo::CleanUpClasses();
335
336 // we can't do this in wxApp itself because it doesn't know if argv had
337 // been allocated
338 #if wxUSE_UNICODE
339 FreeConvertedArgs();
340 #endif // wxUSE_UNICODE
341
342 // check for memory leaks
343 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
344 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
345 {
346 wxLogDebug(wxT("There were memory leaks.\n"));
347 wxDebugContext::Dump();
348 wxDebugContext::PrintStatistics();
349 }
350 #endif // Debug
351
352 #if wxUSE_LOG
353 // and now delete the last logger as well
354 delete wxLog::SetActiveTarget(NULL);
355 #endif // wxUSE_LOG
356 }
357
358 void wxEntryCleanup()
359 {
360 DoCommonPreCleanup();
361
362
363 // delete the application object
364 if ( wxTheApp )
365 {
366 wxTheApp->CleanUp();
367
368 delete wxTheApp;
369 wxApp::SetInstance(NULL);
370 }
371
372
373 DoCommonPostCleanup();
374 }
375
376 // ----------------------------------------------------------------------------
377 // wxEntry
378 // ----------------------------------------------------------------------------
379
380 #if !defined(__WXMSW__) || !wxUSE_ON_FATAL_EXCEPTION
381 #define wxEntryReal wxEntry
382 #endif // !(__WXMSW__ && wxUSE_ON_FATAL_EXCEPTION)
383
384 int wxEntryReal(int& argc, wxChar **argv)
385 {
386 // library initialization
387 if ( !wxEntryStart(argc, argv) )
388 {
389 return -1;
390 }
391
392 // if wxEntryStart succeeded, we must call wxEntryCleanup even if the code
393 // below returns or throws
394 wxCleanupOnExit cleanupOnExit;
395
396 WX_SUPPRESS_UNUSED_WARN(cleanupOnExit);
397
398 // app initialization
399 if ( !wxTheApp->CallOnInit() )
400 {
401 // don't call OnExit() if OnInit() failed
402 return -1;
403 }
404
405 // app execution
406 int retValue = wxTheApp->OnRun();
407
408 // app clean up
409 wxTheApp->OnExit();
410
411 return retValue;
412 }
413
414 // wrap real wxEntry in a try-except block to be able to call
415 // OnFatalException() if necessary
416 #if defined(__WXMSW__) && wxUSE_ON_FATAL_EXCEPTION
417
418 #ifdef __WXWINCE__
419 // For ExitThread
420 #include "wx/msw/private.h"
421 #endif
422
423 extern unsigned long wxGlobalSEHandler(EXCEPTION_POINTERS *pExcPtrs);
424
425 int wxEntry(int& argc, wxChar **argv)
426 {
427 __try
428 {
429 return wxEntryReal(argc, argv);
430 }
431 __except ( wxGlobalSEHandler(GetExceptionInformation()) )
432 {
433 #ifdef __WXWINCE__
434 ::ExitThread(3); // the same exit code as abort()
435 #else
436 ::ExitProcess(3); // the same exit code as abort()
437 #endif
438
439 #if !defined(_MSC_VER) || _MSC_VER < 1300
440 // this code is unreachable but put it here to suppress warnings
441 // from some compilers
442 return -1;
443 #endif
444 }
445 }
446
447 #endif // __WXMSW__ && wxUSE_ON_FATAL_EXCEPTION
448
449 #if wxUSE_UNICODE
450
451 // as with wxEntryStart, we provide an ANSI wrapper
452 int wxEntry(int& argc, char **argv)
453 {
454 ConvertArgsToUnicode(argc, argv);
455
456 return wxEntry(argc, gs_initData.argv);
457 }
458
459 #endif // wxUSE_UNICODE
460
461 // ----------------------------------------------------------------------------
462 // wxInitialize/wxUninitialize
463 // ----------------------------------------------------------------------------
464
465 bool wxInitialize(int argc, wxChar **argv)
466 {
467 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
468
469 if ( gs_initData.nInitCount++ )
470 {
471 // already initialized
472 return true;
473 }
474
475 return wxEntryStart(argc, argv);
476 }
477
478 void wxUninitialize()
479 {
480 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
481
482 if ( !--gs_initData.nInitCount )
483 {
484 wxEntryCleanup();
485 }
486 }
487