From 2db7c6e1a34f8ce24a735aad767d678c25514960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Tue, 3 Apr 2018 13:35:19 +0200 Subject: [PATCH] cert.py: Add rule EXP-05: do not cast away const --- addons/cert.py | 46 +++++++++++++++++++++++++++++++++++++++++ addons/test/cert-test.c | 12 +++++++++++ 2 files changed, 58 insertions(+) diff --git a/addons/cert.py b/addons/cert.py index 469b159df..96d3e131b 100755 --- a/addons/cert.py +++ b/addons/cert.py @@ -70,6 +70,51 @@ def isCast(expr): return False return True +# Get function arguments +def getArgumentsRecursive(tok, arguments): + if tok is None: + return + if tok.str == ',': + getArgumentsRecursive(tok.astOperand1, arguments) + getArgumentsRecursive(tok.astOperand2, arguments) + else: + arguments.append(tok); + +def getArguments(ftok): + arguments = [] + getArgumentsRecursive(ftok.astOperand2, arguments) + return arguments + +# EXP05-C +# do not attempt to cast away const +def exp05(data): + for token in data.tokenlist: + if isCast(token): + # C-style cast + if not token.valueType: + continue + if not token.astOperand1.valueType: + continue + const1 = token.valueType.constness + const2 = token.astOperand1.valueType.constness + if (const1 % 2) < (const2 % 2): + reportError(token, 'style', "Attempt to cast away const", 'cert-EXP05-C') + + elif token.str == '(' and token.astOperand1 and token.astOperand2 and token.astOperand1.function: + function = token.astOperand1.function + arguments = getArguments(token) + for argnr, argvar in function.argument.items(): + if argnr < 1 or argnr > len(arguments): + continue + argtok = arguments[argnr - 1] + if not argtok.valueType: + continue + const1 = argvar.isConst + const2 = arguments[argnr - 1].valueType.constness + if (const1 % 2) < (const2 % 2): + reportError(token, 'style', "Attempt to cast away const", 'cert-EXP05-C') + + # EXP42-C # do not compare padding data def exp42(data): @@ -178,6 +223,7 @@ for arg in sys.argv[1:]: for cfg in data.configurations: if len(data.configurations) > 1: print('Checking ' + arg + ', config "' + cfg.name + '"...') + exp05(cfg) exp42(cfg) exp46(cfg) int31(cfg, data.platform) diff --git a/addons/test/cert-test.c b/addons/test/cert-test.c index 4b24841c1..22fc9c42e 100644 --- a/addons/test/cert-test.c +++ b/addons/test/cert-test.c @@ -12,6 +12,18 @@ struct PackedStruct { short b; }; +void dostuff(int *data); + +void exp05() +{ + const int x = 42; + int *p; + p = (int *)&x; // cert-EXP05-C + + const int data[] = {1,2,3,4}; + dostuff(data); // cert-EXP05-C +} + void exp42() { struct S s1 = {1,2};