Application Bootstrap Lifecycle
Overview
The process starts in Telegram/…/main.cpp. main() disables OpenSSL's atexit cleanup with OPENSSL_init_crypto(OPENSSL_INIT_NO_ATEXIT, nullptr) so detached worker tasks cannot crash after OpenSSL globals are freed, then creates the singleton Core::Launcher via Core::Launcher::Create(argc, argv) and returns launcher->exec().
Telegram/SourceFiles/core/launcher.* owns the pre-Qt-application bootstrap. Core::Launcher records the original arguments and initial working directory, installs Core::BaseIntegration into base::Integration, parses top-level switches such as -debug, -testagent, -autostart, -cleanup, -noupdate, -workdir, -scale, and start URLs, and exposes process-wide identity through Launcher::Instance(), installationTag(), and instanceHash(). Launcher::Create() returns the platform subclass selected by Telegram/…/platform_launcher.h: platform/win/launcher_win.*, platform/mac/launcher_mac.*, or platform/linux/launcher_linux.*.
Core::Launcher::exec() is the ordered startup spine in Telegram/…/launcher.cpp: it prepares executable paths and parsed settings, installs Qt message logging, sets the application name, handles -fixprevious, checks macOS app translocation through Platform::CheckAppTranslocation(), starts logging with Logs::start(), loads experimental options from tdata/experimental_options.json, applies high-DPI policy, installs FFmpeg logging, starts platform and third-party integration with Platform::start() / ThirdParty::start(), and then calls executeApplication(). executeApplication() constructs the Core::Sandbox QApplication, Ui::MainQueueProcessor, and base::ConcurrentTimerEnvironment; the actual event loop and application object are then owned by Core::Sandbox.
Logging is intentionally available before the full application exists. Telegram/SourceFiles/logs.* buffers log entries in memory until the working directory is finalized, then Logs::start() selects the portable or app-data working directory, applies a custom -workdir, creates tdata, calls Launcher::workingFolderReady(), starts crash catching, and opens a temporary log_startN.txt. After single-instance checks, Logs::instanceChecked() renames the start log to log.txt and flushes deferred debug/MTP logs. Debug logs are written under DebugLogs/ in 15-minute slices and only when Logs::DebugEnabled() is true. Telegram/SourceFiles/core/base_integration.* routes base-library logging, assertions, event-loop entry, and crash annotations into Logs, Core::Sandbox, and CrashReports.
Crash handling is split between early catching and per-launch reports in Telegram/SourceFiles/core/crash_reports.*. CrashReports::StartCatching() installs Breakpad/Crashpad and records annotations such as binary name, API id, version, platform, and Launcher::installationTag(). CrashReports::Start() reads tdata/working; if a previous run left a non-empty crash dump, Core::Sandbox shows a crash-report window before calling launchApplication(). CrashReports::Restart() opens the new tdata/working marker and installs signal/new-handler/Qt-fatal handlers. A clean shutdown calls CrashReports::Finish(), closes the marker, and removes it.
The QApplication boundary is in Core::Sandbox (directly constructed from Core::Launcher::executeApplication() even though its files are outside this doc's owned globs). Its startup performs cleanup-mode handling, creates the UpdateChecker, sets up single-instance IPC/locking, connects aboutToQuit, and enters exec(). Once the instance is accepted and crash reporting is ready, Sandbox::launchApplication() creates Core::Application and calls Application::run().
Telegram/SourceFiles/core/application.* owns the global runtime object exposed by Core::App() and guarded by Core::IsAppLaunched(). Its constructor creates long-lived services in dependency order: platform integration (Platform::Integration::Create() from Telegram/SourceFiles/platform/platform_integration.*), battery saving, WebRTC environment, screenshot protection, storage databases, animation manager, audio, fallback MTP config, download manager, Main::Domain, export/calls/Instant View managers, langpack/cloud manager, emoji keywords, tray, UI integration, and proxy rotation. Application::run() creates notifications after ThirdParty::start(), starts local storage/settings, applies startup overrides and scale, refreshes global proxy, handles new-version URL-scheme registration, initializes UI/style/accessibility/emoji/media/storage helpers, creates Window::SavedWindows, then creates the first Window::Controller and makes it the active primary window.
The top-level window handoff is: Application::run() creates a Window::Controller; that controller owns a MainWindow (Telegram/SourceFiles/mainwindow.*) whose platform base is selected by Telegram/…/platform_main_window.h; MainWindow::setupIntro() or MainWindow::setupMain() installs either the intro widget or a MainWidget (Telegram/SourceFiles/mainwidget.*) into the body. MainWindow::finishFirstShow() applies saved work mode/window state, creates global menus, and focuses either the main session widget or intro. MainWidget then owns the session-level UI: dialogs, history, player/call/export top bars, adaptive layout, and chat-section transitions.
Updates are integrated at two points. Telegram/SourceFiles/core/update_checker.* supplies a process-wide UpdateChecker shared by Application and Sandbox; once an active session appears, Application passes it to UpdateChecker().setMtproto(session). Downloaded packages are verified/unpacked into tupdates/temp, with v1 RSA/SHA1 compatibility and v2 manifest/envelope verification from Telegram/SourceFiles/core/update_verify.*; Telegram/SourceFiles/core/update_keys.* provides embedded update trust material and Telegram/…/update_channel.h carries the build channel. On normal exit from Launcher::exec(), if cRestartingUpdate() is set and updates are enabled, launchUpdater(PerformUpdate) is called; if cRestarting() is set, launchUpdater(JustRelaunch) is called.
Shutdown flows back through the same ownership layers. Core::Quit() in core/application.cpp first asks Application::preventsQuit() to stop export/upload/download/media/platform-sensitive exits, marks launch state as QuitRequested, and asks Sandbox::QuitWhenStarted() to exit the event loop when ready. Sandbox::aboutToQuit destroys _application, which runs Application::~Application() to write saved windows/settings, clear windows/media/notifications, finish the domain, shut down local storage/shortcuts/emoji/media/theme/player/style, and finally clear Application::Instance. Control returns to Launcher::exec(), which may spawn updater/relaunch, then calls CrashReports::Finish(), ThirdParty::finish(), Platform::finish(), and Logs::finish().
Telegram/…/stdafx.h is the precompiled include surface for this area. It pulls in Qt, base/rpl/crl, common UI/style/data types, logs.h, and config.h; changes there can silently affect all startup translation units because it is included broadly rather than through local includes.
Coupling
- If
Core::Launcher::exec()ordering in Telegram/…/launcher.cpp changes, verify Telegram/…/logs.cpp, Telegram/…/crash_reports.cpp, and platform startup still see a valid working directory.Logs::start()choosescWorkingDir(), callsLauncher::workingFolderReady(), and starts crash catching beforePlatform::start()and before theQApplicationis constructed. - If command-line parsing changes in Telegram/…/launcher.cpp, update relaunch/updater argument forwarding in Telegram/…/launcher_win.cpp,
Telegram/SourceFiles/platform/mac/launcher_mac.mm, and Telegram/…/launcher_linux.cpp. The relaunch paths reconstruct only selected flags (-debug,-autostart,-startintray,-key,-workdir,-tosettings,-noupdate), so new startup state will be lost unless it is forwarded explicitly. - If logging or assertion integration changes in
Telegram/SourceFiles/core/base_integration.*, verifyCore::Sandbox::customEnterFromEventLoop,Logs::writeMain/writeDebug, andCrashReports::SetAnnotationstill work beforeCore::Applicationexists. Base assertions can fire during bootstrap, so this bridge cannot depend onCore::App(). - If Telegram/…/application.cpp adds services to
Application, place them with destructor order in mind. The header explicitly notes that notifications are destroyed before audio and after the domain, and the destructor manually clears windows beforeMain::Domain::finish()because native window destruction can enter the event loop. - If update verification policy changes in
Telegram/SourceFiles/core/update_verify.*, also check Telegram/…/update_checker.cpp and platformlaunchUpdater()implementations.UpdateCheckerwrites ready updates undertupdates/temp, whileLauncher::exec()decides whether and how to spawn the updater after the event loop exits. - If
MainWindowsetup changes in Telegram/…/mainwindow.cpp, verifyCore::Application::run()still callsfirstShow(),finishFirstShow(),startMediaView(), andprocessCreatedWindow()in a safe order. Start URLs and passcode/setup-email locks are delivered throughMainWindow::setupMain(),clearPasscodeLock(), andApplication::checkStartUrls().
Risks
- Telegram/…/launcher.cpp and Telegram/…/main.cpp: OpenSSL cleanup is deliberately disabled at process start because OpenSSL's atexit handler can free globals while detached workers are still inside OpenSSL. Reintroducing OpenSSL atexit cleanup can turn ordinary quit/restart into worker-thread crashes.
- Telegram/…/logs.cpp and Telegram/…/crash_reports.cpp: crash reporting depends on
cWorkingDir()andtdata/workingbeing established byLogs::start()beforeCrashReports::Start()is evaluated. Moving crash startup earlier can write reports to the wrong place or miss the previous-run crash prompt. - Telegram/…/application.cpp:
Application::~Application()clears windows before finishing the domain because native window destruction, especially WindowsDestroyWindowwith WebView, can enter the event loop and run queued main-thread callbacks. If windows survive until after_domain->finish(), callbacks can observe a stopped domain and trip lifecycle assertions. - Telegram/…/launcher_win.cpp,
Telegram/SourceFiles/platform/mac/launcher_mac.mm, and Telegram/…/launcher_linux.cpp: all relaunch/update paths callLogs::closeMain()andCrashReports::Finish()before spawning. If a new spawn path omits this, the old process can leavetdata/workingbehind and make the next launch look like a crash.