-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathmisra.py
executable file
·5004 lines (4448 loc) · 199 KB
/
misra.py
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# MISRA C 2012 checkers (including amendment 1 and 2)
#
# Example usage of this addon (scan a sourcefile main.cpp)
# cppcheck --dump main.cpp
# python misra.py --rule-texts=<path-to-rule-texts> main.cpp.dump
#
# Limitations: This addon is released as open source. We are not allowed by
# MISRA to distribute rule texts openly.
#
# The MISRA standard documents may be obtained from https://www.misra.org.uk
#
# Total number of rules: 143
from __future__ import print_function
import cppcheckdata
import itertools
import json
import sys
import re
import os
import argparse
import codecs
import string
import copy
try:
from itertools import izip as zip
except ImportError:
pass
import misra_9
def grouped(iterable, n):
"""s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."""
return zip(*[iter(iterable)] * n)
INT_TYPES = ['bool', 'char', 'short', 'int', 'long', 'long long']
STDINT_TYPES = ['%s%d_t' % (n, v) for n, v in itertools.product(
['int', 'uint', 'int_least', 'uint_least', 'int_fast', 'uint_fast'],
[8, 16, 32, 64])]
typeBits = {
'CHAR': None,
'SHORT': None,
'INT': None,
'LONG': None,
'LONG_LONG': None,
'POINTER': None
}
def isUnsignedType(ty):
return ty == 'unsigned' or ty.startswith('uint')
def simpleMatch(token, pattern):
return cppcheckdata.simpleMatch(token, pattern)
def rawlink(rawtoken):
if rawtoken.str == '}':
indent = 0
while rawtoken:
if rawtoken.str == '}':
indent = indent + 1
elif rawtoken.str == '{':
indent = indent - 1
if indent == 0:
break
rawtoken = rawtoken.previous
else:
rawtoken = None
return rawtoken
# Identifiers described in Section 7 "Library" of C90 Standard
# Based on ISO/IEC9899:1990 Annex D -- Library summary and
# Annex E -- Implementation limits.
C90_STDLIB_IDENTIFIERS = {
# D.1 Errors
'errno.h': ['EDOM', 'ERANGE', 'errno'],
# D.2 Common definitions
'stddef.h': ['NULL', 'offsetof', 'ptrdiff_t', 'size_t', 'wchar_t'],
# D.3 Diagnostics
'assert.h': ['NDEBUG', 'assert'],
# D.4 Character handling
'ctype.h': [
'isalnum', 'isalpha', 'isblank', 'iscntrl', 'isdigit',
'isgraph', 'islower', 'isprint', 'ispunct', 'isspace',
'isupper', 'isxdigit', 'tolower', 'toupper',
],
# D.5 Localization
'locale.h': [
'LC_ALL', 'LC_COLLATE', 'LC_CTYPE', 'LC_MONETARY',
'LC_NUMERIC', 'LC_TIME', 'NULL', 'lconv',
'setlocale', 'localeconv',
],
# D.6 Mathematics
'math.h': [
'HUGE_VAL', 'acos', 'asin' , 'atan2', 'cos', 'sin', 'tan', 'cosh',
'sinh', 'tanh', 'exp', 'frexp', 'ldexp', 'log', 'loglO', 'modf',
'pow', 'sqrt', 'ceil', 'fabs', 'floor', 'fmod',
],
# D.7 Nonlocal jumps
'setjmp.h': ['jmp_buf', 'setjmp', 'longjmp'],
# D.8 Signal handling
'signal.h': [
'sig_atomic_t', 'SIG_DFL', 'SIG_ERR', 'SIG_IGN', 'SIGABRT', 'SIGFPE',
'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'signal', 'raise',
],
# D.9 Variable arguments
'stdarg.h': ['va_list', 'va_start', 'va_arg', 'va_end'],
# D.10 Input/output
'stdio.h': [
'_IOFBF', '_IOLBF', '_IONBF', 'BUFSIZ', 'EOF', 'FILE', 'FILENAME_MAX',
'FOPEN_MAX', 'fpos_t', 'L_tmpnam', 'NULL', 'SEEK_CUR', 'SEEK_END',
'SEEK_SET', 'size_t', 'stderr', 'stdin', 'stdout', 'TMP_MAX',
'remove', 'rename', 'tmpfile', 'tmpnam', 'fclose', 'fflush', 'fopen',
'freopen', 'setbuf', 'setvbuf', 'fprintf', 'fscanf', 'printf',
'scanf', 'sprintf', 'sscanf', 'vfprintf', 'vprintf', 'vsprintf',
'fgetc', 'fgets', 'fputc', 'fputs', 'getc', 'getchar', 'gets', 'putc',
'putchar', 'puts', 'ungetc', 'fread', 'fwrite', 'fgetpos', 'fseek',
'fsetpos', 'rewind', 'clearerr', 'feof', 'ferror', 'perror',
],
# D.11 General utilities
'stdlib.h': [
'EXIT_FAILURE', 'EXIT_SUCCESS', 'MB_CUR_MAX', 'NULL', 'RAND_MAX',
'div_t', 'ldiv_t', 'wchar_t', 'atof', 'atoi', 'strtod', 'rand',
'srand', 'calloc', 'free', 'malloc', 'realloc', 'abort', 'atexit',
'exit', 'getenv', 'system', 'bsearch', 'qsort', 'abs', 'div', 'ldiv',
'mblen', 'mbtowc', 'wctomb', 'mbstowcs', 'wcstombs',
],
# D.12 String handling
'string.h': [
'NULL', 'size_t', 'memcpy', 'memmove', 'strcpy', 'strncpy', 'strcat',
'strncat', 'memcmp', 'strcmp', 'strcoll', 'strncmp', 'strxfrm',
'memchr', 'strchr', 'strcspn', 'strpbrk', 'strrchr', 'strspn',
'strstr', 'strtok', 'memset', 'strerror', 'strlen',
],
# D.13 Date and time
'time.h': [
'CLK_TCK', 'NULL', 'clock_t', 'time_t', 'size_t', 'tm', 'clock',
'difftime', 'mktime', 'time', 'asctime', 'ctime', 'gmtime',
'localtime', 'strftime',
],
# Annex E: Implementation limits
'limits.h': [
'CHAR_BIT', 'SCHAR_MIN', 'SCHAR_MAX', 'UCHAR_MAX', 'CHAR_MIN',
'CHAR_MAX', 'MB_LEN_MAX', 'SHRT_MIN', 'SHRT_MAX', 'USHRT_MAX',
'INT_MIN', 'INT_MAX', 'UINT_MAX', 'LONG_MIN', 'LONG_MAX', 'ULONG_MAX',
],
'float.h': [
'FLT_ROUNDS', 'FLT_RADIX', 'FLT_MANT_DIG', 'DBL_MANT_DIG',
'LDBL_MANT_DIG', 'DECIMAL_DIG', 'FLT_DIG', 'DBL_DIG', 'LDBL_DIG',
'DBL_MIN_EXP', 'LDBL_MIN_EXP', 'FLT_MIN_10_EXP', 'DBL_MIN_10_EXP',
'LDBL_MIN_10_EXP', 'FLT_MAX_EXP', 'DBL_MAX_EXP', 'LDBL_MAX_EXP',
'FLT_MAX_10_EXP', 'DBL_MAX_10_EXP', 'LDBL_MAX_10_EXP', 'FLT_MAX',
'DBL_MAX', 'LDBL_MAX', 'FLT_MIN', 'DBL_MIN', 'LDBL_MIN',
'FLT_EPSILON', 'DBL_EPSILON', 'LDBL_EPSILON'
],
}
# Identifiers described in Section 7 "Library" of C99 Standard
# Based on ISO/IEC 9899 WF14/N1256 Annex B -- Library summary
C99_STDLIB_IDENTIFIERS = {
# B.1 Diagnostics
'assert.h': C90_STDLIB_IDENTIFIERS['assert.h'],
# B.2 Complex
'complex.h': [
'complex', 'imaginary', 'I', '_Complex_I', '_Imaginary_I',
'CX_LIMITED_RANGE',
'cacos', 'cacosf', 'cacosl',
'casin', 'casinf', 'casinl',
'catan', 'catanf', 'catanl',
'ccos', 'ccosf', 'ccosl',
'csin', 'csinf', 'csinl',
'ctan', 'ctanf', 'ctanl',
'cacosh', 'cacoshf', 'cacoshl',
'casinh', 'casinhf', 'casinhl',
'catanh', 'catanhf', 'catanhl',
'ccosh', 'ccoshf', 'ccoshl',
'csinh', 'csinhf', 'csinhl',
'ctanh', 'ctanhf', 'ctanhl',
'cexp', 'cexpf', 'cexpl',
'clog', 'clogf', 'clogl',
'cabs', 'cabsf', 'cabsl',
'cpow', 'cpowf', 'cpowl',
'csqrt', 'csqrtf', 'csqrtl',
'carg', 'cargf', 'cargl',
'cimag', 'cimagf', 'cimagl',
'conj', 'conjf', 'conjl',
'cproj', 'cprojf', 'cprojl',
'creal', 'crealf', 'creall',
],
# B.3 Character handling
'ctype.h': C90_STDLIB_IDENTIFIERS['ctype.h'],
# B.4 Errors
'errno.h': C90_STDLIB_IDENTIFIERS['errno.h'] + ['EILSEQ'],
# B.5 Floating-point environment
'fenv.h': [
'fenv_t', 'FE_OVERFLOW', 'FE_TOWARDZERO',
'fexcept_t', 'FE_UNDERFLOW', 'FE_UPWARD',
'FE_DIVBYZERO', 'FE_ALL_EXCEPT', 'FE_DFL_ENV',
'FE_INEXACT', 'FE_DOWNWARD',
'FE_INVALID', 'FE_TONEAREST',
'FENV_ACCESS',
'feclearexcept', 'fegetexceptflag', 'fegetround',
'fesetround', 'fegetenv', 'feholdexcept',
'fesetenv', 'feupdateenv',
],
# B.6 Characteristics of floating types
'float.h': C90_STDLIB_IDENTIFIERS['float.h'] + ['FLT_EVAL_METHOD'],
# B.7 Format conversion of integer types
'inttypes.h': [
'imaxdiv_t', 'imaxabs', 'imaxdiv', 'strtoimax',
'strtoumax', 'wcstoimax', 'wcstoumax',
],
# B.8 Alternative spellings
'iso646.h': [
'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not', 'not_eq',
'or', 'or_eq', 'xor', 'xor_eq',
],
# B.9 Size of integer types
'limits.h': C90_STDLIB_IDENTIFIERS['limits.h'] +
['LLONG_MIN', 'LLONG_MAX', 'ULLONG_MAX'],
# B.10 Localization
'locale.h': C90_STDLIB_IDENTIFIERS['locale.h'],
# B.11 Mathematics
'math.h': C90_STDLIB_IDENTIFIERS['math.h'] + [
'float_t', 'double_t', 'HUGE_VAL', 'HUGE_VALF', 'HUGE_VALL',
'INFINITY', 'NAN', 'FP_INFINITE', 'FP_NAN', 'FP_NORMAL',
'FP_SUBNORMAL', 'FP_ZERO', 'FP_FAST_FMA', 'FP_FAST_FMAF',
'FP_FAST_FMAL', 'FP_ILOGB0', 'FP_ILOGBNAN', 'MATH_ERRNO',
'MATH_ERREXCEPT', 'math_errhandling', 'FP_CONTRACT', 'fpclassify',
'isfinite', 'isinf', 'isnan', 'isnormal', 'signbit', 'acosf', 'acosl',
'asinf', 'asinl', 'atanf', 'atanl', 'atan2', 'atan2f', 'atan2l',
'cosf', 'cosl', 'sinf', 'sinl', 'tanf', 'tanl', 'acosh', 'acoshf',
'acoshl', 'asinh', 'asinhf', 'asinhl', 'atanh', 'atanhf', 'atanhl',
'cosh', 'coshf', 'coshl', 'sinh', 'sinhf', 'sinhl', 'tanh', 'tanhf',
'tanhl', 'expf', 'expl', 'exp2', 'exp2f', 'exp2l', 'expm1', 'expm1f',
'expm1l', 'frexpf', 'frexpl', 'ilogb', 'ilogbf', 'ilogbl', 'float',
'ldexpl', 'logf', 'logl', 'log10f', 'log10l', 'log1p', 'log1pf',
'log1pl', 'log2', 'log2f', 'log2l', 'logb', 'logbf', 'logbl', 'modff',
'modfl', 'scalbn', 'scalbnf', 'scalbnl', 'scalbln', 'scalblnf',
'scalblnl', 'hypotl', 'powf', 'powl', 'sqrtf', 'sqrtl', 'erf', 'erff',
'erfl', 'erfc', 'erfcf', 'erfcl', 'lgamma', 'lgammaf', 'lgammal',
'tgamma', 'tgammaf', 'tgammal', 'ceilf', 'ceill', 'floorf', 'floorl',
'nearbyint', 'nearbyintf', 'nearbyintl', 'rint', 'rintf', 'rintl',
'lrint', 'lrintf', 'lrintl', 'llrint', 'llrintf', 'llrintl', 'round',
'roundf', 'roundl', 'lround', 'lroundf', 'lroundl', 'llround',
'llroundf', 'llroundl', 'trunc', 'truncf', 'truncl', 'fmodf', 'fmodl',
'remainder', 'remainderf', 'remainderl', 'remquo', 'remquof',
'remquol', 'copysign', 'copysignf', 'copysignl', 'nan', 'nanf',
'nanl', 'nextafter', 'nextafterf', 'nextafterl', 'nexttoward',
'nexttowardf', 'nexttowardl', 'fdim', 'fdimf', 'fdiml', 'fmax',
'fmaxf', 'fmaxl', 'fmin', 'fminf', 'fminl', 'fmal', 'isgreater',
'isgreaterequal', 'isless', 'islessequal', 'islessgreater',
'isunordered',
],
# B.12 Nonlocal jumps
'setjmp.h': C90_STDLIB_IDENTIFIERS['setjmp.h'],
# B.13 Signal handling
'signal.h': C90_STDLIB_IDENTIFIERS['signal.h'],
# B.14 Variable arguments
'stdarg.h': C90_STDLIB_IDENTIFIERS['stdarg.h'] + ['va_copy'],
# B.15 Boolean type and values
'stdbool.h': ['bool', 'true', 'false', '__bool_true_false_are_defined'],
# B.16 Common definitions
'stddef.h': C90_STDLIB_IDENTIFIERS['stddef.h'],
# B.17 Integer types
'stdint.h': [
'intptr_t', 'uintptr_t', 'intmax_t', 'uintmax_t', 'INTN_MIN',
'INTN_MAX', 'UINTN_MAX', 'INT_LEASTN_MIN', 'INT_LEASTN_MAX',
'UINT_LEASTN_MAX', 'INT_FASTN_MIN', 'INT_FASTN_MAX', 'UINT_FASTN_MAX',
'INTPTR_MIN', 'INTPTR_MAX', 'UINTPTR_MAX', 'INTMAX_MIN', 'INTMAX_MAX',
'UINTMAX_MAX', 'PTRDIFF_MIN', 'PTRDIFF_MAX', 'SIG_ATOMIC_MIN',
'SIG_ATOMIC_MAX', 'SIZE_MAX', 'WCHAR_MIN', 'WCHAR_MAX', 'WINT_MIN',
'WINT_MAX', 'INTN_C', 'UINTN_C', 'INTMAX_C', 'UINTMAX_C',
] + STDINT_TYPES,
# B.18 Input/output
'stdio.h': C90_STDLIB_IDENTIFIERS['stdio.h'] + [
'mode', 'restrict', 'snprintf', 'vfscanf', 'vscanf',
'vsnprintf', 'vsscanf',
],
# B.19 General utilities
'stdlib.h': C90_STDLIB_IDENTIFIERS['stdlib.h'] + [
'_Exit', 'labs', 'llabs', 'lldiv', 'lldiv_t', 'strtof', 'strtol',
'strtold', 'strtoll', 'strtoul', 'strtoull'
],
# B.20 String handling
'string.h': C90_STDLIB_IDENTIFIERS['string.h'],
# B.21 Type-generic math
'tgmath.h': [
'acos', 'asin', 'atan', 'acosh', 'asinh', 'atanh', 'cos', 'sin', 'tan',
'cosh', 'sinh', 'tanh', 'exp', 'log', 'pow', 'sqrt', 'fabs', 'atan2',
'cbrt', 'ceil', 'copysign', 'erf', 'erfc', 'exp2', 'expm1', 'fdim',
'floor', 'fma', 'fmax', 'fmin', 'fmod', 'frexp', 'hypot', 'ilogb',
'ldexp', 'lgamma', 'llrint', 'llround', 'log10', 'log1p', 'log2',
'logb', 'lrint', 'lround', 'nearbyint', 'nextafter', 'nexttoward',
'remainder', 'remquo', 'rint', 'round', 'scalbn', 'scalbln', 'tgamma',
'trunc', 'carg', 'cimag', 'conj', 'cproj', 'creal',
],
# B.22 Date and time
'time.h': C90_STDLIB_IDENTIFIERS['time.h'] + ['CLOCKS_PER_SEC'],
# B.23 Extended multibyte/wide character utilities
'wchar.h': [
'wchar_t', 'size_t', 'mbstate_t', 'wint_t', 'tm', 'NULL', 'WCHAR_MAX',
'WCHAR_MIN', 'WEOF', 'fwprintf', 'fwscanf', 'swprintf', 'swscanf',
'vfwprintf', 'vfwscanf', 'vswprintf', 'vswscanf', 'vwprintf',
'vwscanf', 'wprintf', 'wscanf', 'fgetwc', 'fgetws', 'fputwc', 'fputws',
'fwide', 'getwc', 'getwchar', 'putwc', 'putwchar', 'ungetwc', 'wcstod',
'wcstof', 'double', 'int', 'long', 'long', 'long', 'wcscpy', 'wcsncpy',
'wmemcpy', 'wmemmove', 'wcscat', 'wcsncat', 'wcscmp', 'wcscoll',
'wcsncmp', 'wcsxfrm', 'wmemcmp', 'wcschr', 'wcscspn', 'wcspbrk',
'wcsrchr', 'wcsspn', 'wcsstr', 'wcstok', 'wmemchr', 'wcslen',
'wmemset', 'wcsftime', 'btowc', 'wctob', 'mbsinit', 'mbrlen',
'mbrtowc', 'wcrtomb', 'mbsrtowcs', 'wcsrtombs',
],
}
def isStdLibId(id_, standard='c99'):
id_lists = []
if standard == 'c89':
id_lists = C90_STDLIB_IDENTIFIERS.values()
elif standard in ('c99', 'c11'):
id_lists = C99_STDLIB_IDENTIFIERS.values()
for l in id_lists:
if id_ in l:
return True
return False
# Reserved keywords defined in ISO/IEC9899:1990 -- ch 6.1.1
C90_KEYWORDS = {
'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if',
'int', 'long', 'register', 'return', 'short', 'signed',
'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned',
'void', 'volatile', 'while'
}
# Reserved keywords defined in ISO/IEC 9899 WF14/N1256 -- ch. 6.4.1
C99_ADDED_KEYWORDS = {
'inline', 'restrict', '_Bool', '_Complex', '_Imaginary',
'bool', 'complex', 'imaginary'
}
C11_ADDED_KEYWORDS = {
'_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
'_Statis_assert', '_Thread_local' ,
'alignas', 'alignof', 'noreturn', 'static_assert'
}
def isKeyword(keyword, standard='c99'):
kw_set = {}
if standard == 'c89':
kw_set = C90_KEYWORDS
elif standard == 'c99':
kw_set = copy.copy(C90_KEYWORDS)
kw_set.update(C99_ADDED_KEYWORDS)
else:
kw_set = copy.copy(C90_KEYWORDS)
kw_set.update(C99_ADDED_KEYWORDS)
kw_set.update(C11_ADDED_KEYWORDS)
return keyword in kw_set
def is_source_file(file):
return file.endswith('.c')
def is_header(file):
return file.endswith('.h')
def is_errno_setting_function(function_name):
return function_name and \
function_name in ('ftell', 'fgetpos', 'fsetpos', 'fgetwc', 'fputwc'
'strtoimax', 'strtoumax', 'strtol', 'strtoul',
'strtoll', 'strtoull', 'strtof', 'strtod', 'strtold'
'wcstoimax', 'wcstoumax', 'wcstol', 'wcstoul',
'wcstoll', 'wcstoull', 'wcstof', 'wcstod', 'wcstold'
'wcrtomb', 'wcsrtombs', 'mbrtowc')
def get_type_conversion_to_from(token):
def get_vartok(expr):
while expr:
if isCast(expr):
if expr.astOperand2 is None:
expr = expr.astOperand1
else:
expr = expr.astOperand2
elif expr.str in ('.', '::'):
expr = expr.astOperand2
elif expr.str == '[':
expr = expr.astOperand1
else:
break
return expr if (expr and expr.variable) else None
if isCast(token):
vartok = get_vartok(token)
if vartok:
return (token.next, vartok.variable.typeStartToken)
elif token.str == '=':
lhs = get_vartok(token.astOperand1)
rhs = get_vartok(token.astOperand2)
if lhs and rhs:
return (lhs.variable.typeStartToken, rhs.variable.typeStartToken)
return None
def is_composite_expr(expr, composite_operator=False):
"""MISRA C 2012, section 8.10.3"""
if expr is None:
return False
if not composite_operator:
if expr.str == '?' and simpleMatch(expr.astOperand2, ':'):
colon = expr.astOperand2
return is_composite_expr(colon.astOperand1,True) or is_composite_expr(colon.astOperand2, True)
if (expr.str in ('+', '-', '*', '/', '%', '&', '|', '^', '>>', "<<", "?", ":", '~')):
return is_composite_expr(expr.astOperand1,True) or is_composite_expr(expr.astOperand2, True)
return False
# non constant expression?
if expr.isNumber:
return False
if expr.astOperand1 or expr.astOperand2:
return is_composite_expr(expr.astOperand1,True) or is_composite_expr(expr.astOperand2, True)
return True
def getEssentialTypeCategory(expr):
if not expr:
return None
if expr.str == ',':
return getEssentialTypeCategory(expr.astOperand2)
if expr.str in ('<', '<=', '==', '!=', '>=', '>', '&&', '||', '!'):
return 'bool'
if expr.str in ('<<', '>>'):
# TODO this is incomplete
return getEssentialTypeCategory(expr.astOperand1)
if len(expr.str) == 1 and expr.str in '+-*/%&|^':
# TODO this is incomplete
e1 = getEssentialTypeCategory(expr.astOperand1)
e2 = getEssentialTypeCategory(expr.astOperand2)
# print('{0}: {1} {2}'.format(expr.str, e1, e2))
if e1 and e2 and e1 == e2:
return e1
if expr.valueType:
return expr.valueType.sign
if expr.valueType and expr.valueType.typeScope and expr.valueType.typeScope.className:
return "enum<" + expr.valueType.typeScope.className + ">"
# Unwrap membership, dereferences and array indexing
vartok = expr
while True:
if simpleMatch(vartok, '[') or (vartok and vartok.str == '*' and vartok.astOperand2 is None):
vartok = vartok.astOperand1
elif simpleMatch(vartok, '.'):
vartok = vartok.astOperand2
else:
break
if vartok and vartok.variable:
typeToken = vartok.variable.typeStartToken
while typeToken and typeToken.isName:
if typeToken.str == 'char' and not typeToken.isSigned and not typeToken.isUnsigned:
return 'char'
if typeToken.valueType:
if typeToken.valueType.type == 'bool':
return typeToken.valueType.type
if typeToken.valueType.type in ('float', 'double', 'long double'):
return "float"
if typeToken.valueType.sign:
return typeToken.valueType.sign
typeToken = typeToken.next
# See Appendix D, section D.6, Character constants
if expr.str[0] == "'" and expr.str[-1] == "'":
if len(expr.str) == 3 or (len(expr.str) == 4 and expr.str[1] == '\\'):
return 'char'
return expr.valueType.sign
if (expr.isCast and expr.str == "("):
castTok = expr.next
while castTok.isName or castTok.str == "*":
if castTok.str == 'char' and not castTok.isSigned and not castTok.isUnsigned:
return 'char'
castTok = castTok.next
if expr.valueType:
return expr.valueType.sign
return None
def getEssentialCategorylist(operand1, operand2):
if not operand1 or not operand2:
return None, None
if (operand1.str in ('++', '--') or
operand2.str in ('++', '--')):
return None, None
if ((operand1.valueType and operand1.valueType.pointer) or
(operand2.valueType and operand2.valueType.pointer)):
return None, None
e1 = getEssentialTypeCategory(operand1)
e2 = getEssentialTypeCategory(operand2)
return e1, e2
def get_essential_type_from_value(value, is_signed):
if value is None:
return None
for t in ('char', 'short', 'int', 'long', 'long long'):
bits = bitsOfEssentialType(t)
if bits >= 64:
continue
if is_signed:
range_min = -(1 << (bits - 1))
range_max = (1 << (bits - 1)) - 1
else:
range_min = 0
range_max = (1 << bits) - 1
sign = 'signed' if is_signed else 'unsigned'
if is_signed and value < 0 and value >= range_min:
return '%s %s' % (sign, t)
if value >= 0 and value <= range_max:
return '%s %s' % (sign, t)
return None
def getEssentialType(expr):
if not expr:
return None
# See Appendix D, section D.6, Character constants
if expr.str[0] == "'" and expr.str[-1] == "'":
if len(expr.str) == 3 or (len(expr.str) == 4 and expr.str[1] == '\\'):
return 'char'
return '%s %s' % (expr.valueType.sign, expr.valueType.type)
if expr.variable or isCast(expr):
typeToken = expr.variable.typeStartToken if expr.variable else expr.next
while typeToken and typeToken.isName:
if typeToken.str == 'char' and not typeToken.isSigned and not typeToken.isUnsigned:
return 'char'
typeToken = typeToken.next
if expr.valueType:
if expr.valueType.type == 'bool':
return 'bool'
if expr.valueType.isFloat():
return expr.valueType.type
if expr.valueType.isIntegral():
if (expr.valueType.sign is None) and expr.valueType.type == 'char':
return 'char'
return '%s %s' % (expr.valueType.sign, expr.valueType.type)
elif expr.isNumber:
# Appendix D, D.6 The essential type of literal constants
# Integer constants
if expr.valueType.type == 'bool':
return 'bool'
if expr.valueType.isFloat():
return expr.valueType.type
if expr.valueType.isIntegral():
if expr.valueType.type != 'int':
return '%s %s' % (expr.valueType.sign, expr.valueType.type)
return get_essential_type_from_value(expr.getKnownIntValue(), expr.valueType.sign == 'signed')
elif expr.str in ('<', '<=', '>=', '>', '==', '!=', '&&', '||', '!'):
return 'bool'
elif expr.astOperand1 and expr.astOperand2 and expr.str in (
'+', '-', '*', '/', '%', '&', '|', '^', '>>', "<<", "?", ":"):
if expr.astOperand1.valueType and expr.astOperand1.valueType.pointer > 0:
return None
if expr.astOperand2.valueType and expr.astOperand2.valueType.pointer > 0:
return None
e1 = getEssentialType(expr.astOperand1)
e2 = getEssentialType(expr.astOperand2)
if e1 is None or e2 is None:
return None
if is_constant_integer_expression(expr):
sign1 = e1.split(' ')[0]
sign2 = e2.split(' ')[0]
if sign1 == sign2 and sign1 in ('signed', 'unsigned'):
e = get_essential_type_from_value(expr.getKnownIntValue(), sign1 == 'signed')
if e:
return e
if bitsOfEssentialType(e2) >= bitsOfEssentialType(e1):
return e2
return e1
elif expr.str == "~":
e1 = getEssentialType(expr.astOperand1)
return e1
return None
def bitsOfEssentialType(ty):
if ty is None:
return 0
last_type = ty.split(' ')[-1]
if last_type == 'Boolean':
return 1
if last_type == 'char':
return typeBits['CHAR']
if last_type == 'short':
return typeBits['SHORT']
if last_type == 'int':
return typeBits['INT']
if ty.endswith('long long'):
return typeBits['LONG_LONG']
if last_type == 'long':
return typeBits['LONG']
for sty in STDINT_TYPES:
if ty == sty:
return int(''.join(filter(str.isdigit, sty)))
return 0
def get_function_pointer_type(tok):
ret = ''
while tok and (tok.isName or tok.str == '*'):
ret += ' ' + tok.str
tok = tok.next
if tok is None or tok.str != '(':
return None
tok = tok.link
if not simpleMatch(tok, ') ('):
return None
ret += '('
tok = tok.next.next
while tok and (tok.str not in '()'):
if tok.varId is None:
ret += ' ' + tok.str
tok = tok.next
if (tok is None) or tok.str != ')':
return None
return ret[1:] + ')'
def isCast(expr):
if not expr or expr.str != '(' or not expr.astOperand1 or expr.astOperand2:
return False
if simpleMatch(expr, '( )'):
return False
return True
def is_constant_integer_expression(expr):
if expr is None:
return False
if expr.isInt:
return True
if not expr.isArithmeticalOp:
return False
if expr.astOperand1 and not is_constant_integer_expression(expr.astOperand1):
return False
if expr.astOperand2 and not is_constant_integer_expression(expr.astOperand2):
return False
return True
def isFunctionCall(expr, std='c99'):
if not expr:
return False
if expr.str != '(' or not expr.astOperand1:
return False
if expr.astOperand1 != expr.previous:
return False
if isKeyword(expr.astOperand1.str, std):
return False
return True
def hasExternalLinkage(var):
return var.isGlobal and not var.isStatic
def countSideEffects(expr):
if not expr or expr.str in (',', ';'):
return 0
ret = 0
if expr.str in ('++', '--', '='):
ret = 1
return ret + countSideEffects(expr.astOperand1) + countSideEffects(expr.astOperand2)
def getForLoopExpressions(forToken):
if not forToken or forToken.str != 'for':
return None
lpar = forToken.next
if not lpar or lpar.str != '(':
return None
if not lpar.astOperand2 or lpar.astOperand2.str != ';':
return None
if not lpar.astOperand2.astOperand2 or lpar.astOperand2.astOperand2.str != ';':
return None
return [lpar.astOperand2.astOperand1,
lpar.astOperand2.astOperand2.astOperand1,
lpar.astOperand2.astOperand2.astOperand2]
def get_function_scope(cfg, func):
if func:
for scope in cfg.scopes:
if scope.function == func:
return scope
return None
def is_variable_changed(start_token, end_token, var):
"""Check if variable is updated between body_start and body_end"""
tok = start_token
while tok != end_token:
if tok.isAssignmentOp:
vartok = tok.astOperand1
while vartok.astOperand1:
vartok = vartok.astOperand1
if vartok and vartok.variable == var:
return True
tok = tok.next
return False
def getForLoopCounterVariables(forToken, cfg):
""" Return a set of Variable objects defined in ``for`` statement and
satisfy requirements to loop counter term from section 8.14 of MISRA
document.
"""
if not forToken or forToken.str != 'for':
return None
tn = forToken.next
if not tn or tn.str != '(':
return None
vars_defined = set()
vars_initialized = set()
vars_exit = set()
vars_modified = set()
cur_clause = 1
te = tn.link
while tn and tn != te:
if tn.variable:
if cur_clause == 1 and tn.variable.nameToken == tn:
vars_defined.add(tn.variable)
elif cur_clause == 2:
vars_exit.add(tn.variable)
elif cur_clause == 3:
if tn.next and countSideEffectsRecursive(tn.next) > 0:
vars_modified.add(tn.variable)
elif tn.previous and tn.previous.str in ('++', '--'):
tn_ast = tn.astParent
if tn_ast and tn_ast == tn.previous:
vars_modified.add(tn.variable)
elif tn_ast and tn_ast.str == '.' and tn_ast.astOperand2 and tn_ast.astOperand2.variable:
vars_modified.add(tn_ast.astOperand2.variable)
if cur_clause == 1 and tn.isAssignmentOp:
var_token = tn.astOperand1
while var_token and var_token.str == '.':
var_token = var_token.astOperand2
if var_token and var_token.variable:
vars_initialized.add(var_token.variable)
if cur_clause == 1 and tn.isName and tn.next.str == '(':
function_args_in_init = getArguments(tn.next)
function_scope = get_function_scope(cfg, tn.function)
for arg_nr in range(len(function_args_in_init)):
init_arg = function_args_in_init[arg_nr]
if init_arg is None or not init_arg.isUnaryOp('&'):
continue
var_token = init_arg.astOperand1
while var_token and var_token.str == '.':
var_token = var_token.astOperand2
if var_token is None or var_token.variable is None:
continue
changed = False
if function_scope is None:
changed = True
elif tn.function is None:
changed = True
else:
function_body_start = function_scope.bodyStart
function_body_end = function_scope.bodyEnd
args = tn.function.argument[arg_nr + 1]
if function_scope is None or is_variable_changed(function_body_start, function_body_end, args):
changed = True
if changed:
vars_initialized.add(var_token.variable)
if tn.str == ';':
cur_clause += 1
tn = tn.next
return vars_defined | vars_initialized, vars_exit & vars_modified
def findCounterTokens(cond):
if not cond:
return []
if cond.str in ['&&', '||']:
c = findCounterTokens(cond.astOperand1)
c.extend(findCounterTokens(cond.astOperand2))
return c
ret = []
if ((cond.isArithmeticalOp and cond.astOperand1 and cond.astOperand2) or
(cond.isComparisonOp and cond.astOperand1 and cond.astOperand2)):
if cond.astOperand1.isName:
ret.append(cond.astOperand1)
if cond.astOperand2.isName:
ret.append(cond.astOperand2)
if cond.astOperand1.isOp:
ret.extend(findCounterTokens(cond.astOperand1))
if cond.astOperand2.isOp:
ret.extend(findCounterTokens(cond.astOperand2))
return ret
def isFloatCounterInWhileLoop(whileToken):
if not simpleMatch(whileToken, 'while ('):
return False
lpar = whileToken.next
rpar = lpar.link
counterTokens = findCounterTokens(lpar.astOperand2)
tok_varid = tuple(tok.varId for tok in counterTokens if tok.varId)
whileBodyStart = None
if simpleMatch(rpar, ') {'):
whileBodyStart = rpar.next
elif simpleMatch(whileToken.previous, '} while') and simpleMatch(whileToken.previous.link.previous, 'do {'):
whileBodyStart = whileToken.previous.link
else:
return False
token = whileBodyStart
while token != whileBodyStart.link:
token = token.next
if not token.varId:
continue
if token.varId not in tok_varid:
continue
if not token.astParent or not token.valueType or not token.valueType.isFloat():
continue
parent = token.astParent
if parent.str in ('++', '--'):
return True
while parent:
if parent.isAssignmentOp and parent.str != "=" and parent.astOperand1 == token:
return True
if parent.str == "=" and parent.astOperand1.str == token.str and parent.astOperand1 != token:
return True
parent = parent.astParent
return False
def countSideEffectsRecursive(expr):
if not expr or expr.str == ';':
return 0
if expr.str == '=' and expr.astOperand1 and expr.astOperand1.str == '[':
prev = expr.astOperand1.previous
if prev and (prev.str == '{' or prev.str == '{'):
return countSideEffectsRecursive(expr.astOperand2)
if expr.str == '=' and expr.astOperand1 and expr.astOperand1.str == '.':
e = expr.astOperand1
while e and e.str == '.' and e.astOperand2:
e = e.astOperand1
if e and e.str == '.':
return 0
if expr.isAssignmentOp or expr.str in {'++', '--'}:
return 1
# Todo: Check function calls
return countSideEffectsRecursive(expr.astOperand1) + countSideEffectsRecursive(expr.astOperand2)
def isBoolExpression(expr):
if not expr:
return False
if expr.valueType and (expr.valueType.type == 'bool' or expr.valueType.bits == 1):
return True
return expr.str in ['!', '==', '!=', '<', '<=', '>', '>=', '&&', '||', '0', '1', 'true', 'false']
def isEnumConstant(expr):
if not expr or not expr.values:
return False
values = expr.values
return len(values) == 1 and values[0].valueKind == 'known'
def isConstantExpression(expr):
if expr.isNumber:
return True
if expr.isName and not isEnumConstant(expr):
return False
if simpleMatch(expr.previous, 'sizeof ('):
return True
if expr.astOperand1 and not isConstantExpression(expr.astOperand1):
return False
if expr.astOperand2 and not isConstantExpression(expr.astOperand2):
return False
return True
def isUnknownConstantExpression(expr):
if expr.isName and not isEnumConstant(expr) and expr.variable is None:
return True
if expr.astOperand1 and isUnknownConstantExpression(expr.astOperand1):
return True
if expr.astOperand2 and isUnknownConstantExpression(expr.astOperand2):
return True
return False
def isUnsignedInt(expr):
return expr and expr.valueType and expr.valueType.type in ('short', 'int') and expr.valueType.sign == 'unsigned'
def getPrecedence(expr):
if not expr:
return 16
if not expr.astOperand1 or not expr.astOperand2:
return 16
if expr.str in ('*', '/', '%'):
return 12
if expr.str in ('+', '-'):
return 11
if expr.str in ('<<', '>>'):
return 10
if expr.str in ('<', '>', '<=', '>='):
return 9
if expr.str in ('==', '!='):
return 8
if expr.str == '&':
return 7
if expr.str == '^':
return 6
if expr.str == '|':
return 5
if expr.str == '&&':
return 4
if expr.str == '||':
return 3
if expr.str in ('?', ':'):
return 2
if expr.isAssignmentOp:
return 1
if expr.str == ',':
return 0
return -1
def findRawLink(token):
tok1 = None
tok2 = None
forward = False
if token.str in '{([':
tok1 = token.str
tok2 = '})]'['{(['.find(token.str)]
forward = True
elif token.str in '})]':
tok1 = token.str
tok2 = '{(['['})]'.find(token.str)]
forward = False
else:
return None
# try to find link
indent = 0
while token:
if token.str == tok1:
indent = indent + 1
elif token.str == tok2:
if indent <= 1:
return token
indent = indent - 1
if forward is True:
token = token.next
else:
token = token.previous
# raw link not found
return None
def numberOfParentheses(tok1, tok2):
while tok1 and tok1 != tok2:
if tok1.str == '(' or tok1.str == ')':
return False
tok1 = tok1.next
return tok1 == tok2
def findGotoLabel(gotoToken):
label = gotoToken.next.str
tok = gotoToken.next.next
while tok:
if tok.str == '}' and tok.scope.type == 'Function':