File: probe.cpp

package info (click to toggle)
gammaray 3.1.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 24,796 kB
  • sloc: cpp: 109,174; ansic: 2,156; sh: 336; python: 274; yacc: 90; lex: 82; xml: 61; makefile: 28; javascript: 9; ruby: 5
file content (999 lines) | stat: -rw-r--r-- 31,737 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
/*
  probe.cpp

  This file is part of GammaRay, the Qt application inspection and manipulation tool.

  SPDX-FileCopyrightText: 2010 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Volker Krause <volker.krause@kdab.com>

  SPDX-License-Identifier: GPL-2.0-or-later

  Contact KDAB at <info@kdab.com> for commercial licensing options.
*/
// krazy:excludeall=null,captruefalse,staticobjects

#include <config-gammaray.h>

#include "probe.h"
#include "enumrepositoryserver.h"
#include "execution.h"
#include "classesiconsrepositoryserver.h"
#include "metaobjectrepository.h"
#include "objectlistmodel.h"
#include "objecttreemodel.h"
#include "probesettings.h"
#include "probecontroller.h"
#include "problemcollector.h"
#include "toolmanager.h"
#include "toolpluginmodel.h"
#include "util.h"
#include "varianthandler.h"
#include "metaobjectregistry.h"
#include "favoriteobject.h"

#include "remote/server.h"
#include "remote/remotemodelserver.h"
#include "remote/serverproxymodel.h"
#include "remote/selectionmodelserver.h"
#include "toolpluginerrormodel.h"
#include "probeguard.h"

#include <common/objectbroker.h>
#include <common/streamoperators.h>
#include <common/paths.h>

#include <compat/qasconst.h>

#include <QGuiApplication>
#include <QWindow>
#include <QDir>
#include <QLibrary>
#include <QMouseEvent>
#include <QUrl>
#include <QThread>
#include <QTimer>
#include <private/qobject_p.h>
#include <private/qhooks_p.h>
#include <algorithm>
#include <iostream>
#include <cstdio>

#define IF_DEBUG(x)

#ifdef ENABLE_EXPENSIVE_ASSERTS
#define EXPENSIVE_ASSERT(x) Q_ASSERT(x)
#else
#define EXPENSIVE_ASSERT(x)
#endif

using namespace GammaRay;
using namespace std;

QAtomicPointer<Probe> Probe::s_instance = QAtomicPointer<Probe>(nullptr);

namespace GammaRay {
static void signal_begin_callback(QObject *caller, int method_index, void **argv)
{
    // Ignore event dispatcher signals
    if (caller->inherits("QAbstractEventDispatcher"))
        return;

    if (method_index == 0 || !Probe::instance() || Probe::instance()->filterObject(caller))
        return;

    method_index = Util::signalIndexToMethodIndex(caller->metaObject(), method_index);
    Probe::executeSignalCallback([=](const SignalSpyCallbackSet &callbacks) {
        if (callbacks.signalBeginCallback)
            callbacks.signalBeginCallback(caller, method_index, argv);
    });
}

static void signal_end_callback(QObject *caller, int method_index)
{
    if (method_index == 0 || !Probe::instance())
        return;

    QMutexLocker locker(Probe::objectLock());
    if (!Probe::instance())
        return;
    if (!Probe::instance()->isValidObject(caller)) // implies filterObject()
        return; // deleted in the slot
    locker.unlock();

    method_index = Util::signalIndexToMethodIndex(caller->metaObject(), method_index);
    Probe::executeSignalCallback([=](const SignalSpyCallbackSet &callbacks) {
        if (callbacks.signalEndCallback)
            callbacks.signalEndCallback(caller, method_index);
    });
}

static void slot_begin_callback(QObject *caller, int method_index, void **argv)
{
    if (method_index == 0 || !Probe::instance() || Probe::instance()->filterObject(caller))
        return;

    Probe::executeSignalCallback([=](const SignalSpyCallbackSet &callbacks) {
        if (callbacks.slotBeginCallback)
            callbacks.slotBeginCallback(caller, method_index, argv);
    });
}

static void slot_end_callback(QObject *caller, int method_index)
{
    if (method_index == 0 || !Probe::instance())
        return;

    QMutexLocker locker(Probe::objectLock());
    if (!Probe::instance()->isValidObject(caller)) // implies filterObject()
        return; // deleted in the slot
    locker.unlock();

    Probe::executeSignalCallback([=](const SignalSpyCallbackSet &callbacks) {
        if (callbacks.slotEndCallback)
            callbacks.slotEndCallback(caller, method_index);
    });
}

static QItemSelectionModel *selectionModelFactory(QAbstractItemModel *model)
{
    Q_ASSERT(!model->objectName().isEmpty());
    return new SelectionModelServer(model->objectName() + ".selection", model, Probe::instance());
}
}

// useful for debugging, dumps the object and all it's parents
// also usable from GDB!
void dumpObject(QObject *obj)
{
    if (!obj) {
        cout << "QObject(0x0)" << endl;
        return;
    }

    const std::ios::fmtflags oldFlags(cout.flags());
    do {
        cout << obj->metaObject()->className() << "(" << hex << obj << ")";
        obj = obj->parent();
        if (obj)
            cout << " <- ";
    } while (obj);
    cout << endl;
    cout.flags(oldFlags);
}

struct Listener
{
    Listener() = default;

    bool trackDestroyed = true;
    QVector<QObject *> addedBeforeProbeInstance;

    QHash<QObject *, Execution::Trace> constructionBacktracesForObjects;
};

Q_GLOBAL_STATIC(Listener, s_listener)

// ensures proper information is returned by isValidObject by
// locking it in objectAdded/Removed
Q_GLOBAL_STATIC(QRecursiveMutex, s_lock)

Probe::Probe(QObject *parent)
    : QObject(parent)
    , m_objectListModel(new ObjectListModel(this))
    , m_objectTreeModel(new ObjectTreeModel(this))
    , m_window(nullptr)
    , m_metaObjectRegistry(new MetaObjectRegistry(this))
    , m_queueTimer(new QTimer(this))
    , m_server(nullptr)
{
    qputenv("DEBUGINFOD_URLS", QByteArray());

    Q_ASSERT(thread() == qApp->thread());
    IF_DEBUG(cout << "attaching GammaRay probe" << endl;)

    StreamOperators::registerOperators();
    ProbeSettings::receiveSettings();

    m_server = new Server(this);

    ObjectBroker::setSelectionModelFactoryCallback(selectionModelFactory);
    ObjectBroker::registerObject<ProbeControllerInterface *>(new ProbeController(this));
    m_toolManager = new ToolManager(this);
    ObjectBroker::registerObject<ToolManagerInterface *>(m_toolManager);
    ObjectBroker::registerObject<FavoriteObjectInterface *>(new FavoriteObject(this));

    m_problemCollector = new ProblemCollector(this);

    ObjectBroker::registerObject<EnumRepository *>(EnumRepositoryServer::create(this));
    ClassesIconsRepositoryServer::create(this);
    registerModel(QStringLiteral("com.kdab.GammaRay.ObjectTree"), m_objectTreeModel);
    registerModel(QStringLiteral("com.kdab.GammaRay.ObjectList"), m_objectListModel);

    ToolPluginModel *toolPluginModel = new ToolPluginModel(
        m_toolManager->toolPluginManager()->plugins(), this);
    registerModel(QStringLiteral("com.kdab.GammaRay.ToolPluginModel"), toolPluginModel);
    ToolPluginErrorModel *toolPluginErrorModel = new ToolPluginErrorModel(m_toolManager->toolPluginManager()->errors(), this);
    registerModel(QStringLiteral("com.kdab.GammaRay.ToolPluginErrorModel"), toolPluginErrorModel);

    m_queueTimer->setSingleShot(true);
    m_queueTimer->setInterval(0);
    connect(m_queueTimer, &QTimer::timeout,
            this, &Probe::processQueuedObjectChanges);

    m_previousSignalSpyCallbackSet = qt_signal_spy_callback_set.loadRelaxed();

    connect(this, &Probe::objectCreated, m_metaObjectRegistry, &MetaObjectRegistry::objectAdded);
    connect(this, &Probe::objectDestroyed, m_metaObjectRegistry, &MetaObjectRegistry::objectRemoved);
}

