summaryrefslogtreecommitdiff
path: root/compilerplugins/clang/dyncastvisibility.cxx
blob: 7d6b19aa6e24524c49b9a6b6b9595191c3fa9af5 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef LO_CLANG_SHARED_PLUGINS

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <set>
#include <string>

#include "config_clang.h"

#include "plugin.hxx"

namespace {

using Bases = std::set<CXXRecordDecl const *>;

Visibility getTypeVisibility(CXXRecordDecl const * decl) {
    assert(decl->isThisDeclarationADefinition());
    if (auto const opt = decl->getExplicitVisibility(
            NamedDecl::VisibilityForType))
    {
        return *opt;
    }
    if (auto const opt = decl->getExplicitVisibility(
            NamedDecl::VisibilityForValue))
    {
        return *opt;
    }
    auto const visi = decl->getVisibility();
    return visi == DefaultVisibility && decl->isInAnonymousNamespace()
        ? HiddenVisibility : visi;
}

// Check whether 'decl' is derived from 'base', gathering any 'bases' between
// 'decl' and 'base', and whether any of those 'bases' or 'base' are 'hidden'
// (i.e., have non-default visibility):
bool isDerivedFrom(
    CXXRecordDecl const * decl, CXXRecordDecl const * base, Bases * bases,
    bool * hidden)
{
    bool derived = false;
    for (auto const & i: decl->bases()) {
        auto const bd
            = (cast<CXXRecordDecl>(i.getType()->getAs<RecordType>()->getDecl())
               ->getDefinition());
        assert(bd != nullptr);
        if (bd == base) {
            *hidden |= getTypeVisibility(base) != DefaultVisibility;
            derived = true;
        }
        else if (bd->isDerivedFrom(base)) {
            if (bases->insert(bd).second) {
                auto const d = isDerivedFrom(bd, base, bases, hidden);
                assert(d);
                (void)d;
                *hidden |= getTypeVisibility(bd) != DefaultVisibility;
            }
            derived = true;
        }
    }
    return derived;
}

StringRef vis(Visibility v) {
    switch (v) {
    case HiddenVisibility:
        return "hidden";
    case ProtectedVisibility:
        return "protected";
    case DefaultVisibility:
        return "default";
    }
    llvm_unreachable("unknown visibility");
}

class DynCastVisibility final:
    public loplugin::FilteringPlugin<DynCastVisibility>
{
public:
    explicit DynCastVisibility(loplugin::InstantiationData const & data):
        FilteringPlugin(data) {}

    bool shouldVisitTemplateInstantiations() const { return true; }

    bool VisitCXXDynamicCastExpr(CXXDynamicCastExpr const * expr) {
        if (ignoreLocation(expr)) {
            return true;
        }
        auto td = expr->getTypeAsWritten();
        if (auto const t = td->getAs<ReferenceType>()) {
            td = t->getPointeeType();
        }
        while (auto const t = td->getAs<clang::PointerType>()) {
            td = t->getPointeeType();
        }
        auto const rtd = td->getAs<RecordType>();
        if (rtd == nullptr) {
            return true;
        }
        auto const rdd = cast<CXXRecordDecl>(rtd->getDecl())->getDefinition();
        if (rdd == nullptr) {
            return true;
        }
        if (getTypeVisibility(rdd) != DefaultVisibility) {
            // Heuristic to find problematic dynamic_cast<T> with hidden type T is: T is defined in
            // include/M1/ while the compilation unit is in module M2/ with M1 != M2.  There are
            // legitimate cases where T is a hidden type in dynamic_cast<T>, e.g., when both the
            // type and the cast are in the same library.  This heuristic appears to be conservative
            // enough to produce only a few false positives (which have been addressed with
            // preceding commits, marking the relevant types in global include files as
            // SAL_DLLPUBLIC_RTTI after all, to be on the safe side) and aggressive enough to find
            // at least some interesting cases (though it would still not be aggressive enough to
            // have found ff570b4b58dbf274d3094d21d974f18b613e9b4b "DocumentSettingsSerializer must
            // be SAL_DLLPUBLIC_RTTI for dynamic_cast"):
            auto const file = getFilenameOfLocation(
                compiler.getSourceManager().getSpellingLoc(rdd->getLocation()));
            if (loplugin::hasPathnamePrefix(file, SRCDIR "/include/")) {
                std::size_t const n1 = std::strlen(SRCDIR "/include/");
                std::size_t n2 = file.find('/', n1);
#if defined _WIN32
                n2 = std::min(n2, file.find('\\', n1));
#endif
                auto const seg = n2 >= file.size() ? file.substr(n1) : file.substr(n1, n2 - n1);
                auto prefix = std::string(SRCDIR "/");
                prefix += seg;
                if (!loplugin::hasPathnamePrefix(
                            handler.getMainFileName(), prefix))
                {
                    report(
                        DiagnosticsEngine::Warning,
                        "Suspicious dynamic_cast to %0 with %1 type visibility", expr->getExprLoc())
                        << td << vis(getTypeVisibility(rdd)) << expr->getSourceRange();
                    report(DiagnosticsEngine::Note, "class %0 defined here", rdd->getLocation())
                        << td << rdd->getSourceRange();
                }
            }
            return true;
        }
        auto ts = expr->getSubExpr()->getType();
        while (auto const t = ts->getAs<clang::PointerType>()) {
            ts = t->getPointeeType();
        }
        auto const rts = ts->getAs<RecordType>();
        if (rts == nullptr) { // in case it's a dependent type
            return true;
        }
        auto const rds = cast<CXXRecordDecl>(rts->getDecl())->getDefinition();
        assert(rds != nullptr);
        Bases bs;
        bool hidden = false;
        if (!(isDerivedFrom(rdd, rds, &bs, &hidden) && hidden)) {
            return true;
        }
        report(
            DiagnosticsEngine::Warning,
            ("dynamic_cast from %0 with %1 type visibility to %2 with %3 type"
             " visibility"),
            expr->getExprLoc())
            << ts << vis(getTypeVisibility(rds)) << td
            << vis(getTypeVisibility(rdd)) << expr->getSourceRange();
        report(
            DiagnosticsEngine::Note,
            "base class %0 with %1 type visibility defined here",
            rds->getLocation())
            << ts << vis(getTypeVisibility(rds)) << rds->getSourceRange();
        for (auto const i: bs) {
            if (getTypeVisibility(i) != DefaultVisibility) {
                report(
                    DiagnosticsEngine::Note,
                    ("intermediary class %0 with %1 type visibility defined"
                     " here"),
                    i->getLocation())
                    << i << vis(getTypeVisibility(i)) << i->getSourceRange();
            }
        }
        report(
            DiagnosticsEngine::Note,
            "derived class %0 with %1 type visibility defined here",
            rdd->getLocation())
            << td << vis(getTypeVisibility(rdd)) << rdd->getSourceRange();
        return true;
    }

    virtual bool preRun() override {
        return compiler.getLangOpts().CPlusPlus;
    }
private:
    void run() override {
        if (preRun()) {
            TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
        }
    }
};

static loplugin::Plugin::Registration<DynCastVisibility> dyncastvisibility(
    "dyncastvisibility");

}

#endif // LO_CLANG_SHARED_PLUGINS

/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */