### Bug Summary

File: | builds/wireshark/wireshark/ui/qt/main_application.cpp
Warning: | line 482, column 13 Potential memory leak

### Annotated Source Code

Press '?' to see keyboard shortcuts

Show analyzer invocation
clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name main_application.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -fno-delete-null-pointer-checks -mframe-pointer=all -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -ffloat16-excess-precision=fast -fbfloat16-excess-precision=fast -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/builds/wireshark/wireshark/build -fcoverage-compilation-dir=/builds/wireshark/wireshark/build -resource-dir /usr/lib/llvm-22/lib/clang/22 -isystem /usr/include/glib-2.0 -isystem /usr/lib/x86_64-linux-gnu/glib-2.0/include -isystem /builds/wireshark/wireshark/build/ui/qt -isystem /builds/wireshark/wireshark/ui/qt -isystem /builds/wireshark/wireshark/ui/qt/lua_debugger -isystem /usr/include/x86_64-linux-gnu/qt6/QtConcurrent -isystem /usr/include/x86_64-linux-gnu/qt6 -isystem /usr/include/x86_64-linux-gnu/qt6/QtCore -isystem /usr/lib/x86_64-linux-gnu/qt6/mkspecs/linux-g++ -isystem /usr/include/x86_64-linux-gnu/qt6/QtNetwork -isystem /usr/include/x86_64-linux-gnu/qt6/QtPrintSupport -isystem /usr/include/x86_64-linux-gnu/qt6/QtGui -isystem /usr/include/x86_64-linux-gnu/qt6/QtWidgets -isystem /usr/include/x86_64-linux-gnu/qt6/QtSvg -isystem /usr/include/x86_64-linux-gnu/qt6/QtMultimedia -isystem /usr/include/x86_64-linux-gnu/qt6/QtDBus -D CARES_NO_DEPRECATED -D G_DISABLE_DEPRECATED -D G_DISABLE_SINGLE_INCLUDES -D QT_CONCURRENT_LIB -D QT_CORE_LIB -D QT_DBUS_LIB -D QT_GUI_LIB -D QT_MULTIMEDIA_LIB -D QT_NETWORK_LIB -D QT_PRINTSUPPORT_LIB -D QT_SVG_LIB -D QT_WIDGETS_LIB -D WS_DEBUG -D WS_DEBUG_UTF_8 -I /builds/wireshark/wireshark/build/ui/qt/qtui_autogen/include -I /builds/wireshark/wireshark/build -I /builds/wireshark/wireshark -I /builds/wireshark/wireshark/include -D _GLIBCXX_ASSERTIONS -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-22/lib/clang/22/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/builds/wireshark/wireshark/= -fmacro-prefix-map=/builds/wireshark/wireshark/build/= -fmacro-prefix-map=../= -Wno-format-nonliteral -std=c++17 -fdeprecated-macro -ferror-limit 19 -fwrapv -fwrapv-pointer -fstrict-flex-arrays=3 -stack-protector 2 -fstack-clash-protection -fcf-protection=full -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions -fexceptions -fcolor-diagnostics -analyzer-output=html -faddrsig -fdwarf2-cfi-asm -o /builds/wireshark/wireshark/sbout/2026-09-06-100407-3660-1 -x c++ /builds/wireshark/wireshark/ui/qt/main_application.cpp

Keyboard shortcuts:

- Use 'j/k' keys for keyboard navigation
- Use 'Shift+S' to show/hide relevant lines
- Use '?' to toggle this window

Close
Show only relevant lines Show control flow arrows