Probe::~Probe()
{
    emit aboutToDetach();
    IF_DEBUG(cerr << "detaching GammaRay probe" << endl;)

    // Remove hooks
    qtHookData[QHooks::AddQObject] = 0;
    qtHookData[QHooks::RemoveQObject] = 0;
    qtHookData[QHooks::Startup] = 0;

    qt_register_signal_spy_callbacks(m_previousSignalSpyCallbackSet);

    ObjectBroker::clear();
    ProbeSettings::resetLauncherIdentifier();
    MetaObjectRepository::instance()->clear();
    VariantHandler::clear();

    s_instance = QAtomicPointer<Probe>(nullptr);
}

void Probe::setWindow(QObject *window)
{
    m_window = window;
}

QObject *Probe::window() const
{
    return m_window;
}

MetaObjectRegistry *Probe::metaObjectRegistry() const
{
    return m_metaObjectRegistry;
}

Probe *GammaRay::Probe::instance()
{
    return s_instance.loadRelaxed();
}

bool Probe::isInitialized()
{
    return instance();
}

bool Probe::canShowWidgets()
{
    return QCoreApplication::instance()->inherits("QApplication");
}

void Probe::createProbe(bool findExisting)
{
    Q_ASSERT(qApp);
    Q_ASSERT(!isInitialized());

    // first create the probe and its children
    // we must not hold the object lock here as otherwise we can deadlock
    // with other QObject's we create and other threads are using. One
    // example are QAbstractSocketEngine.
    IF_DEBUG(cout << "setting up new probe instance" << endl;)
    Probe *probe = nullptr;
    {
        ProbeGuard guard;
        probe = new Probe;
    }
    IF_DEBUG(cout << "done setting up new probe instance" << endl;)

    connect(qApp, &QCoreApplication::aboutToQuit, probe, &Probe::shutdown);

    // Our safety net, if there's no call to QCoreApplication::exec() we'll never receive the aboutToQuit() signal
    // Make sure we still cleanup safely after the application instance got destroyed
    connect(qApp, &QObject::destroyed, probe, &Probe::shutdown);

    // now we can get the lock and add items which where added before this point in time
    {
        QMutexLocker lock(s_lock());
        // now we set the instance while holding the lock,
        // all future calls to object{Added,Removed} will
        // act directly on the data structures there instead
        // of using addedBeforeProbeInstance
        // this will only happen _after_ the object lock above is released though
        Q_ASSERT(!instance());

        s_instance = QAtomicPointer<Probe>(probe);

        // add objects to the probe that were tracked before its creation
        foreach (QObject *obj, s_listener()->addedBeforeProbeInstance) {
            objectAdded(obj);
        }
        s_listener()->addedBeforeProbeInstance.clear();

        // try to find existing objects by other means
        if (findExisting)
            probe->findExistingObjects();
    }

    // eventually initialize the rest
    QMetaObject::invokeMethod(probe, "delayedInit", Qt::QueuedConnection);
}

void Probe::resendServerAddress()
{
    Q_ASSERT(isInitialized());
    Q_ASSERT(m_server);
    if (!m_server->isListening()) // already connected
        return;
    ProbeSettings::receiveSettings();
    ProbeSettings::sendServerAddress(m_server->externalAddress());
}

void Probe::startupHookReceived()
{
#ifdef Q_OS_ANDROID
    QDir root = QDir::home();
    root.cdUp();
    Paths::setRootPath(root.absolutePath());
#endif
    s_listener()->trackDestroyed = false;
}

void Probe::delayedInit()
{
    QCoreApplication::instance()->installEventFilter(this);

    QString appName = qApp->applicationName();
    if (appName.isEmpty() && !qApp->arguments().isEmpty()) {
        appName = qApp->arguments().first().remove(qApp->applicationDirPath());
        if (appName.startsWith('.'))
            appName = appName.right(appName.length() - 1);
        if (appName.startsWith('/'))
            appName = appName.right(appName.length() - 1);
    }
    if (appName.isEmpty())
        appName = tr("PID %1").arg(qApp->applicationPid());
    m_server->setLabel(appName);
    // The applicationName might be translated, so let's go with the application file base name
    m_server->setKey(QFileInfo(qApp->applicationFilePath()).completeBaseName());
    m_server->setPid(qApp->applicationPid());

    if (ProbeSettings::value(QStringLiteral("RemoteAccessEnabled"), true).toBool()) {
        const auto serverStarted = m_server->listen();
        if (serverStarted) {
            ProbeSettings::sendServerAddress(m_server->externalAddress());
        } else {
            ProbeSettings::sendServerLaunchError(m_server->errorString());
        }
    }

    if (ProbeSettings::value(QStringLiteral("InProcessUi"), false).toBool())
        showInProcessUi();
}

