aboutsummaryrefslogtreecommitdiffstats
path: root/plugins/clangstaticanalyzer/clangstaticanalyzerruncontrol.cpp
blob: e0c7b11e716f0be34a8689573a91eca187993a73 (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
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
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc
** All rights reserved.
** For any questions to Digia, please use contact form at http://qt.digia.com <http://qt.digia.com/>
**
** This file is part of the Qt Enterprise LicenseChecker Add-on.
**
** Licensees holding valid Qt Enterprise licenses may use this file in
** accordance with the Qt Enterprise License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.
**
** If you have questions regarding the use of this file, please use
** contact form at http://qt.digia.com <http://qt.digia.com/>
**
****************************************************************************/

#include "clangstaticanalyzerruncontrol.h"

#include "clangstaticanalyzerlogfilereader.h"
#include "clangstaticanalyzerrunner.h"
#include "clangstaticanalyzersettings.h"
#include "clangstaticanalyzerutils.h"

#include <analyzerbase/analyzermanager.h>

#include <clangcodemodel/clangutils.h>

#include <coreplugin/progressmanager/futureprogress.h>
#include <coreplugin/progressmanager/progressmanager.h>

#include <cpptools/cppmodelmanager.h>
#include <cpptools/cppprojects.h>
#include <cpptools/cppprojectfile.h>

#include <projectexplorer/project.h>
#include <projectexplorer/target.h>

#include <QLoggingCategory>
#include <QTemporaryDir>

using namespace CppTools;
using namespace ProjectExplorer;

static Q_LOGGING_CATEGORY(LOG, "qtc.clangstaticanalyzer.runcontrol")

namespace ClangStaticAnalyzer {
namespace Internal {

ClangStaticAnalyzerRunControl::ClangStaticAnalyzerRunControl(
        const Analyzer::AnalyzerStartParameters &startParams,
        ProjectExplorer::RunConfiguration *runConfiguration)
    : AnalyzerRunControl(startParams, runConfiguration)
    , m_initialFilesToProcessSize(0)
{
}

static QList<ClangStaticAnalyzerRunControl::SourceFileConfiguration> calculateFilesToProcess(
            Project *project)
{
    typedef ClangStaticAnalyzerRunControl::SourceFileConfiguration SourceFileConfiguration;
    QTC_ASSERT(project, return QList<SourceFileConfiguration>());
    ProjectInfo projectInfo = CppModelManager::instance()->projectInfo(project);
    QTC_ASSERT(projectInfo, return QList<SourceFileConfiguration>());

    QList<SourceFileConfiguration> files;
    const QList<ProjectPart::Ptr> projectParts = projectInfo.projectParts();
    foreach (const ProjectPart::Ptr &projectPart, projectParts) {
        foreach (const ProjectFile &file, projectPart->files) {
            if (file.path == CppModelManager::configurationFileName())
                continue;
            QTC_CHECK(file.kind != ProjectFile::Unclassified);
            if (ProjectFile::isSource(file.kind))
                files << SourceFileConfiguration(file, projectPart);
        }
    }

    return files;
}

bool ClangStaticAnalyzerRunControl::startEngine()
{
    emit starting(this);

    RunConfiguration *runConfig = runConfiguration();
    QTC_ASSERT(runConfig, emit finished(); return false);
    Target *target = runConfig->target();
    QTC_ASSERT(target, emit finished(); return false);
    Project *project = target->project();
    QTC_ASSERT(project, emit finished(); return false);

    const QString projectFile = project->projectFilePath().toString();
    appendMessage(tr("Running Clang Static Analyzer on %1").arg(projectFile) + QLatin1Char('\n'),
                        Utils::NormalMessageFormat);

    // Check clang executable
    bool isValidClangExecutable;
    const QString executable = clangExecutableFromSettings(&isValidClangExecutable);
    if (!isValidClangExecutable) {
        emit appendMessage(tr("Clang Static Analyzer: Invalid executable \"%1\", stop.")
                            .arg(executable) + QLatin1Char('\n'),
                           Utils::ErrorMessageFormat);
        emit finished();
        return false;
    }
    m_clangExecutable = executable;

    // Create log dir
    QTemporaryDir temporaryDir(QDir::tempPath() + QLatin1String("/qtc-clangstaticanalyzer-XXXXXX"));
    temporaryDir.setAutoRemove(false);
    if (!temporaryDir.isValid()) {
        emit appendMessage(tr("Clang Static Analyzer: Failed to create temporary dir, stop.")
                           + QLatin1Char('\n'), Utils::ErrorMessageFormat);
        emit finished();
        return false;
    }
    m_clangLogFileDir = temporaryDir.path();

    // Collect files
    const QList<SourceFileConfiguration> filesToProcess = calculateFilesToProcess(project);
    qCDebug(LOG) << "Files to process:";
    foreach (const SourceFileConfiguration &fileConfig, filesToProcess) {
        qCDebug(LOG) << fileConfig.file.path + QLatin1String(" [")
                          + fileConfig.projectPart->projectFile + QLatin1Char(']');
    }
    m_filesToProcess = filesToProcess;
    m_initialFilesToProcessSize = m_filesToProcess.count();

    // Set up progress information
    using namespace Core;
    FutureProgress *futureProgress
        = ProgressManager::addTask(m_progress.future(), tr("Analyzing"), "ClangStaticAnalyzer");
    futureProgress->setKeepOnFinish(FutureProgress::HideOnFinish);
    connect(futureProgress, &FutureProgress::canceled,
            this, &ClangStaticAnalyzerRunControl::onProgressCanceled);
    m_progress.setProgressRange(0, m_initialFilesToProcessSize);
    m_progress.reportStarted();

    // Start process(es)
    m_runners.clear();
    const int parallelRuns = ClangStaticAnalyzerSettings::instance()->simultaneousProcesses();
    QTC_ASSERT(parallelRuns >= 1, emit finished(); return false);
    while (m_runners.size() < parallelRuns && !m_filesToProcess.isEmpty())
        analyzeNextFile();
    return true;
}

void ClangStaticAnalyzerRunControl::stopEngine()
{
    QSetIterator<ClangStaticAnalyzerRunner *> i(m_runners);
    while (i.hasNext()) {
        ClangStaticAnalyzerRunner *runner = i.next();
        QObject::disconnect(runner, 0, this, 0);
        delete runner;
    }
    m_runners.clear();
    m_filesToProcess.clear();
    analyzeNextFile(); // emits finished
}

void ClangStaticAnalyzerRunControl::analyzeNextFile()
{
    if (m_progress.isFinished())
        return; // The previous call already reported that we are finished.

    if (m_filesToProcess.isEmpty()) {
        if (m_runners.size() == 0) {
            appendMessage(tr("Clang Static Analyzer finished.") + QLatin1Char('\n'),
                          Utils::NormalMessageFormat);
            m_progress.reportFinished();
            emit finished();
        }
        return;
    }

    const SourceFileConfiguration config = m_filesToProcess.takeFirst();
    const QString filePath = config.file.path;
    const QStringList options = config.createClangOptions();

    ClangStaticAnalyzerRunner *runner = createRunner();
    m_runners.insert(runner);
    qCDebug(LOG) << "analyzeNextFile:" << filePath;
    QTC_ASSERT(runner->run(filePath, options), return);
}

ClangStaticAnalyzerRunner *ClangStaticAnalyzerRunControl::createRunner()
{
    QTC_ASSERT(!m_clangExecutable.isEmpty(), return 0);
    QTC_ASSERT(!m_clangLogFileDir.isEmpty(), return 0);

    ClangStaticAnalyzerRunner *runner
            = new ClangStaticAnalyzerRunner(m_clangExecutable, m_clangLogFileDir, this);
    connect(runner, &ClangStaticAnalyzerRunner::finishedWithSuccess,
            this, &ClangStaticAnalyzerRunControl::onRunnerFinishedWithSuccess);
    connect(runner, &ClangStaticAnalyzerRunner::finishedWithFailure,
            this, &ClangStaticAnalyzerRunControl::onRunnerFinishedWithFailure);
    return runner;
}

void ClangStaticAnalyzerRunControl::onRunnerFinishedWithSuccess(const QString &logFilePath)
{
    qCDebug(LOG) << "onRunnerFinishedWithSuccess:" << logFilePath;
    handleFinished();

    QString errorMessage;
    const QList<Diagnostic> diagnostics = LogFileReader::read(logFilePath, &errorMessage);
    QTC_CHECK(errorMessage.isEmpty());
    if (!errorMessage.isEmpty())
        qCDebug(LOG) << "onRunnerFinishedWithSuccess: Error reading log file:" << errorMessage;
    if (!diagnostics.isEmpty())
        emit newDiagnosticsAvailable(diagnostics);
}

void ClangStaticAnalyzerRunControl::onRunnerFinishedWithFailure(const QString &errorMessage,
                                                                const QString &errorDetails)
{
    qCDebug(LOG) << "onRunnerFinishedWithFailure:" << errorMessage << errorDetails;
    handleFinished();
}

void ClangStaticAnalyzerRunControl::handleFinished()
{
    m_runners.remove(qobject_cast<ClangStaticAnalyzerRunner *>(sender()));
    updateProgressValue();
    sender()->deleteLater();
    analyzeNextFile();
}

void ClangStaticAnalyzerRunControl::onProgressCanceled()
{
    Analyzer::AnalyzerManager::stopTool();
    m_progress.reportCanceled();
    m_progress.reportFinished();
}

void ClangStaticAnalyzerRunControl::updateProgressValue()
{
    m_progress.setProgressValue(m_initialFilesToProcessSize - m_filesToProcess.size());
}

QStringList ClangStaticAnalyzerRunControl::SourceFileConfiguration::createClangOptions() const
{
    QStringList result;

    const bool objcExt = projectPart->languageExtensions & ProjectPart::ObjectiveCExtensions;
    result += CppTools::CompilerOptionsBuilder::createLanguageOption(file.kind, objcExt);
    result += CppTools::CompilerOptionsBuilder::createOptionsForLanguage(
                                                    projectPart->languageVersion,
                                                    projectPart->languageExtensions);
    result += CppTools::CompilerOptionsBuilder::createDefineOptions(projectPart->toolchainDefines);
    result += CppTools::CompilerOptionsBuilder::createDefineOptions(projectPart->projectDefines);
    result += CppTools::CompilerOptionsBuilder::createHeaderPathOptions(projectPart->headerPaths);
    result += QLatin1String("-fPIC"); // TODO: Remove?

    return result;
}

} // namespace Internal
} // namespace ClangStaticAnalyzer