1 | /* main_application.cpp
2 | *
3 | * Wireshark - Network traffic analyzer
4 | * By Gerald Combs <gerald@wireshark.org>
5 | * Copyright 1998 Gerald Combs
6 | *
7 | * SPDX-License-Identifier: GPL-2.0-or-later
8 | */
9 |
10 | // warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data
11 | #ifdef _MSC_VER
12 | #pragma warning(push)
13 | #pragma warning(disable : 4267)
14 | #endif
15 |
16 | #define WS_LOG_DOMAIN"Main" LOG_DOMAIN_MAIN"Main"
17 |
18 | #include "main_application.h"
19 |
20 | #include <algorithm>
21 | #include <errno(*__errno_location ()).h>
22 |
23 | #include "wsutil/filesystem.h"
24 | #include "app/application_flavor.h"
25 |
26 | #include "epan/addr_resolv.h"
27 | #include "epan/column-utils.h"
28 | #include "epan/disabled_protos.h"
29 | #include "epan/ftypes/ftypes.h"
30 | #include "epan/prefs.h"
31 | #include "epan/proto.h"
32 | #include "epan/tap.h"
33 | #include "epan/timestamp.h"
34 | #include "epan/decode_as.h"
35 | #include "epan/dfilter/dfilter-macro.h"
36 |
37 | #include "ui/commandline.h"
38 | #include "ui/decode_as_utils.h"
39 | #include "ui/preference_utils.h"
40 | #include "ui/language.h"
41 | #include "ui/recent.h"
42 | #include "ui/simple_dialog.h"
43 | #include "ui/util.h"
44 |
45 | #include <ui/qt/utils/qt_ui_utils.h>
46 | #include <ui/qt/utils/color_utils.h>
47 | #include <ui/qt/utils/software_update.h>
48 | #include <ui/qt/utils/theme_manager.h>
49 | #include "coloring_rules_dialog.h"
50 |
51 | #include "epan/color_filters.h"
52 |
53 | #include "extcap.h"
54 | #ifdef HAVE_LIBPCAP1
55 | #include <capture/iface_monitor.h>
56 | #endif
57 |
58 | #include "wsutil/filter_files.h"
59 | #include "ui/capture_globals.h"
60 | #include "ui/file_dialog.h"
61 | #include "ui/recent_utils.h"
62 |
63 | #ifdef HAVE_LIBPCAP1
64 | #include "ui/capture.h"
65 | #endif
66 |
67 | #include "wsutil/utf8_entities.h"
68 |
69 | #ifdef _WIN32
70 | # include "wsutil/file_util.h"
71 | # include <QMessageBox>
72 | # include <QSettings>
73 | #endif /* _WIN32 */
74 |
75 | #include <ui/qt/capture_file.h>
76 |
77 | #include <ui/qt/main_window.h>
78 | #include <ui/qt/manager/interface_list_manager.h>
79 | #include <ui/qt/main_status_bar.h>
80 | #include <ui/qt/utils/workspace_state.h>
81 | #include <ui/qt/utils/theme_styler.h>
82 |
83 | #include <QAction>
84 | #include <QApplication>
85 | #include <QColorDialog>
86 | #include <QDesktopServices>
87 | #include <QDir>
88 | #include <QEvent>
89 | #include <QFileOpenEvent>
90 | #include <QFontInfo>
91 | #include <QFontMetrics>
92 | #include <QLibraryInfo>
93 | #include <QLocale>
94 | #include <QMainWindow>
95 | #include <QMutableListIterator>
96 | #include <QProxyStyle>
97 | #include <QSocketNotifier>
98 | #include <QThreadPool>
99 | #include <QUrl>
100 | #include <qmath.h>
101 |
102 | #include <QMimeDatabase>
103 |
104 | #include <QStyleHints>
105 |
106 | #if QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 5, 0)((6<<16)|(5<<8)|(0)) && defined(Q_OS_WIN)
107 | #include <QStyleFactory>
108 | #endif
109 |
110 | #ifdef _MSC_VER
111 | #pragma warning(pop)
112 | #endif
113 |
114 | MainApplication *mainApp;
115 |
116 | // XXX - Copied from ui/gtk/file_dlg.c
117 |
118 | static QHash<int, QList<QAction *> > dynamic_menu_groups_;
119 | static QHash<int, QList<QAction *> > added_menu_groups_;
120 | static QHash<int, QList<QAction *> > removed_menu_groups_;
121 |
122 | QString MainApplication::window_title_separator_ = QString::fromUtf8(" " UTF8_MIDDLE_DOT"\u00b7" " ");
123 |
124 | // QMimeDatabase parses a large-ish XML file and can be slow to initialize.
125 | // Do so in a worker thread as early as possible.
126 | // https://github.com/lxde/pcmanfm-qt/issues/415
127 | class MimeDatabaseInitThread : public QRunnable
128 | {
129 | private:
130 | void run() override
131 | {
132 | QMimeDatabase mime_db;
133 | mime_db.mimeTypeForData(QByteArray());
134 | }
135 | };
136 |
137 | void
138 | topic_action(topic_action_e action)
139 | {
140 | if (mainApp) mainApp->helpTopicAction(action);
141 | }
142 |
143 | /* write all capture filenames of the menu to the user's recent file */
144 | extern "C" void menu_recent_file_write_all(FILE *rf) {
145 |
146 | const QList<RecentFileInfo>& recentFiles = WorkspaceState::instance()->recentCaptureFiles();
147 | int rFSize = static_cast<int>(recentFiles.size());
148 | for (int i = 0; i < rFSize; i++) {
149 | const RecentFileInfo& rfi = recentFiles.at(i);
150 |
151 | QString cf_name = rfi.filename;
152 | if (!cf_name.isNull()) {
153 | fprintf (rf, RECENT_KEY_CAPTURE_FILE"recent.capture_file" ": %s\n", qUtf8Printable(cf_name)QtPrivate::asString(cf_name).toUtf8().constData());
154 | }
155 | }
156 | }
157 |
158 | void MainApplication::refreshPacketData()
159 | {
160 | if (host_name_lookup_process()) {
161 | emit addressResolutionChanged();
162 | } else if (col_data_changed()) {
163 | emit columnDataChanged();
164 | }
165 | }
166 |
167 | void MainApplication::updateTaps()
168 | {
169 | draw_tap_listeners(false);
170 | }
171 |
172 | QDir MainApplication::openDialogInitialDir() {
173 | return QDir(get_open_dialog_initial_dir());
174 | }
175 |
176 | void MainApplication::setLastOpenDirFromFilename(const QString file_name)
177 | {
178 | /* XXX - Use canonicalPath() instead of absolutePath()? */
179 | QString directory = QDir::toNativeSeparators(QFileInfo(file_name).absolutePath());
180 | /* XXX - printable? */
181 | set_last_open_dir(qUtf8Printable(directory)QtPrivate::asString(directory).toUtf8().constData());
182 | }
183 |
184 | void MainApplication::helpTopicAction(topic_action_e action)
185 | {
186 | QString url = gchar_free_to_qstring(topic_action_url(action));
187 |
188 | if (!url.isEmpty()) {
189 | QDesktopServices::openUrl(QUrl(QDir::fromNativeSeparators(url)));
190 | }
191 | }
192 |
193 | void MainApplication::setConfigurationProfile(const char *profile_name, bool write_recent_file)
194 | {
195 | char *rf_path;
196 | int rf_open_errno;
197 | char *err_msg = NULL__null;
198 | const char* env_prefix = application_configuration_environment_prefix();
199 |
200 | /* First check if profile exists */
201 | if (!profile_exists(env_prefix, profile_name, false)) {
202 | if (profile_exists(env_prefix, profile_name, true)) {
203 | char *pf_dir_path, *pf_dir_path2, *pf_filename;
204 | /* Copy from global profile */
205 | if (create_persconffile_profile(env_prefix, profile_name, &pf_dir_path) == -1) {
206 | simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
207 | "Can't create directory\n\"%s\":\n%s.",
208 | pf_dir_path, g_strerror(errno(*__errno_location ())));
209 |
210 | g_free(pf_dir_path)(__builtin_object_size ((pf_dir_path), 0) != ((size_t) - 1)) ? g_free_sized (pf_dir_path, __builtin_object_size ((pf_dir_path ), 0)) : (g_free) (pf_dir_path);
211 | }
212 |
213 | if (copy_persconffile_profile(env_prefix, profile_name, profile_name, true, &pf_filename,
214 | &pf_dir_path, &pf_dir_path2) == -1) {
215 | simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
216 | "Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
217 | pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno(*__errno_location ())));
218 |
219 | g_free(pf_filename)(__builtin_object_size ((pf_filename), 0) != ((size_t) - 1)) ? g_free_sized (pf_filename, __builtin_object_size ((pf_filename ), 0)) : (g_free) (pf_filename);
220 | g_free(pf_dir_path)(__builtin_object_size ((pf_dir_path), 0) != ((size_t) - 1)) ? g_free_sized (pf_dir_path, __builtin_object_size ((pf_dir_path ), 0)) : (g_free) (pf_dir_path);
221 | g_free(pf_dir_path2)(__builtin_object_size ((pf_dir_path2), 0) != ((size_t) - 1)) ? g_free_sized (pf_dir_path2, __builtin_object_size ((pf_dir_path2 ), 0)) : (g_free) (pf_dir_path2);
222 | }
223 | } else {
224 | /* No personal and no global profile exists */
225 | return;
226 | }
227 | }
228 |
229 | /* Then check if changing to another profile */
230 | if (profile_name && strcmp (profile_name, get_profile_name()) == 0) {
231 | return;
232 | }
233 |
234 | /* Get the current geometry, before writing it to disk */
235 | emit profileChanging();
236 |
237 | if (write_recent_file && profile_exists(env_prefix, get_profile_name(), false))
238 | {
239 | /* Write recent file for profile we are leaving, if it still exists */
240 | write_profile_recent();
241 | }
242 |
243 | // Freeze the packet list early to avoid updating column data before doing a
244 | // full redissection. The packet list will be thawed when redissection is done.
245 | emit freezePacketList(true);
246 |
247 | /* Set profile name and update the status bar */
248 | set_profile_name (profile_name);
249 | emit profileNameChanged(profile_name);
250 |
251 | /* Apply new preferences */
252 | readConfigurationFiles(true);
253 |
254 | /* Reading the new profile's preferences reset every registered preference,
255 | * including the ones that are shared by all of our profiles. Those aren't
256 | * part of the profile we're leaving, so read them back in. */
257 | extcap_read_preferences();
258 |
259 | /* Apply command-line preferences */
260 | commandline_options_reapply();
261 | extcap_register_preferences(NULL__null, NULL__null);
262 |
263 | /* Switching profile requires reloading the macro list. */
264 | reloadDisplayFilterMacros();
265 |
266 | if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
267 | simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK0x01,
268 | "Could not open common recent file\n\"%s\": %s.",
269 | rf_path, g_strerror(rf_open_errno));
270 | g_free(rf_path)(__builtin_object_size ((rf_path), 0) != ((size_t) - 1)) ? g_free_sized (rf_path, __builtin_object_size ((rf_path), 0)) : (g_free) ( rf_path);
271 | }
272 | if (recent.gui_fileopen_remembered_dir &&
273 | test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR21) {
274 | set_last_open_dir(recent.gui_fileopen_remembered_dir);
275 | }
276 | timestamp_set_type(recent.gui_time_format);
277 | timestamp_set_precision(recent.gui_time_precision);
278 | timestamp_set_seconds_type (recent.gui_seconds_format);
279 |
280 | prefs_to_capture_opts(&global_capture_opts);
281 | prefs_apply_all();
282 | #ifdef HAVE_LIBPCAP1
283 | /* Re-apply interface display attributes from the new profile's prefs before
284 | the preferencesChanged() emit below, so its listeners see fresh data. The
285 | manager owns interface enumeration/attributes now. */
286 | if (MainWindow *mw = mainWindow())
287 | if (InterfaceListManager *mgr = mw->interfaceListManager())
288 | mgr->reapplyInterfacePreferences();
289 | #endif
290 |
291 | emit columnsChanged();
292 | emit preferencesChanged();
293 | emit recentPreferencesRead();
294 | emit filterExpressionsChanged();
295 | emit checkDisplayFilter();
296 | emit captureFilterListChanged();
297 | emit displayFilterListChanged();
298 |
299 | /* Reload color filters */
300 | if (!color_filters_reload(&err_msg, color_filter_add_cb, application_configuration_environment_prefix())) {
301 | simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01, "%s", err_msg);
302 | g_free(err_msg)(__builtin_object_size ((err_msg), 0) != ((size_t) - 1)) ? g_free_sized (err_msg, __builtin_object_size ((err_msg), 0)) : (g_free) ( err_msg);
303 | }
304 |
305 | /* Capture-interface prefs are now watched by InterfaceListManager, which
306 | rescans when capture_no_interface_load / capture_no_extcap flips. A profile
307 | switch can also change interface display attributes, so notify subscribers
308 | (the manager owns the interface-list-changed signal now). */
309 | MainWindow *mw = mainWindow();
310 | if (mw && mw->interfaceListManager())
311 | mw->interfaceListManager()->notifyListChanged();
312 | emit packetDissectionChanged();
313 |
314 | /* Write recent_common file to ensure last used profile setting is stored. */
315 | write_recent();
316 | }
317 |
318 | void MainApplication::reloadLuaPluginsDelayed()
319 | {
320 | QTimer::singleShot(0, this, [this]() {
321 | /* Clear the reloading flag so the re-triggered reload
322 | * is not blocked by the isReloadingLua() guard. */
323 | setReloadingLua(false);
324 | emit reloadLuaPlugins();
325 | });
326 | }
327 |
328 | const QIcon &MainApplication::normalIcon()
329 | {
330 | if (normal_icon_.isNull()) {
331 | initializeIcons();
332 | }
333 | return normal_icon_;
334 | }
335 |
336 | const QIcon &MainApplication::captureIcon()
337 | {
338 | if (capture_icon_.isNull()) {
339 | initializeIcons();
340 | }
341 | return capture_icon_;
342 | }
343 |
344 | const QString MainApplication::windowTitleString(QStringList title_parts)
345 | {
346 | QMutableStringListIterator tii(title_parts);
347 | while (tii.hasNext()) {
348 | QString ti = tii.next();
349 | if (ti.isEmpty()) tii.remove();
350 | }
351 | title_parts.prepend(applicationName());
352 | return title_parts.join(window_title_separator_);
353 | }
354 |
355 | void MainApplication::applyCustomColorsFromRecent()
356 | {
357 | int i = 0;
358 | bool ok;
359 | for (GList *custom_color = recent.custom_colors; custom_color; custom_color = custom_color->next) {
360 | QRgb rgb = QString((const char *)custom_color->data).toUInt(&ok, 16);
361 | if (ok) {
362 | QColorDialog::setCustomColor(i++, QColor(rgb));
363 | }
364 | }
365 | }
366 |
367 | // Return the first top-level MainWindow.
368 | MainWindow *MainApplication::mainWindow()
369 | {
370 | foreach (QWidget *tlw, topLevelWidgets())for (auto _container_370 = QtPrivate::qMakeForeachContainer(topLevelWidgets ()); _container_370.i != _container_370.e; ++_container_370.i ) if (QWidget *tlw = *_container_370.i; false) {} else {
371 | MainWindow *tlmw = qobject_cast<MainWindow *>(tlw);
372 | if (tlmw && tlmw->isVisible()) {
373 | return tlmw;
374 | }
375 | }
376 | return nullptr;
377 | }
378 |
379 | void MainApplication::storeCustomColorsInRecent()
380 | {
381 | if (QColorDialog::customCount()) {
382 | prefs_clear_string_list(recent.custom_colors);
383 | recent.custom_colors = NULL__null;
384 | for (int i = 0; i < QColorDialog::customCount(); i++) {
385 | QRgb rgb = QColorDialog::customColor(i).rgb();
386 | recent.custom_colors = g_list_append(recent.custom_colors, ws_strdup_printf("%08x", rgb)wmem_strdup_printf(__null, "%08x", rgb));
387 | }
388 | }
389 | }
390 |
391 | bool MainApplication::event(QEvent *event)
392 | {
393 | QString display_filter = NULL__null;
394 | if (event->type() == QEvent::FileOpen) {
395 | QFileOpenEvent *foe = static_cast<QFileOpenEvent *>(event);
396 | if (foe && foe->file().length() > 0) {
397 | QString cf_path(foe->file());
398 | if (initialized_) {
399 | emit openCaptureFile(cf_path, display_filter, WTAP_TYPE_AUTO0);
400 | } else {
401 | pending_open_files_.append(cf_path);
402 | }
403 | }
404 | return true;
405 | }
406 | return QApplication::event(event);
407 | }
408 |
409 | void MainApplication::cleanup()
410 | {
411 | SoftwareUpdate::instance()->cleanup();
412 | storeCustomColorsInRecent();
413 | // Write the user's recent file(s) to disk.
414 | write_profile_recent();
415 | write_recent();
416 |
417 | // We might end up here via exit_application.
418 | QThreadPool::globalInstance()->waitForDone();
419 | }
420 |
421 | MainApplication::MainApplication(int &argc, char **argv) :
422 | QApplication(argc, argv),
423 | initialized_(false),
424 | is_reloading_lua_(false),
425 | if_notifier_(NULL__null),
426 | active_captures_(0)
427 | #if defined(Q_OS_MAC) || defined(Q_OS_WIN)
428 | , normal_icon_(windowIcon())
429 | #endif
430 | {
431 | mainApp = this;
432 |
433 | MimeDatabaseInitThread *mime_db_init_thread = new(MimeDatabaseInitThread);
434 | QThreadPool::globalInstance()->start(mime_db_init_thread);
435 |
436 | Q_INIT_RESOURCE(about)do { extern int qInitResources_about (); qInitResources_about (); } while (false);
1 | Loop condition is false. Exiting loop | →
437 | Q_INIT_RESOURCE(i18n)do { extern int qInitResources_i18n (); qInitResources_i18n ( ); } while (false);
2 | ← | Loop condition is false. Exiting loop | →
438 | Q_INIT_RESOURCE(layout)do { extern int qInitResources_layout (); qInitResources_layout (); } while (false);
3 | ← | Loop condition is false. Exiting loop | →
439 | Q_INIT_RESOURCE(stock_icons)do { extern int qInitResources_stock_icons (); qInitResources_stock_icons (); } while (false);
4 | ← | Loop condition is false. Exiting loop | →
440 | Q_INIT_RESOURCE(languages)do { extern int qInitResources_languages (); qInitResources_languages (); } while (false);
5 | ← | Loop condition is false. Exiting loop | →
441 |
442 | // Initialize the ThemeManager as early as possible so that any
443 | // widget constructed afterwards can resolve themed stylesheets and
444 | // color tokens. This must run after QApplication's base ctor (so
445 | // that the palette is queryable for light/dark detection) but
446 | // before any UI is built. recent_common has already been read in
447 | // main()/stratoshark_main() prior to constructing this application
448 | // object, so we can read any configured themes as well.
449 | // Theme selection is persisted in recent_common (recent.gui_theme_name),
450 | // not in the preferences file — so it survives profile switches and
451 | // stays global to the install. Empty / missing value, or the legacy
452 | // "default" sentinel, get resolved by ThemeManager itself to the
453 | // current flavor's preferred default (wireshark / stratoshark).
454 | ThemeManager::init(ThemeManager::resolveThemeName(
455 | QString::fromUtf8(recent.gui_theme_name)));
456 |
457 | #ifdef Q_OS_WIN
458 | /* RichEd20.DLL is needed for native file dialog filter entries. */
459 | ws_load_library("riched20.dll");
460 | #endif // Q_OS_WIN
461 |
462 | // We use a lot of style sheets that base their colors on the main
463 | // application palette, so this works better.
464 | setAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles, true);
465 |
466 | // Throw various settings at the wall with the hope that one of them will
467 | // enable context menu shortcuts QTBUG-69452, QTBUG-109590
468 | setAttribute(Qt::AA_DontShowShortcutsInContextMenus, false);
469 | styleHints()->setShowShortcutsInContextMenus(true);
470 |
471 | packet_data_timer_.setParent(this);
472 | connect(&packet_data_timer_, &QTimer::timeout, this, &MainApplication::refreshPacketData);
473 | packet_data_timer_.start(1000);
474 |
475 | tap_update_timer_.setParent(this);
476 | // tap_update_timer interval is set when preferences are set before init
477 | connect(this, &MainApplication::appInitialized, &tap_update_timer_, [&]() { tap_update_timer_.start(); });
478 | connect(&tap_update_timer_, &QTimer::timeout, this, &MainApplication::updateTaps);
479 |
480 | setStyle(new ThemeStyler);
6 | ← | Memory is allocated | →
481 |
482 | connect(qApp(static_cast<QApplication *>(QCoreApplication::instance ())), &QApplication::aboutToQuit, this, &MainApplication::cleanup);
7 | ← | Potential memory leak
483 | }
484 |
485 | MainApplication::~MainApplication()
486 | {
487 | mainApp = NULL__null;
488 | clearDynamicMenuGroupItems();
489 | }
490 |
491 | void MainApplication::emitAppSignal(AppSignal signal)
492 | {
493 | switch (signal) {
494 | case ColumnsChanged:
495 | emit columnsChanged();
496 | break;
497 | case CaptureFilterListChanged:
498 | emit captureFilterListChanged();
499 | break;
500 | case DisplayFilterListChanged:
501 | emit displayFilterListChanged();
502 | break;
503 | case FilterExpressionsChanged:
504 | emit filterExpressionsChanged();
505 | break;
506 | case NameResolutionChanged:
507 | emit addressResolutionChanged();
508 | break;
509 | case PreferencesChanged:
510 | tap_update_timer_.setInterval(prefs.tap_update_interval);
511 | emit preferencesChanged();
512 | break;
513 | case PacketDissectionChanged:
514 | emit packetDissectionChanged();
515 | break;
516 | case RecentPreferencesRead:
517 | emit recentPreferencesRead();
518 | break;
519 | case FieldsChanged:
520 | emit fieldsChanged();
521 | break;
522 | case FreezePacketList:
523 | emit freezePacketList(false);
524 | break;
525 | case AggregationChanged:
526 | emit aggregationChanged();
527 | break;
528 | default:
529 | break;
530 | }
531 | }
532 |
533 | // Flush any collected app signals.
534 | //
535 | // On macOS emitting PacketDissectionChanged from a dialog can
536 | // render the application unusable:
537 | // https://gitlab.com/wireshark/wireshark/-/issues/11361
538 | // https://gitlab.com/wireshark/wireshark/-/issues/11448
539 | // Work around the problem by queueing up app signals and emitting them
540 | // after the dialog is closed.
541 | //
542 | // The following bugs might be related although they don't describe the
543 | // exact behavior we're working around here:
544 | // https://bugreports.qt.io/browse/QTBUG-38512
545 | // https://bugreports.qt.io/browse/QTBUG-38600
546 | void MainApplication::flushAppSignals()
547 | {
548 | while (!app_signals_.isEmpty()) {
549 | mainApp->emitAppSignal(app_signals_.takeFirst());
550 | }
551 | }
552 |
553 | void MainApplication::emitStatCommandSignal(const QString &menu_path, const char *arg, void *userdata)
554 | {
555 | emit openStatCommandDialog(menu_path, arg, userdata);
556 | }
557 |
558 | void MainApplication::emitTapParameterSignal(const QString cfg_abbr, const QString arg, void *userdata)
559 | {
560 | emit openTapParameterDialog(cfg_abbr, arg, userdata);
561 | }
562 |
563 | // XXX Combine statistics and funnel routines into addGroupItem + groupItems?
564 | void MainApplication::addDynamicMenuGroupItem(int group, QAction *sg_action)
565 | {
566 | if (!dynamic_menu_groups_.contains(group)) {
567 | dynamic_menu_groups_[group] = QList<QAction *>();
568 | }
569 | dynamic_menu_groups_[group] << sg_action;
570 | }
571 |
572 | void MainApplication::appendDynamicMenuGroupItem(int group, QAction *sg_action)
573 | {
574 | if (!added_menu_groups_.contains(group)) {
575 | added_menu_groups_[group] = QList<QAction *>();
576 | }
577 | added_menu_groups_[group] << sg_action;
578 | addDynamicMenuGroupItem(group, sg_action);
579 | }
580 |
581 | void MainApplication::removeDynamicMenuGroupItem(int group, QAction *sg_action)
582 | {
583 | if (!removed_menu_groups_.contains(group)) {
584 | removed_menu_groups_[group] = QList<QAction *>();
585 | }
586 | removed_menu_groups_[group] << sg_action;
587 | dynamic_menu_groups_[group].removeAll(sg_action);
588 | }
589 |
590 | void MainApplication::clearDynamicMenuGroupItems()
591 | {
592 | foreach (int group, dynamic_menu_groups_.keys())for (auto _container_592 = QtPrivate::qMakeForeachContainer(dynamic_menu_groups_ .keys()); _container_592.i != _container_592.e; ++_container_592 .i) if (int group = *_container_592.i; false) {} else {
593 | dynamic_menu_groups_[group].clear();
594 | }
595 | }
596 |
597 | QList<QAction *> MainApplication::dynamicMenuGroupItems(int group)
598 | {
599 | if (!dynamic_menu_groups_.contains(group)) {
600 | return QList<QAction *>();
601 | }
602 |
603 | QList<QAction *> sgi_list = dynamic_menu_groups_[group];
604 | std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
605 | return sgi_list;
606 | }
607 |
608 | QList<QAction *> MainApplication::addedMenuGroupItems(int group)
609 | {
610 | if (!added_menu_groups_.contains(group)) {
611 | return QList<QAction *>();
612 | }
613 |
614 | QList<QAction *> sgi_list = added_menu_groups_[group];
615 | std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
616 | return sgi_list;
617 | }
618 |
619 | QList<QAction *> MainApplication::removedMenuGroupItems(int group)
620 | {
621 | if (!removed_menu_groups_.contains(group)) {
622 | return QList<QAction *>();
623 | }
624 |
625 | QList<QAction *> sgi_list = removed_menu_groups_[group];
626 | std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
627 | return sgi_list;
628 | }
629 |
630 | void MainApplication::clearAddedMenuGroupItems()
631 | {
632 | foreach (int group, added_menu_groups_.keys())for (auto _container_632 = QtPrivate::qMakeForeachContainer(added_menu_groups_ .keys()); _container_632.i != _container_632.e; ++_container_632 .i) if (int group = *_container_632.i; false) {} else {
633 | added_menu_groups_[group].clear();
634 | }
635 | }
636 |
637 | void MainApplication::clearRemovedMenuGroupItems()
638 | {
639 | foreach (int group, removed_menu_groups_.keys())for (auto _container_639 = QtPrivate::qMakeForeachContainer(removed_menu_groups_ .keys()); _container_639.i != _container_639.e; ++_container_639 .i) if (int group = *_container_639.i; false) {} else {
640 | foreach (QAction *action, removed_menu_groups_[group])for (auto _container_640 = QtPrivate::qMakeForeachContainer(removed_menu_groups_ [group]); _container_640.i != _container_640.e; ++_container_640 .i) if (QAction *action = *_container_640.i; false) {} else {
641 | delete action;
642 | }
643 | removed_menu_groups_[group].clear();
644 | }
645 | }
646 |
647 | #ifdef HAVE_LIBPCAP1
648 |
649 | static void
650 | iface_mon_event_cb(const char *iface, int added, int up)
651 | {
652 | int present = 0;
653 | unsigned ifs, j;
654 | interface_t *device;
655 | interface_options *interface_opts;
656 |
657 | for (ifs = 0; ifs < global_capture_opts.all_ifaces->len; ifs++) {
658 | device = &g_array_index(global_capture_opts.all_ifaces, interface_t, ifs)(((interface_t*) (void *) (global_capture_opts.all_ifaces)-> data) [(ifs)]);
659 | if (strcmp(device->name, iface) == 0) {
660 | present = 1;
661 | if (!up) {
662 | /*
663 | * Interface went down or disappeared; remove all instances
664 | * of it from the current list of interfaces selected
665 | * for capturing.
666 | */
667 | for (j = 0; j < global_capture_opts.ifaces->len; j++) {
668 | interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j)(((interface_options*) (void *) (global_capture_opts.ifaces)-> data) [(j)]);
669 | if (strcmp(interface_opts->name, device->name) == 0) {
670 | capture_opts_del_iface(&global_capture_opts, j);
671 | }
672 | }
673 | }
674 | }
675 | }
676 |
677 | mainApp->emitLocalInterfaceEvent(iface, added, up);
678 | if (present != up) {
679 | /*
680 | * We've been told that there's a new interface or that an old
681 | * interface is gone; reload the local interface list.
682 | *
683 | * XXX: We also want to reload the local interface list if [what
684 | * we can retrieve about] the capabilities of the device have changed.
685 | * Ideally we'd update the capabilities of just the one device in
686 | * the cache and signal that the list has been updated, instead of
687 | * freeing the entire cache and scanning again - but some extcaps
688 | * depend on other interfaces being up; e.g. by default androiddump
689 | * tries to connect to the loopback interface to look for adb running,
690 | * so if the loopback interface changes so does the status of
691 | * androiddump.
692 | *
693 | * On Linux, at least, you can't get the capabilities from a down
694 | * interface, but it's still present in all_ifaces - dumpcap returns
695 | * it in the list, and we show it so the user can get a status / error
696 | * message when trying to capture on it instead of it vanishing.
697 | * So if both present and up are true, then we still want to refresh
698 | * to update the capabilities and restart the stats.
699 | *
700 | * We also store the address in all_ifaces and show them to the user,
701 | * so we probably should monitor those events as well and update
702 | * the interface list appropriately when those change.
703 | */
704 | MainWindow *mainWindow = mainApp->mainWindow();
705 | if (mainWindow && mainWindow->interfaceListManager())
706 | mainWindow->interfaceListManager()->requestRefresh();
707 | }
708 | }
709 |
710 | #endif
711 |
712 | void MainApplication::ifChangeEventsAvailable()
713 | {
714 | #ifdef HAVE_LIBPCAP1
715 | /*
716 | * Something's readable from the descriptor for interface
717 | * monitoring.
718 | *
719 | * Have the interface-monitoring code Read whatever interface-change
720 | * events are available, and call the callback for them.
721 | */
722 | iface_mon_event();
723 | #endif
724 | }
725 |
726 | void MainApplication::emitLocalInterfaceEvent(const char *ifname, int added, int up)
727 | {
728 | emit localInterfaceEvent(ifname, added, up);
729 | }
730 |
731 | void MainApplication::whenInitializedDispatch(const QObject *context, std::function<void()> fn)
732 | {
733 | // POLICY DECISION (your input shapes behavior here):
734 | //
735 | // We get here only when a caller registers via whenInitialized() *after*
736 | // appInitialized() has already fired. The not-yet-initialized path runs the
737 | // callback later, from the event loop, once construction is long finished.
738 | // How should the already-initialized path behave?
739 | //
740 | // A) Synchronous: fn(); right now. Simplest. But the callback runs while
741 | // the caller's constructor is still on the stack -- the object may be
742 | // only partly built, and any code after the whenInitialized() call in
743 | // that constructor runs *after* the callback. Timing differs from the
744 | // deferred path.
745 | //
746 | // B) Deferred to the event loop (e.g. QTimer::singleShot(0, context, fn)
747 | // or QMetaObject::invokeMethod(..., Qt::QueuedConnection)): callback
748 | // always runs after the current call returns, matching the signal path
749 | // exactly, so callers see one consistent ordering. Costs one event-loop
750 | // turn and needs the context-still-alive guarantee.
751 | //
752 | // Option A (current behavior) is intentional for now: it exactly reproduces
753 | // the old open-coded `if (isInitialized()) doThing();` -- a synchronous call
754 | // on the caller's stack -- so routing those sites through whenInitialized()
755 | // is a pure no-op refactor. Option B is the intended end state, but it
756 | // shifts the already-initialized callback by one event-loop turn and so
757 | // changes ordering for every converted site at once; switch to it only
758 | // behind broader ordering/lifetime tests (dialogs opened mid-session,
759 | // welcome/interface frames at cold start, context destroyed same-turn).
760 | //
761 | // To switch, delete the fn() below and enable the deferred dispatch:
762 | //
763 | // QTimer::singleShot(0, const_cast<QObject *>(context), std::move(fn));
764 | //
765 | // (context is the receiver, so the call is dropped if it dies first, and
766 | // runs on context's thread -- matching the connect() branch.)
767 | Q_UNUSED(context)(void)context; // option A ignores context; option B uses it.
768 | fn(); // option A: synchronous, matches legacy behavior.
769 | }
770 |
771 | void MainApplication::allSystemsGo()
772 | {
773 | QString display_filter = NULL__null;
774 | initialized_ = true;
775 | emit appInitialized();
776 | while (pending_open_files_.length() > 0) {
777 | emit openCaptureFile(pending_open_files_.front(), display_filter, WTAP_TYPE_AUTO0);
778 | pending_open_files_.pop_front();
779 | }
780 |
781 | bool sideBarVisible = recent.gui_welcome_page_sidebar_tips_visible ||
782 | recent.gui_welcome_page_sidebar_learn_visible;
783 | SoftwareUpdate::instance()->init(!sideBarVisible);
784 |
785 | #ifdef HAVE_LIBPCAP1
786 | int err;
787 | err = iface_mon_start(&iface_mon_event_cb);
788 | if (err == 0) {
789 | if_notifier_ = new QSocketNotifier(iface_mon_get_sock(),
790 | QSocketNotifier::Read, this);
791 | connect(if_notifier_, &QSocketNotifier::activated, this, &MainApplication::ifChangeEventsAvailable);
792 | }
793 | #endif
794 | }
795 |
796 | _e_prefs *MainApplication::readConfigurationFiles(bool reset)
797 | {
798 | e_prefs *prefs_p;
799 |
800 | if (reset) {
801 | //
802 | // Reset current preferences and enabled/disabled protocols and
803 | // heuristic dissectors before reading.
804 | // (Needed except when this is called at startup.)
805 | //
806 | prefs_reset(application_configuration_environment_prefix(), application_columns(), application_num_columns());
807 | proto_reenable_all();
808 | }
809 |
810 | /* Load libwireshark settings from the current profile. */
811 | prefs_p = epan_load_settings();
812 |
813 | return prefs_p;
814 | }
815 |
816 | static void switchTranslator(QTranslator& myTranslator, const QLocale &locale, const QString& filename, const QStringList &searchPath)
817 | {
818 | mainApp->removeTranslator(&myTranslator);
819 | for (const QString &path : searchPath) {
820 | if (myTranslator.load(locale, filename, QStringLiteral("_")(QString(QtPrivate::qMakeStringPrivate(u"" "_"))), path)) {
821 | mainApp->installTranslator(&myTranslator);
822 | return;
823 | }
824 | }
825 | if (locale.language() != QLocale::C) {
826 | /* Don't compare the locale itself, see:
827 | * https://doc.qt.io/qt-6/qlocale.html#operator-eq-eq
828 | *
829 | * Note that the ordered list of languages that were tried is that of
830 | * locale.uiLanguages(); the first language in that list is not
831 | * necessarily locale.language(), especially on Windows (See #17221.)
832 | */
833 | qWarningQMessageLogger(static_cast<const char *>("ui/qt/main_application.cpp" ), 833, static_cast<const char *>(__PRETTY_FUNCTION__)) .warning() << "Couldn't load" << filename << "translations." << "Searched:" << searchPath;
834 | }
835 | }
836 |
837 | void MainApplication::loadLanguage(const QString newLanguage)
838 | {
839 | QLocale locale;
840 | const char* env_prefix = application_configuration_environment_prefix();
841 |
842 | if (newLanguage.isEmpty() || newLanguage == USE_SYSTEM_LANGUAGE"system") {
843 | locale = QLocale::system();
844 | } else {
845 | locale = QLocale(newLanguage);
846 | }
847 |
848 | QLocale::setDefault(locale);
849 |
850 | // Search path list ordered by priority. Prefer personal configuration
851 | // to global datadir to embedded resources to Qt global directory.
852 | QStringList searchPath;
853 | searchPath.emplaceBack(gchar_free_to_qstring(get_persconffile_path("languages", false, env_prefix)));
854 | searchPath.emplaceBack(QStringLiteral("%1/languages")(QString(QtPrivate::qMakeStringPrivate(u"" "%1/languages"))).arg(get_datafile_dir(env_prefix)));
855 | searchPath.emplaceBack(QStringLiteral(":/i18n/")(QString(QtPrivate::qMakeStringPrivate(u"" ":/i18n/"))));
856 |
857 | #if QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 8, 0)((6<<16)|(8<<8)|(0))
858 | searchPath.append(QLibraryInfo::paths(QLibraryInfo::TranslationsPath));
859 | #else
860 | searchPath.emplaceBack(QLibraryInfo::path(QLibraryInfo::TranslationsPath));
861 | #endif
862 |
863 | // Translations are searched for in the reverse order in which they were
864 | // installed, so install the Qt generic translator first and ours last.
865 | switchTranslator(mainApp->translatorQt, locale, QStringLiteral("qt")(QString(QtPrivate::qMakeStringPrivate(u"" "qt"))), searchPath);
866 |
867 | // XXX - Yes, the translation files are also wireshark_%1.qm for Stratoshark.
868 | // There is a stratoshark_en.[ts|qm] file too (for plurals?) though I'm
869 | // not sure if it's used properly.
870 | switchTranslator(mainApp->translator, locale, QStringLiteral("wireshark")(QString(QtPrivate::qMakeStringPrivate(u"" "wireshark"))), searchPath);
871 | }
872 |
873 | void MainApplication::doTriggerMenuItem(MainMenuItem menuItem)
874 | {
875 | switch (menuItem)
876 | {
877 | case FileOpenDialog:
878 | emit openCaptureFile(QString(), QString(), WTAP_TYPE_AUTO0);
879 | break;
880 | case CaptureOptionsDialog:
881 | emit openCaptureOptions();
882 | break;
883 | }
884 | }
885 |
886 | void MainApplication::captureEventHandler(CaptureEvent ev)
887 | {
888 | switch(ev.captureContext())
889 | {
890 | #ifdef HAVE_LIBPCAP1
891 | case CaptureEvent::Update:
892 | case CaptureEvent::Fixed:
893 | switch (ev.eventType())
894 | {
895 | case CaptureEvent::Prepared:
896 | iface_mon_enable(true);
897 | break;
898 | case CaptureEvent::Started:
899 | active_captures_++;
900 | emit captureActive(active_captures_);
901 | break;
902 | case CaptureEvent::Finished:
903 | active_captures_--;
904 | emit captureActive(active_captures_);
905 | // A refresh requested during the capture was deferred by
906 | // InterfaceListManager (capture-active guard) and is serviced now via
907 | // the captureActive signal above; no explicit re-trigger needed.
908 | break;
909 | default:
910 | break;
911 | }
912 | break;
913 | #endif
914 | case CaptureEvent::File:
915 | case CaptureEvent::Reload:
916 | case CaptureEvent::Rescan:
917 | switch (ev.eventType())
918 | {
919 | case CaptureEvent::Started:
920 | QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL3000 / 5, this, SLOT(updateTaps())qFlagLocation("1" "updateTaps()" "\0" "ui/qt/main_application.cpp" ":" "920"));
921 | QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL3000 / 2, this, SLOT(updateTaps())qFlagLocation("1" "updateTaps()" "\0" "ui/qt/main_application.cpp" ":" "921"));
922 | break;
923 | case CaptureEvent::Finished:
924 | updateTaps();
925 | break;
926 | default:
927 | break;
928 | }
929 | break;
930 | default:
931 | break;
932 | }
933 | }
934 |
935 | void MainApplication::pushStatus(StatusInfo status, const QString &message, const QString &messagetip)
936 | {
937 | MainWindow * mw = mainWindow();
938 | if (! mw) {
939 | return;
940 | }
941 |
942 | MainStatusBar * bar = mw->statusBar();
943 | if (! bar) {
944 | return;
945 | }
946 |
947 | switch(status)
948 | {
949 | case FilterSyntax:
950 | bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILTER, message);
951 | break;
952 | case FieldStatus:
953 | bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FIELD, message);
954 | break;
955 | case FileStatus:
956 | bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILE, message, messagetip);
957 | break;
958 | case ByteStatus:
959 | bar->pushGenericStatus(MainStatusBar::STATUS_CTX_BYTE, message);
960 | break;
961 | case BusyStatus:
962 | bar->pushGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS, message, messagetip);
963 | break;
964 | case TemporaryStatus:
965 | bar->pushGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY, message);
966 | break;
967 | }
968 | }
969 |
970 | void MainApplication::popStatus(StatusInfo status)
971 | {
972 | MainWindow * mw = mainWindow();
973 | if (! mw) {
974 | return;
975 | }
976 |
977 | MainStatusBar * bar = mw->statusBar();
978 | if (! bar) {
979 | return;
980 | }
981 |
982 | switch(status)
983 | {
984 | case FilterSyntax:
985 | bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILTER);
986 | break;
987 | case FieldStatus:
988 | bar->popGenericStatus(MainStatusBar::STATUS_CTX_FIELD);
989 | break;
990 | case FileStatus:
991 | bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILE);
992 | break;
993 | case ByteStatus:
994 | bar->popGenericStatus(MainStatusBar::STATUS_CTX_BYTE);
995 | break;
996 | case BusyStatus:
997 | bar->popGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS);
998 | break;
999 | case TemporaryStatus:
1000 | bar->popGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY);
1001 | break;
1002 | }
1003 | }
1004 |
1005 | void MainApplication::gotoFrame(int frame)
1006 | {
1007 | MainWindow * mw = mainWindow();
1008 | if (! mw) {
1009 | return;
1010 | }
1011 |
1012 | mw->gotoFrame(frame);
1013 | }
1014 |
1015 | void MainApplication::reloadDisplayFilterMacros()
1016 | {
1017 | dfilter_macro_reload(application_configuration_environment_prefix());
1018 | // The signal is needed when the display filter grammar changes for
1019 | // any reason (not just "fields".)
1020 | mainApp->emitAppSignal(MainApplication::FieldsChanged);
1021 | }