void Probe::shutdown()
{
    delete this;
}

void Probe::showInProcessUi()
{
    if (!canShowWidgets()) {
        cerr << "Unable to show in-process UI in a non-QWidget based application." << endl;
        return;
    }

    IF_DEBUG(cout << "creating GammaRay::MainWindow" << endl;)
    ProbeGuard guard;

    QLibrary lib;
    for (auto &path : Paths::pluginPaths(QStringLiteral(GAMMARAY_PROBE_ABI))) {
        path += QStringLiteral("/gammaray_inprocessui");
#if defined(GAMMARAY_INSTALL_QT_LAYOUT)
        path += '-';
        path += GAMMARAY_PROBE_ABI;
#else
#if !defined(Q_OS_MAC)
#if defined(QT_DEBUG)
        path += QLatin1String(GAMMARAY_DEBUG_POSTFIX);
#endif
#endif
#endif
        lib.setFileName(path);
        if (lib.load())
            break;
    }

    if (!lib.isLoaded()) {
        std::cerr << "Failed to load in-process UI module: "
                  << qPrintable(lib.errorString())
                  << std::endl;
    } else {
        void (*factory)() = reinterpret_cast<void (*)()>(lib.resolve("gammaray_create_inprocess_mainwindow"));
        if (!factory)
            std::cerr << Q_FUNC_INFO << ' ' << qPrintable(lib.errorString()) << endl;
        else
            factory();
    }

    IF_DEBUG(cout << "creation done" << endl;)
}

bool Probe::filterObject(QObject *obj) const
{
    QSet<QObject *> visitedObjects;
    int iteration = 0;
    QObject *o = obj;
    do {
        if (iteration > 100) {
            // Probably we have a loop in the tree. Do loop detection.
            if (visitedObjects.contains(o)) {
                std::cerr << "We detected a loop in the object tree for object " << o;
                if (!o->objectName().isEmpty())
                    std::cerr << " \"" << qPrintable(o->objectName()) << "\"";
                std::cerr << " (" << o->metaObject()->className() << ")." << std::endl;
                return true;
            }
            visitedObjects << o;
        }
        ++iteration;

        if (o == this || o == window() || (qstrncmp(o->metaObject()->className(), "GammaRay::", 10) == 0)) {
            return true;
        }
        o = o->parent();
    } while (o);
    return false;
}

void Probe::registerModel(const QString &objectName, QAbstractItemModel *model)
{
    auto *ms = new RemoteModelServer(objectName, model);
    ms->setModel(model);
    ObjectBroker::registerModelInternal(objectName, model);
}

QAbstractItemModel *Probe::objectListModel() const
{
    return m_objectListModel;
}

const QVector<QObject *> &Probe::allQObjects() const
{
    return m_objectListModel->objects();
}

QAbstractItemModel *Probe::objectTreeModel() const
{
    return m_objectTreeModel;
}

ProblemCollector *Probe::problemCollector() const
{
    return m_problemCollector;
}

QRecursiveMutex *Probe::objectLock()
{
    return s_lock();
}

/*
 * We need to handle 4 different cases in here:
 * (1) our thread, from ctor:
 * - wait until next event-loop re-entry of our thread
 * - emit objectCreated if object still valid
 * (2) our thread, after ctor:
 * - emit objectCreated right away
 * (3) other thread, from ctor:
 * - wait until next event-loop re-entry in other thread (FIXME: we do not currently do this!!)
 * - post information to our thread
 * (4) other thread, after ctor:
 * - post information to our thread
 * - emit objectCreated there right away if object still valid
 *
 * Pre-conditions: lock may or may not be held already, arbitrary thread
 */
