summaryrefslogtreecommitdiff
path: root/clang-plugin/plugin.cpp
blob: 9d0a69799f47fdc6230e000ea03774f40225fa12 (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
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
/* -*- Mode: C++; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/*
 * Tartan
 * Copyright © 2013 Collabora Ltd.
 *
 * Tartan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tartan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tartan.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *     Philip Withnall <philip.withnall@collabora.co.uk>
 */

#include "config.h"

#include <clang/Frontend/FrontendPluginRegistry.h>
#ifdef HAVE_LLVM_8_0
#include <clang/StaticAnalyzer/Frontend/CheckerRegistry.h>
#else
#include <clang/StaticAnalyzer/Core/CheckerRegistry.h>
#endif
#include <clang/AST/AST.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/MultiplexConsumer.h>
#include <llvm/Support/raw_ostream.h>

#include "debug.h"
#include "gir-attributes.h"
#include "gassert-attributes.h"
#include "gerror-checker.h"
#include "gsignal-checker.h"
#include "gvariant-checker.h"
#include "nullability-checker.h"

using namespace clang;

namespace tartan {

/* Global GIR manager shared between AST and path-sensitive checkers. */
std::shared_ptr<GirManager> global_gir_manager =
	std::make_shared<GirManager> ();

/**
 * Plugin core.
 */
class TartanAction : public PluginASTAction {
private:
	/* Enabling/Disabling checkers is implemented as a blocklist: all
	 * checkers are enabled by default, unless a --disable-checker argument
	 * specifically disables them (by listing their name in this set). */
	std::shared_ptr<std::unordered_set<std::string>> _disabled_checkers =
		std::make_shared<std::unordered_set<std::string>> ();

	/* Whether to limit output to only diagnostics. */
	enum {
		VERBOSITY_QUIET,
		VERBOSITY_NORMAL,
		VERBOSITY_VERBOSE,
	}_verbosity = VERBOSITY_NORMAL;

protected:
	/* Note: This is called before ParseArgs, and must transfer ownership
	 * of the ASTConsumer. The TartanAction object is destroyed immediately
	 * after this function call returns, so must be careful not to retain
	 * state which is needed by the consumers. */
	std::unique_ptr<ASTConsumer>
	CreateASTConsumer (CompilerInstance &compiler,
					   llvm::StringRef /* in_file */)
	{
		/* Try and prevent Tartan’s changes to the AST from actually
		 * affecting compilation. See bug: 844/04c. */
		if (compiler.getFrontendOpts ().ProgramAction !=
		    frontend::ActionKind::ParseSyntaxOnly &&
		    compiler.getFrontendOpts ().ProgramAction !=
		    frontend::ActionKind::RunAnalysis) {
			DiagnosticsEngine &d = compiler.getDiagnostics ();
			DiagnosticIDs &ids = *d.getDiagnosticIDs ();
			unsigned int id = ids.getCustomDiagID (
				(DiagnosticIDs::Level) DiagnosticsEngine::Error,
				"Tartan must only be enabled when in "
				"syntax-only or analysis modes.");
			d.Report (id);

			return std::make_unique<ASTConsumer> ();
		}

		std::vector<std::unique_ptr<ASTConsumer>> consumers;

		/* Annotaters. */
		consumers.push_back (std::unique_ptr<ASTConsumer> (
			new GirAttributesConsumer (global_gir_manager)));
		consumers.push_back (std::unique_ptr<ASTConsumer> (
			new GAssertAttributesConsumer ()));

		/* Checkers. */
		consumers.push_back (std::unique_ptr<ASTConsumer> (
			new NullabilityConsumer (compiler,
			                         global_gir_manager,
			                         this->_disabled_checkers)));
		consumers.push_back (std::unique_ptr<ASTConsumer> (
			new GVariantConsumer (compiler,
			                      global_gir_manager,
			                      this->_disabled_checkers)));
		consumers.push_back (std::unique_ptr<ASTConsumer> (
			new GSignalConsumer (compiler,
			                     global_gir_manager,
			                     this->_disabled_checkers)));
		consumers.push_back (std::unique_ptr<ASTConsumer> (
			new GirAttributesChecker (compiler,
			                          global_gir_manager,
			                          this->_disabled_checkers)));

		return std::make_unique<MultiplexConsumer> (std::move (consumers));
	}

private:
	bool
	_load_typelib (const CompilerInstance &CI,
	               const std::string& gi_namespace_and_version)
	{
		std::string::size_type p = gi_namespace_and_version.find ("-");

		if (p == std::string::npos) {
			/* Ignore it — probably a non-typelib file. */
			return false;
		}

		std::string gi_namespace =
			gi_namespace_and_version.substr (0, p);
		std::string gi_version =
			gi_namespace_and_version.substr (p + 1);

		DEBUG ("Loading typelib " + gi_namespace + " " + gi_version);

		/* Load the repository. */
		GError *error = NULL;

		global_gir_manager.get ()->load_namespace (gi_namespace,
		                                           gi_version,
		                                           &error);
		if (error != NULL &&
		    !g_error_matches (error, G_IREPOSITORY_ERROR,
		                      G_IREPOSITORY_ERROR_NAMESPACE_VERSION_CONFLICT)) {
			DiagnosticsEngine &d = CI.getDiagnostics ();
			DiagnosticIDs &ids = *d.getDiagnosticIDs ();
			unsigned int id = ids.getCustomDiagID (
				(DiagnosticIDs::Level) DiagnosticsEngine::Warning,
				"Fail to load GI repository ‘" + gi_namespace +
				"’ (version " + gi_version + "): " +
				error->message);
			d.Report (id);

			g_error_free (error);

			return false;
		}

		g_clear_error (&error);

		return true;
	}

	/* Load all the GI typelibs we can find. This shouldn’t take long, and
	 * saves the user having to specify which typelibs to use (or us having
	 * to try and work out which ones the user’s code uses by looking at
	 * #included files). */
	bool
	_load_gi_repositories (const CompilerInstance &CI)
	{
		GSList/*<unowned string>*/ *typelib_paths, *l;

		typelib_paths = g_irepository_get_search_path ();

		for (l = typelib_paths; l != NULL; l = l->next) {
			GDir *dir;
			const gchar *typelib_path, *typelib_filename;
			GError *error = NULL;

			typelib_path = (const gchar *) l->data;
			dir = g_dir_open (typelib_path, 0, &error);

			if (error != NULL) {
				/* Warn about the bogus include path and
				 * continue. */
				DiagnosticsEngine &d = CI.getDiagnostics ();

				unsigned int id = d.getCustomDiagID (
					DiagnosticsEngine::Warning,
					"Error opening typelib path ‘%0’: %1");
				d.Report (id)
					<< typelib_path
					<< error->message;

				continue;
			}

			while ((typelib_filename = g_dir_read_name (dir)) != NULL) {
				if (!g_str_has_suffix (typelib_filename, ".typelib")) {
					/* No ‘.typelib’ suffix — ignore. */
					continue;
				}

				/* Load the typelib. Ignore failure. */
				std::string _typelib_filename (typelib_filename);
				std::string::size_type last_dot = _typelib_filename.find_last_of (".");
				g_assert (last_dot != std::string::npos);

				std::string gi_namespace_and_version = _typelib_filename.substr (0, last_dot);
				this->_load_typelib (CI, gi_namespace_and_version);
			}

			g_dir_close (dir);
		}

		return true;
	}

protected:
	/* Parse command line arguments for the plugin. Note: This is called
	 * after CreateASTConsumer. */
	bool
	ParseArgs (const CompilerInstance &CI,
	           const std::vector<std::string>& args)
	{
		/* Enable the default set of checkers. */
		for (std::vector<std::string>::const_iterator it = args.begin();
		     it != args.end (); ++it) {
			std::string arg = *it;

			if (arg == "--help") {
				this->PrintHelp (llvm::outs ());
			} else if (arg == "--quiet") {
				this->_verbosity = VERBOSITY_QUIET;
			} else if (arg == "--verbose") {
				this->_verbosity = VERBOSITY_VERBOSE;
			} else if (arg == "--enable-checker") {
				const std::string checker = *(++it);
				if (checker == "all") {
					this->_disabled_checkers.get ()->clear ();
				} else {
					this->_disabled_checkers.get ()->erase (std::string (checker));
				}
			} else if (arg == "--disable-checker") {
				const std::string checker = *(++it);
				this->_disabled_checkers.get ()->insert (std::string (checker));
			} else if (arg == "--typelib-path") {
				g_irepository_prepend_search_path ((++it)->c_str ());
			}
		}

		/* Load all typelibs. */
		this->_load_gi_repositories (CI);

		/* Listen to the V environment variable (as standard in automake) too. */
		const char *v_value = getenv ("V");
		if (v_value != NULL && strcmp (v_value, "0") == 0) {
			this->_verbosity = VERBOSITY_QUIET;
		}

		/* Output a version message. */
		if (this->_verbosity > VERBOSITY_NORMAL) {
			llvm::outs () << "Tartan version " << VERSION << " "
			                 "compiled for LLVM " <<
			                 LLVM_CONFIG_VERSION << ".\n" <<
			                 "Disabled checkers: ";

			for (std::unordered_set<std::string>::const_iterator it = this->_disabled_checkers.get ()->begin ();
			     it != this->_disabled_checkers.get ()->end (); ++it) {
				std::string checker = *it;

				if (it != this->_disabled_checkers.get ()->begin ()) {
					llvm::outs () << ", ";
				}
				llvm::outs () << checker;
			}
			if (this->_disabled_checkers.get ()->begin () ==
			    this->_disabled_checkers.get ()->end ()) {
				llvm::outs () << "(none)";
			}

			llvm::outs () << "\n";
		}

		return true;
	}

	/* Print plugin-specific help. */
	void
	PrintHelp (llvm::raw_ostream& out)
	{
		/* TODO: i18n */
		out << "A plugin to enable extra static analysis checks and "
		       "warnings for C code which\nuses GLib, by making use of "
		       "GIR metadata and other GLib coding conventions.\n"
		       "\n"
		       "Arguments:\n"
		       "    --enable-checker [name]\n"
		       "        Enable the given Tartan checker, which may be "
		               "‘all’. All checkers are\n"
		       "        enabled by default.\n"
		       "    --disable-checker [name]\n"
		       "        Disable the given Tartan checker, which may be "
		               "‘all’. All checkers are\n"
		       "        enabled by default.\n"
		       "    --typelib-path [path]\n"
		       "        Add the given path to the search path for typelibs.\n"
		       "    --quiet\n"
		       "        Disable all plugin output except code "
		               "diagnostics (remarks,\n"
		       "        warnings and errors).\n"
		       "    --verbose\n"
		       "        Output additional versioning information.\n"
		       "\n"
		       "Usage:\n"
		       "    clang -cc1 -load /path/to/libtartan.so "
		           "-add-plugin tartan \\\n"
		           "-analyzer-checker tartan\\\n"
		       "        -plugin-arg-tartan --disable-checker \\\n"
		       "        -plugin-arg-tartan all \\\n"
		       "        -plugin-arg-tartan --enable-checker \\\n"
		       "        -plugin-arg-tartan gir-attributes\n";
	}

	bool
	shouldEraseOutputFiles ()
	{
		/* TODO: Make this conditional on an error occurring. */
		return false;
	}
};


/* Register the AST checkers with LLVM. */
static FrontendPluginRegistry::Add<TartanAction>
X("tartan", "add attributes and warnings using GLib-specific metadata");

/* Register the path-dependent plugins with Clang. */
extern "C"
void clang_registerCheckers (ento::CheckerRegistry &registry);

extern "C"
void clang_registerCheckers (ento::CheckerRegistry &registry) {
	registry.addChecker<GErrorChecker> ("tartan.GErrorChecker",
	                                    "Check GError API usage"
#ifdef HAVE_LLVM_8_0
	                                    , "http://www.freedesktop.org/software/tartan/"
#endif
	                                    );
}

extern "C"
const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING;

} /* namespace tartan */