aboutsummaryrefslogtreecommitdiffstats
path: root/clang-plugin/printf_check.cc
blob: d8aeee82842d8e402d5828265e74c15b5673aa78 (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
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
/*-
 * Copyright 2016 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <sys/types.h>
#include "printf_check.h"
#include "clang/AST/AST.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <sstream>
#include <ctype.h>
#include <signal.h>
#include <assert.h>
#include <cstdint>

using namespace clang;

namespace rspamd {
	struct PrintfArgChecker;

	static bool cstring_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool int_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool long_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool size_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool char_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool double_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool long_double_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool pointer_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool pid_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool int64_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool int32_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool gboolean_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool tok_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool fstring_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool gstring_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	static bool gerr_arg_handler (const Expr *arg,
			struct PrintfArgChecker *ctx);

	using arg_parser_t = bool (*) (const Expr *, struct PrintfArgChecker *);

	static void
	print_error (const std::string &err, const Expr *e, const ASTContext *ast,
			CompilerInstance *ci)
	{
		auto loc = e->getExprLoc ();
		auto &diag = ci->getDiagnostics ();
		auto id = diag.getCustomDiagID (DiagnosticsEngine::Error,
				"format query error: %0");
		diag.Report (loc, id) << err;
	}

	static void
	print_warning (const std::string &err, const Expr *e, const ASTContext *ast,
			CompilerInstance *ci)
	{
		auto loc = e->getExprLoc ();
		auto &diag = ci->getDiagnostics ();
		auto id = diag.getCustomDiagID (DiagnosticsEngine::Warning,
				"format query warning: %0");
		diag.Report (loc, id) << err;
	}

	struct PrintfArgChecker {
	private:
		arg_parser_t parser;
	public:
		int width;
		int precision;
		bool is_unsigned;
		ASTContext *past;
		CompilerInstance *pci;

		PrintfArgChecker (arg_parser_t _p, ASTContext *_ast, CompilerInstance *_ci) :
				parser (_p), past (_ast), pci(_ci)
		{
			width = 0;
			precision = 0;
			is_unsigned = false;
		}

		virtual ~PrintfArgChecker ()
		{
		}

		bool operator() (const Expr *e)
		{
			return parser (e, this);
		}
	};

	class PrintfCheckVisitor::impl {
		std::unordered_map<std::string, unsigned int> printf_functions;
		std::unordered_set<char> format_specs;
		ASTContext *pcontext;
		CompilerInstance *ci;

		std::unique_ptr <PrintfArgChecker> parseFlags (const std::string &flags,
				const Expr *e)
		{
			auto type = flags.back ();

			switch (type) {
			case 's':
				return llvm::make_unique<PrintfArgChecker> (cstring_arg_handler,
						this->pcontext, this->ci);
			case 'd':
				return llvm::make_unique<PrintfArgChecker> (int_arg_handler,
						this->pcontext, this->ci);
			case 'z':
				return llvm::make_unique<PrintfArgChecker> (size_arg_handler,
						this->pcontext, this->ci);
			case 'l':
				return llvm::make_unique<PrintfArgChecker> (long_arg_handler,
						this->pcontext, this->ci);
			case 'f':
			case 'g':
				return llvm::make_unique<PrintfArgChecker> (double_arg_handler,
						this->pcontext, this->ci);
			case 'F':
			case 'G':
				return llvm::make_unique<PrintfArgChecker> (
						long_double_arg_handler,
						this->pcontext, this->ci);
			case 'c':
				return llvm::make_unique<PrintfArgChecker> (char_arg_handler,
						this->pcontext, this->ci);
			case 'p':
				return llvm::make_unique<PrintfArgChecker> (pointer_arg_handler,
						this->pcontext, this->ci);
			case 'P':
				return llvm::make_unique<PrintfArgChecker> (pid_arg_handler,
						this->pcontext, this->ci);
			case 'L':
				return llvm::make_unique<PrintfArgChecker> (int64_arg_handler,
						this->pcontext, this->ci);
			case 'D':
				return llvm::make_unique<PrintfArgChecker> (int32_arg_handler,
						this->pcontext, this->ci);
			case 'B':
				return llvm::make_unique<PrintfArgChecker> (gboolean_arg_handler,
						this->pcontext, this->ci);
			case 'T':
				return llvm::make_unique<PrintfArgChecker> (tok_arg_handler,
						this->pcontext, this->ci);
			case 'V':
				return llvm::make_unique<PrintfArgChecker> (fstring_arg_handler,
						this->pcontext, this->ci);
			case 'v':
				return llvm::make_unique<PrintfArgChecker> (gstring_arg_handler,
						this->pcontext, this->ci);
			case 'e':
				return llvm::make_unique<PrintfArgChecker> (gerr_arg_handler,
						this->pcontext, this->ci);
			default:
				print_warning (std::string("unknown parser flag: ") + type,
						e, this->pcontext, this->ci);
				break;
			}

			return nullptr;
		}

		std::shared_ptr <std::vector<PrintfArgChecker>>
		genParsers (const StringRef query, const Expr *e)
		{
			enum {
				ignore_chars = 0,
				read_percent,
				read_width,
				read_precision,
				read_arg
			} state = ignore_chars;
			int width, precision;
			std::string flags;

			auto res = std::make_shared<std::vector<PrintfArgChecker> > ();

			for (auto citer = query.begin(); citer != query.end(); ++citer) {
				auto c = *citer;

				switch (state) {
				case ignore_chars:
					if (c == '%') {
						state = read_percent;
						flags.clear ();
						width = precision = 0;
					}
					break;
				case read_percent:
					if (isdigit (c)) {
						state = read_width;
						width = c - '0';
					}
					else if (c == '.') {
						state = read_precision;
						precision = c - '0';
					}
					else if (c == '*') {
						/* %*s - need integer argument */
						res->emplace_back (int_arg_handler, this->pcontext,
								this->ci);

						if (*std::next (citer) == '.') {
							++citer;
							state = read_precision;
						}
						else {
							state = read_arg;
						}
					}
					else if (c == '%') {
						/* Percent character, ignore */
						state = ignore_chars;
					}
					else {
						// Rewind iter
						--citer;
						state = read_arg;
					}
					break;
				case read_width:
					if (isdigit (c)) {
						width *= 10;
						width += c - '0';
					}
					else if (c == '.') {
						state = read_precision;
						precision = c - '0';
					}
					else {
						// Rewind iter
						--citer;
						state = read_arg;
					}
					break;
				case read_precision:
					if (isdigit (c)) {
						precision *= 10;
						precision += c - '0';
					}
					else if (c == '*') {
						res->emplace_back (int_arg_handler, this->pcontext,
								this->ci);
						state = read_arg;
					}
					else {
						// Rewind iter
						--citer;
						state = read_arg;
					}
					break;
				case read_arg:
					auto found = format_specs.find (c);
					if (found != format_specs.end () || !isalpha (c)) {

						if (isalpha (c)) {
							flags.push_back (c);
						}

						auto handler = parseFlags (flags, e);

						if (handler) {
							auto handler_copy = *handler;
							handler_copy.precision = precision;
							handler_copy.width = width;
							res->emplace_back (std::move (handler_copy));
						}
						else {
							return nullptr;
						}

						if (c == '%') {
							state = read_percent;
						}
						else {
							state = ignore_chars;
						}
						flags.clear ();
						width = precision = 0;
					}
					else {
						flags.push_back (c);
					}
					break;
				}
			}

			if (state == read_arg) {
				auto handler = parseFlags (flags, e);

				if (handler) {
					auto handler_copy = *handler;
					handler_copy.precision = precision;
					handler_copy.width = width;
					res->emplace_back (std::move (handler_copy));
				}
				else {
					return nullptr;
				}
			}

			return res;
		}

	public:
		impl (ASTContext *_ctx, clang::CompilerInstance &_ci)
				: pcontext (_ctx), ci(&_ci)
		{
			/* name -> format string position */
			printf_functions = {
					{"rspamd_printf",               0},
					{"rspamd_default_log_function", 4},
					{"rspamd_snprintf",             2},
					{"rspamd_fprintf",              1},
					{"rspamd_printf_gstring",       1},
					{"rspamd_printf_fstring",       1}
			};

			format_specs = {
					's', 'd', 'l', 'L', 'v', 'V', 'f', 'F', 'g', 'G',
					'T', 'z', 'D', 'c', 'p', 'P', 'e', 'B'
			};
		};

		bool VisitCallExpr (CallExpr *E)
		{
			auto callee = dyn_cast<NamedDecl> (E->getCalleeDecl ());
			if (callee == NULL) {
				llvm::errs () << "Bad callee\n";
				return false;
			}

			auto fname = callee->getNameAsString ();

			auto pos_it = printf_functions.find (fname);

			if (pos_it != printf_functions.end ()) {
				const auto args = E->getArgs ();
				auto pos = pos_it->second;
				auto query = args[pos];

				if (!query->isEvaluatable (*pcontext)) {
					print_warning (std::string ("cannot evaluate query"),
							E, this->pcontext, this->ci);
					return false;
				}

				clang::Expr::EvalResult r;

				if (!query->EvaluateAsRValue (r, *pcontext)) {
					print_warning (std::string ("cannot evaluate rvalue of query"),
							E, this->pcontext, this->ci);
					return false;
				}

				auto qval = dyn_cast<StringLiteral> (
						r.Val.getLValueBase ().get<const Expr *> ());
				if (!qval) {
					print_warning (std::string ("bad or absent query string"),
							E, this->pcontext, this->ci);
					return false;
				}

				auto parsers = genParsers (qval->getString (), E);

				if (parsers) {
					if (parsers->size () != E->getNumArgs () - (pos + 1)) {
						std::ostringstream err_buf;
						err_buf << "number of arguments for " << fname
								<< " missmatches query string '" <<
								qval->getString ().str ()
										<< "', expected " << parsers->size () <<
								" args"
										<< ", got " <<
								(E->getNumArgs () - (pos + 1))
										<< " args";
						print_error (err_buf.str (), E, this->pcontext, this->ci);

						return false;
					}
					else {
						for (auto i = pos + 1; i < E->getNumArgs (); i++) {
							auto arg = args[i];

							if (arg) {
								if (!parsers->at (i - (pos + 1)) (arg)) {
									return false;
								}
							}
						}
					}
				}
			}

			return true;
		}
	};

	PrintfCheckVisitor::PrintfCheckVisitor (ASTContext *ctx,
			clang::CompilerInstance &ci) :
			pimpl{new impl (ctx, ci)}
	{
	}

	PrintfCheckVisitor::~PrintfCheckVisitor ()
	{
	}

	bool PrintfCheckVisitor::VisitCallExpr (clang::CallExpr *E)
	{
		return pimpl->VisitCallExpr (E);
	}

	/* Type handlers */
	static bool
	cstring_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		auto type = arg->getType ().split ().Ty;

		if (!type->isPointerType ()) {
			print_error (
					std::string ("bad string argument for %s: ") +
					arg->getType ().getAsString (),
					arg, ctx->past, ctx->pci);
			return false;
		}

		auto ptr_type = type->getPointeeType ().split ().Ty;

		if (!ptr_type->isCharType ()) {
			/* We might have gchar * here */
			auto desugared_type = ptr_type->getUnqualifiedDesugaredType ();
			auto desugared_ptr_type = type->getUnqualifiedDesugaredType ();

			if (!desugared_type || (!desugared_type->isCharType () &&
						!desugared_ptr_type->isVoidPointerType ())) {
				if (desugared_type) {
					desugared_type->dump ();
				}
				print_error (
						std::string ("bad string argument for %s: ") +
								arg->getType ().getAsString (),
						arg, ctx->past, ctx->pci);
				return false;
			}
		}

		return true;
	}

	static bool
	check_builtin_type (const Expr *arg, struct PrintfArgChecker *ctx,
			const std::vector <BuiltinType::Kind> &k, const std::string &fmt)
	{
		auto type = arg->getType ().split ().Ty;

		auto desugared_type = type->getUnqualifiedDesugaredType ();

		if (!desugared_type->isBuiltinType ()) {
			print_error (
					std::string ("not a builtin type for ") + fmt + " arg: " +
							arg->getType ().getAsString (),
					arg, ctx->past, ctx->pci);
			return false;
		}

		auto builtin_type = dyn_cast<BuiltinType> (desugared_type);
		auto kind = builtin_type->getKind ();
		auto found = false;

		for (auto kk : k) {
			if (kind == kk) {
				found = true;
				break;
			}
		}

		if (!found) {
			print_error (
					std::string ("bad argument for ") + fmt + " arg: " +
					arg->getType ().getAsString () + ", resolved as: " +
					builtin_type->getNameAsCString (ctx->past->getPrintingPolicy ()),
					arg, ctx->past, ctx->pci);
			return false;
		}

		return true;
	}

	static bool
	int_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_builtin_type (arg,
				ctx,
				{BuiltinType::Kind::UInt,
				 BuiltinType::Kind::Int},
				"%d or *");
	}

	static bool
	long_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_builtin_type (arg,
				ctx,
				{BuiltinType::Kind::ULong,
				 BuiltinType::Kind::Long},
				"%l");
	}

	static bool
	char_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_builtin_type (arg,
				ctx,
				{BuiltinType::Kind::UChar,
				 BuiltinType::Kind::SChar,
				 BuiltinType::Kind::Int}, // Because of char -> int propagation
				"%c");
	}

	static bool
	size_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		if (sizeof (size_t) == sizeof (long)) {
			return check_builtin_type (arg,
					ctx,
					{BuiltinType::Kind::ULong,
					 BuiltinType::Kind::Long},
					"%z");
		}
		else if (sizeof (size_t) == sizeof (int)) {
			return check_builtin_type (arg,
					ctx,
					{BuiltinType::Kind::UInt,
					 BuiltinType::Kind::Int},
					"%z");
		}
		else {
			assert (0);
		}

		return true;
	}

	static bool
	double_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_builtin_type (arg,
				ctx,
				{BuiltinType::Kind::Double},
				"%f or %g");
	}

	static bool
	long_double_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_builtin_type (arg,
				ctx,
				{BuiltinType::Kind::LongDouble},
				"%F or %G");
	}

	static bool
	pid_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		if (sizeof (pid_t) == sizeof (long)) {
			return check_builtin_type (arg,
					ctx,
					{BuiltinType::Kind::ULong,
					 BuiltinType::Kind::Long},
					"%P");
		}
		else if (sizeof (pid_t) == sizeof (int)) {
			return check_builtin_type (arg,
					ctx,
					{BuiltinType::Kind::UInt,
					 BuiltinType::Kind::Int},
					"%P");
		}
		else {
			assert (0);
		}
	}

	static bool
	pointer_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		auto type = arg->getType ().split ().Ty;

		if (!type->isPointerType ()) {
			print_error (
					std::string ("bad pointer argument for %p: ") +
							arg->getType ().getAsString (),
					arg, ctx->past, ctx->pci);
			return false;
		}

		return true;
	}

	static bool
	int64_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		std::vector <BuiltinType::Kind> check;

		if (sizeof (int64_t) == sizeof (long long)) {
			check.push_back (BuiltinType::Kind::ULongLong);
			check.push_back (BuiltinType::Kind::LongLong);
		}
		if (sizeof (int64_t) == sizeof (long)) {
			check.push_back (BuiltinType::Kind::ULong);
			check.push_back (BuiltinType::Kind::Long);
		}

		return check_builtin_type (arg,
				ctx,
				check,
				"%L");

		return true;
	}

	static bool
	int32_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		std::vector < BuiltinType::Kind> check;

		if (sizeof (int32_t) == sizeof (long)) {
			check.push_back (BuiltinType::Kind::ULong);
			check.push_back (BuiltinType::Kind::Long);
		}
		if (sizeof (int32_t) == sizeof (int)) {
			check.push_back (BuiltinType::Kind::UInt);
			check.push_back (BuiltinType::Kind::Int);
		}

		return check_builtin_type (arg,
				ctx,
				check,
				"%D");

		return true;
	}

	static bool
	gboolean_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_builtin_type (arg,
				ctx,
				{BuiltinType::Kind::Int}, // gboolean is int in fact
				"%b");
	}

	static bool
	check_struct_type (const Expr *arg, struct PrintfArgChecker *ctx,
			const std::string &sname, const std::string &fmt)
	{
		auto type = arg->getType ().split ().Ty;

		if (!type->isPointerType ()) {
			print_error (
					std::string ("bad string argument for %s: ") +
							arg->getType ().getAsString (),
					arg, ctx->past, ctx->pci);
			return false;
		}

		auto ptr_type = type->getPointeeType ().split ().Ty;
		auto desugared_type = ptr_type->getUnqualifiedDesugaredType ();

		if (!desugared_type->isRecordType ()) {
			print_error (
					std::string ("not a record type for ") + fmt + " arg: " +
							arg->getType ().getAsString (),
					arg, ctx->past, ctx->pci);
			return false;
		}

		auto struct_type = desugared_type->getAsStructureType ();
		auto struct_decl = struct_type->getDecl ();
		auto struct_def = struct_decl->getNameAsString ();

		if (struct_def != sname) {
			print_error (std::string ("bad argument '") + struct_def + "' for "
					+ fmt + " arg: " +
					arg->getType ().getAsString (),
					arg, ctx->past, ctx->pci);
			return false;
		}

		return true;
	}

	static bool
	tok_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_struct_type (arg,
				ctx,
				"f_str_tok",
				"%T");
	}

	static bool
	fstring_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_struct_type (arg,
				ctx,
				"f_str_s",
				"%V");
	}

	static bool
	gstring_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_struct_type (arg,
				ctx,
				"_GString",
				"%v");
	}

	static bool
	gerr_arg_handler (const Expr *arg, struct PrintfArgChecker *ctx)
	{
		return check_struct_type (arg,
				ctx,
				"_GError",
				"%e");
	}
};