void Probe::objectAdded(QObject *obj, bool fromCtor)
{
    QMutexLocker lock(s_lock());

    // attempt to ignore objects created by GammaRay itself, especially short-lived ones
    if (fromCtor && ProbeGuard::insideProbe() && obj->thread() == QThread::currentThread())
        return;

    // ignore objects created when global statics are already getting destroyed (on exit)
    if (s_listener.isDestroyed())
        return;


    if (Execution::hasFastStackTrace() && fromCtor) {
        s_listener()->constructionBacktracesForObjects.insert(obj, Execution::stackTrace(32, 2)); // skip 2: this and the hook function calling us
    }

    if (!isInitialized()) {
        IF_DEBUG(cout
                     << "objectAdded Before: "
                     << hex << obj
                     << (fromCtor ? " (from ctor)" : "") << endl;)
        s_listener()->addedBeforeProbeInstance << obj;
        return;
    }

    if (instance()->filterObject(obj)) {
        IF_DEBUG(cout
                     << "objectAdded Filter: "
                     << hex << obj
                     << (fromCtor ? " (from ctor)" : "") << endl;)
        return;
    }

    if (instance()->m_validObjects.contains(obj)) {
        // this happens when we get a child event before the objectAdded call from the ctor
        // or when we add an item from addedBeforeProbeInstance who got added already
        // due to the add-parent-before-child logic
        IF_DEBUG(cout
                     << "objectAdded Known: "
                     << hex << obj
                     << (fromCtor ? " (from ctor)" : "") << endl;)
        return;
    }

    // make sure we already know the parent
    if (obj->parent() && !instance()->m_validObjects.contains(obj->parent()))
        objectAdded(obj->parent(), fromCtor);
    Q_ASSERT(!obj->parent() || instance()->m_validObjects.contains(obj->parent()));

    instance()->m_validObjects << obj;

    if (!fromCtor && obj->parent() && instance()->isObjectCreationQueued(obj->parent())) {
        // when a child event triggers a call to objectAdded while inside the ctor
        // the parent is already tracked but it's call to objectFullyConstructed
        // was delayed. hence we must do the same for the child for integrity
        fromCtor = true;
    }

    IF_DEBUG(cout << "objectAdded: " << hex << obj
                  << (fromCtor ? " (from ctor)" : "")
                  << ", p: " << obj->parent() << endl;)

    if (fromCtor)
        instance()->queueCreatedObject(obj);
    else
        instance()->objectFullyConstructed(obj);
}

// pre-conditions: lock may or may not be held already, our thread
void Probe::processQueuedObjectChanges()
{
    QMutexLocker lock(s_lock());

    IF_DEBUG(cout << Q_FUNC_INFO << " " << m_queuedObjectChanges.size() << endl;)

    // must be called from the main thread via timeout
    Q_ASSERT(QThread::currentThread() == thread());

    const auto queuedObjectChanges = m_queuedObjectChanges; // copy, in case this gets modified while we iterate (which can actually happen)
    for (const auto &change : queuedObjectChanges) {
        switch (change.type) {
        case ObjectChange::Create:
            objectFullyConstructed(change.obj);
            break;
        case ObjectChange::Destroy:
            emit objectDestroyed(change.obj);
            break;
        }
    }

    IF_DEBUG(cout << Q_FUNC_INFO << " done" << endl;)

    m_queuedObjectChanges.clear();

    for (QObject *obj : qAsConst(m_pendingReparents)) {
        if (!isValidObject(obj))
            continue;
        if (filterObject(obj)) // the move might have put it under a hidden parent
            objectRemoved(obj);
        else
            emit objectReparented(obj);
    }
    m_pendingReparents.clear();
}

// pre-condition: lock is held already, our thread
void Probe::objectFullyConstructed(QObject *obj)
{
    Q_ASSERT(thread() == QThread::currentThread());

    if (!m_validObjects.contains(obj)) {
        // deleted already
        IF_DEBUG(cout << "stale fully constructed: " << hex << obj << endl;)
        return;
    }

    if (filterObject(obj)) {
        // when the call was delayed from the ctor construction,
        // the parent might not have been set properly yet. hence
        // apply the filter again
        m_validObjects.remove(obj);
        IF_DEBUG(cout << "now filtered fully constructed: " << hex << obj << endl;)
        return;
    }

    IF_DEBUG(cout << "fully constructed: " << hex << obj << endl;)

    // ensure we know all our ancestors already
    for (QObject *parent = obj->parent(); parent; parent = parent->parent()) {
        if (!m_validObjects.contains(parent)) {
            objectAdded(parent); // will also handle any further ancestors
            break;
        }
    }
    Q_ASSERT(!obj->parent() || m_validObjects.contains(obj->parent()));

    m_toolManager->objectAdded(obj);
    emit objectCreated(obj);
}

/*
 * We have two cases to consider here:
 * (1) our thread:
 * - emit objectDestroyed() right away
 * (2) other thread:
 * - post information to our thread, emit objectDestroyed() there
 *
 * pre-conditions: arbitrary thread, lock may or may not be held already
 */
void Probe::objectRemoved(QObject *obj)
{
    QMutexLocker lock(s_lock());

    if (!isInitialized()) {
        IF_DEBUG(cout
                     << "objectRemoved Before: "
                     << hex << obj
                     << " have statics: " << s_listener() << endl;)

        if (!s_listener())
            return;

        QVector<QObject *> &addedBefore = s_listener()->addedBeforeProbeInstance;
        for (auto it = addedBefore.begin(); it != addedBefore.end();) {
            if (*it == obj)
                it = addedBefore.erase(it);
            else
                ++it;
        }
        return;
    }

    IF_DEBUG(cout << "object removed:" << hex << obj << " " << obj->parent() << endl;)

    bool success = instance()->m_validObjects.remove(obj);
    if (!success) {
        // object was not tracked by the probe, probably a gammaray object
        EXPENSIVE_ASSERT(!instance()->isObjectCreationQueued(obj));
        return;
    }

    instance()->purgeChangesForObject(obj);
    EXPENSIVE_ASSERT(!instance()->isObjectCreationQueued(obj));

    if (instance()->thread() == QThread::currentThread())
        emit instance()->objectDestroyed(obj);
    else
        instance()->queueDestroyedObject(obj);
}

void Probe::handleObjectDestroyed(QObject *obj)
{
    objectRemoved(obj);
}

// pre-condition: we have the lock, arbitrary thread
void Probe::queueCreatedObject(QObject *obj)
{
    EXPENSIVE_ASSERT(!isObjectCreationQueued(obj));

    ObjectChange c;
    c.obj = obj;
    c.type = ObjectChange::Create;
    m_queuedObjectChanges.push_back(c);
    notifyQueuedObjectChanges();
}

// pre-condition: we have the lock, arbitrary thread
void Probe::queueDestroyedObject(QObject *obj)
{
    ObjectChange c;
    c.obj = obj;
    c.type = ObjectChange::Destroy;
    m_queuedObjectChanges.push_back(c);
    notifyQueuedObjectChanges();
}

// pre-condition: we have the lock, arbitrary thread
bool Probe::isObjectCreationQueued(QObject *obj) const
{
    return std::find_if(m_queuedObjectChanges.begin(), m_queuedObjectChanges.end(),
                        [obj](const ObjectChange &c) {
                            return c.obj == obj && c.type == Probe::ObjectChange::Create;
                        })
        != m_queuedObjectChanges.end();
}

// pre-condition: we have the lock, arbitrary thread
void Probe::purgeChangesForObject(QObject *obj)
{
    for (int i = 0; i < m_queuedObjectChanges.size(); ++i) {
        if (m_queuedObjectChanges.at(i).obj == obj
            && m_queuedObjectChanges.at(i).type == ObjectChange::Create) {
            m_queuedObjectChanges.remove(i);
            return;
        }
    }
}

// pre-condition: we have the lock, arbitrary thread
void Probe::notifyQueuedObjectChanges()
{
    if (m_queueTimer->isActive())
        return;

    if (thread() == QThread::currentThread()) {
        m_queueTimer->start();
    } else {
        static QMetaMethod m;
        if (m.methodIndex() < 0) {
            const auto idx = QTimer::staticMetaObject.indexOfMethod("start()");
            Q_ASSERT(idx >= 0);
            m = QTimer::staticMetaObject.method(idx);
            Q_ASSERT(m.methodIndex() >= 0);
        }
        m.invoke(m_queueTimer, Qt::QueuedConnection);
    }
}

bool Probe::eventFilter(QObject *receiver, QEvent *event)
{
    if (ProbeGuard::insideProbe() && receiver->thread() == QThread::currentThread())
        return QObject::eventFilter(receiver, event);

    if (event->type() == QEvent::ChildAdded || event->type() == QEvent::ChildRemoved) {
        QChildEvent *childEvent = static_cast<QChildEvent *>(event);
        QObject *obj = childEvent->child();

        QMutexLocker lock(s_lock());
        const bool tracked = m_validObjects.contains(obj);
        const bool filtered = filterObject(obj);

        IF_DEBUG(cout << "child event: " << hex << obj << ", p: " << obj->parent() << dec
                      << ", tracked: " << tracked
                      << ", filtered: " << filtered
                      << ", type: " << (childEvent->added() ? "added" : "removed") << endl;)

        if (!filtered && childEvent->added()) {
            if (!tracked) {
                // was not tracked before, add to all models
                // child added events are sent before qt_addObject is called,
                // so we assumes this comes from the ctor
                objectAdded(obj, true);
            } else if (!isObjectCreationQueued(obj) && !isObjectCreationQueued(obj->parent()) && isValidObject(obj->parent())) {
                // object is known already, just update the position in the tree
                // BUT: only when we did not queue this item before
                IF_DEBUG(cout << "update pos: " << hex << obj << endl;)
                m_pendingReparents.removeAll(obj);
                emit objectReparented(obj);
            } else if (!isValidObject(obj->parent())) {
                objectAdded(obj->parent());
                m_pendingReparents.push_back(obj);
                notifyQueuedObjectChanges();
            }
        } else if (tracked) {
            // defer processing this until we know its final location
            m_pendingReparents.push_back(obj);
            notifyQueuedObjectChanges();
        }
    }

    // widget only unfortunately, but more precise than ChildAdded/Removed...
    if (event->type() == QEvent::ParentChange) {
        QMutexLocker lock(s_lock());
        const bool tracked = m_validObjects.contains(receiver);
        const bool filtered = filterObject(receiver);
        const bool parentTracked = m_validObjects.contains(receiver->parent());

        if (!filtered && tracked && !isObjectCreationQueued(receiver)
            && !isObjectCreationQueued(receiver->parent()) && parentTracked) {
            m_pendingReparents.removeAll(receiver);
            emit objectReparented(receiver);
        } else if (!parentTracked) {
            objectAdded(receiver->parent());
            m_pendingReparents.push_back(receiver);
            notifyQueuedObjectChanges();
        }
    }

    // we have no preloading hooks, so recover all objects we see
    if (needsObjectDiscovery() && event->type() != QEvent::ChildAdded
        && event->type() != QEvent::ChildRemoved
        && event->type() != QEvent::ParentChange // already handled above
        && event->type() != QEvent::Destroy
        && event->type() != QEvent::WinIdChange // unsafe since emitted from dtors
        && !filterObject(receiver)) {
        QMutexLocker lock(s_lock());
        const bool tracked = m_validObjects.contains(receiver);
        if (!tracked)
            discoverObject(receiver);
    }

    // filters provided by plugins
    if (!filterObject(receiver)) {
        for (QObject *filter : qAsConst(m_globalEventFilters)) {
            filter->eventFilter(receiver, event);
        }
    }

    return QObject::eventFilter(receiver, event);
}

void Probe::findExistingObjects()
{
    discoverObject(QCoreApplication::instance());

    if (auto guiApp = qobject_cast<QGuiApplication *>(QCoreApplication::instance())) {
        foreach (auto window, guiApp->allWindows()) {
            discoverObject(window);
        }
    }
}

void Probe::discoverObject(QObject *object)
{
    if (!object)
        return;

    QMutexLocker lock(s_lock());
    if (m_validObjects.contains(object))
        return;

    objectAdded(object);
    foreach (QObject *child, object->children()) {
        discoverObject(child);
    }
}

void Probe::installGlobalEventFilter(QObject *filter)
{
    Q_ASSERT(!m_globalEventFilters.contains(filter));
    m_globalEventFilters.push_back(filter);
}

bool Probe::needsObjectDiscovery()
{
    return s_listener()->trackDestroyed;
}

bool Probe::hasReliableObjectTracking()
{
    return true; // qHooks available, which works independent of the injector used
}

void Probe::selectObject(QObject *object, const QPoint &pos)
{
    const auto tools = m_toolManager->toolsForObject(object);
    m_toolManager->selectTool(tools.value(0));
    emit objectSelected(object, pos);
}

void Probe::selectObject(QObject *object, const QString &toolId, const QPoint &pos)
{
    if (!m_toolManager->hasTool(toolId)) {
        std::cerr << "Invalid tool id: " << qPrintable(toolId) << std::endl;
        return;
    }

    m_toolManager->selectTool(toolId);
    emit objectSelected(object, pos);
}

void Probe::selectObject(void *object, const QString &typeName)
{
    const auto tools = m_toolManager->toolsForObject(object, typeName);
    const QString toolId = tools.value(0);

    if (!m_toolManager->hasTool(toolId)) {
        std::cerr << "Invalid tool id: " << qPrintable(toolId) << std::endl;
        return;
    }

    m_toolManager->selectTool(tools.value(0));
    emit nonQObjectSelected(object, typeName);
}

void Probe::markObjectAsFavorite(QObject *object)
{
    {
        QMutexLocker locker(Probe::objectLock());
        if (!Probe::instance()->isValidObject(object))
            return; // deleted in the slot
    }

    Q_EMIT objectFavorited(object);
}

void Probe::removeObjectAsFavorite(QObject *object)
{
    {
        QMutexLocker locker(Probe::objectLock());
        if (!Probe::instance()->isValidObject(object))
            return; // deleted in the slot
    }
    Q_EMIT objectUnfavorited(object);
}

void Probe::registerSignalSpyCallbackSet(const SignalSpyCallbackSet &callbacks)
{
    if (callbacks.isNull())
        return;
    m_signalSpyCallbacks.push_back(callbacks);
    setupSignalSpyCallbacks();
}

void Probe::setupSignalSpyCallbacks()
{
    // memory management is with us for Qt >= 5.14, therefore static here!
    static QSignalSpyCallbackSet cbs = { nullptr, nullptr, nullptr, nullptr };
    foreach (const auto &it, m_signalSpyCallbacks) {
        if (it.signalBeginCallback)
            cbs.signal_begin_callback = signal_begin_callback;
        if (it.signalEndCallback)
            cbs.signal_end_callback = signal_end_callback;
        if (it.slotBeginCallback)
            cbs.slot_begin_callback = slot_begin_callback;
        if (it.slotEndCallback)
            cbs.slot_end_callback = slot_end_callback;
    }
    qt_register_signal_spy_callbacks(&cbs);
}

template<typename Func>
void Probe::executeSignalCallback(const Func &func)
{
    std::for_each(instance()->m_signalSpyCallbacks.constBegin(),
                  instance()->m_signalSpyCallbacks.constEnd(),
                  func);
}

SourceLocation Probe::objectCreationSourceLocation(const QObject *object)
{
    QObject *key = const_cast<QObject *>(object);
    if (!s_listener()->constructionBacktracesForObjects.contains(key)) {
        IF_DEBUG(std::cout << "No backtrace for object available" << object << "." << std::endl;)
        return SourceLocation();
    }

    const auto &st = s_listener()->constructionBacktracesForObjects.value(key);
    int distanceToQObject = 0;

    const QMetaObject *metaObject = object->metaObject();
    while (metaObject && metaObject != &QObject::staticMetaObject) {
        distanceToQObject++;
        metaObject = metaObject->superClass();
    }

    const auto frame = Execution::resolveOne(st, distanceToQObject + 1);
    return frame.location;
}

Execution::Trace Probe::objectCreationStackTrace(QObject *object)
{
    return s_listener()->constructionBacktracesForObjects.value(object);
}