|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Detect error-prone zero initialization of unions. |
| 4 | + |
| 5 | +import dataclasses |
| 6 | +import cppcheck |
| 7 | +import cppcheckdata |
| 8 | +from typing import List, Tuple |
| 9 | + |
| 10 | + |
| 11 | +@dataclasses.dataclass |
| 12 | +class Member: |
| 13 | + name: str |
| 14 | + size: int |
| 15 | + |
| 16 | + |
| 17 | +@dataclasses.dataclass |
| 18 | +class Union: |
| 19 | + name: str |
| 20 | + members: List[Member] = dataclasses.field(default_factory=list) |
| 21 | + |
| 22 | + def largest_member(self): |
| 23 | + return sorted(self.members, key=lambda m: -m.size)[0] |
| 24 | + |
| 25 | + def is_largest_member_first(self): |
| 26 | + sizes = [m.size for m in self.members] |
| 27 | + |
| 28 | + has_unknown_sizes = 0 in sizes |
| 29 | + if has_unknown_sizes: |
| 30 | + return True |
| 31 | + |
| 32 | + return sizes[0] == sorted(sizes, key=lambda s: -s)[0] |
| 33 | + |
| 34 | + |
| 35 | +def estimate_size_of_type( |
| 36 | + platform: cppcheckdata.Platform, type: str, pointer: bool |
| 37 | +) -> int: |
| 38 | + bits = 0 |
| 39 | + if pointer: |
| 40 | + bits = platform.pointer_bit |
| 41 | + elif type == "char": |
| 42 | + bits = platform.char_bit |
| 43 | + elif type == "short": |
| 44 | + bits = platform.short_bit |
| 45 | + elif type == "int": |
| 46 | + bits = platform.int_bit |
| 47 | + elif type == "long": |
| 48 | + bits = platform.long_bit |
| 49 | + elif type == "long_long": |
| 50 | + bits = platform.long_long_bit |
| 51 | + else: |
| 52 | + # Fair estimate... |
| 53 | + bits = platform.int_bit |
| 54 | + return bits |
| 55 | + |
| 56 | + |
| 57 | +def tokat(token: cppcheckdata.Token, offset) -> cppcheckdata.Token: |
| 58 | + at = token.tokAt(offset) |
| 59 | + if at: |
| 60 | + return at |
| 61 | + |
| 62 | + empty = {"str": ""} |
| 63 | + return cppcheckdata.Token(empty) |
| 64 | + |
| 65 | + |
| 66 | +def parse_array_length(token) -> int: |
| 67 | + if not tokat(token, 1).str == "[": |
| 68 | + return 1 |
| 69 | + |
| 70 | + nelements = 0 |
| 71 | + try: |
| 72 | + nelements = int(tokat(token, 2).str) |
| 73 | + except ValueError: |
| 74 | + return 1 |
| 75 | + |
| 76 | + if not tokat(token, 3).str == "]": |
| 77 | + return 1 |
| 78 | + |
| 79 | + return nelements |
| 80 | + |
| 81 | + |
| 82 | +def is_zero_initialized(token): |
| 83 | + return ( |
| 84 | + tokat(token, 1).str == "=" |
| 85 | + and tokat(token, 2).str == "{" |
| 86 | + and ( |
| 87 | + tokat(token, 3).str == "}" |
| 88 | + or (tokat(token, 3).str == "0" and tokat(token, 4).str == "}") |
| 89 | + ) |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +def is_pointer(variable: cppcheckdata.Variable) -> bool: |
| 94 | + return variable.nameToken.valueType.pointer and not variable.isArray |
| 95 | + |
| 96 | + |
| 97 | +def accumulated_member_size( |
| 98 | + data: cppcheckdata.CppcheckData, variable: cppcheckdata.Variable |
| 99 | +) -> Tuple[str, int]: |
| 100 | + # Note that cppcheck might not be able to observe all types due to |
| 101 | + # inaccessible include(s). |
| 102 | + if not variable.nameToken.valueType: |
| 103 | + return (None, 0) |
| 104 | + |
| 105 | + if variable.nameToken.valueType.type == "record": |
| 106 | + if not variable.nameToken.valueType.typeScope: |
| 107 | + return (None, 0) |
| 108 | + |
| 109 | + nested_variables = variable.nameToken.valueType.typeScope.varlist |
| 110 | + |
| 111 | + # Circumvent what seems to be a bug in which only the last bitfield has |
| 112 | + # its bits properly assigned. |
| 113 | + has_bitfields = any([v.nameToken.valueType.bits for v in nested_variables]) |
| 114 | + if has_bitfields: |
| 115 | + return (variable.nameToken.str, len(nested_variables)) |
| 116 | + |
| 117 | + total_size = 0 |
| 118 | + for nested in nested_variables: |
| 119 | + # Avoid potential cyclic members referring to the type currently |
| 120 | + # being traversed. |
| 121 | + if is_pointer(nested): |
| 122 | + total_size += data.platform.pointer_bit |
| 123 | + else: |
| 124 | + _, size = accumulated_member_size(data, nested.nameToken.variable) |
| 125 | + total_size += size |
| 126 | + return (variable.nameToken.str, total_size) |
| 127 | + |
| 128 | + vt = variable.nameToken.valueType |
| 129 | + if vt.bits: |
| 130 | + size = vt.bits |
| 131 | + else: |
| 132 | + size = estimate_size_of_type( |
| 133 | + data.platform, |
| 134 | + variable.nameToken.valueType.type, |
| 135 | + is_pointer(variable), |
| 136 | + ) |
| 137 | + if variable.isArray: |
| 138 | + size *= parse_array_length(variable.nameToken) |
| 139 | + return (variable.nameToken.str, size) |
| 140 | + |
| 141 | + |
| 142 | +def error_message(u: Union): |
| 143 | + return ( |
| 144 | + f"Zero initializing union {u.name} does not guarantee its complete " |
| 145 | + "storage to be zero initialized as its largest member is not declared " |
| 146 | + f"as the first member. Consider making {u.largest_member().name} the " |
| 147 | + "first member or favor memset()." |
| 148 | + ) |
| 149 | + |
| 150 | + |
| 151 | +@cppcheck.checker |
| 152 | +def union_zero_init(cfg, data, debug=False): |
| 153 | + unions_by_id = {} |
| 154 | + |
| 155 | + # Detect union declarations. |
| 156 | + for scope in cfg.scopes: |
| 157 | + if not scope.type == "Union": |
| 158 | + continue |
| 159 | + |
| 160 | + union = Union(name=scope.className) |
| 161 | + for variable in scope.varlist: |
| 162 | + name, size = accumulated_member_size(data, variable) |
| 163 | + union.members.append(Member(name=name, size=size)) |
| 164 | + unions_by_id[scope.Id] = union |
| 165 | + |
| 166 | + if debug: |
| 167 | + for id, u in unions_by_id.items(): |
| 168 | + print(id, u, u.is_largest_member_first(), u.largest_member()) |
| 169 | + |
| 170 | + # Detect problematic union variables. |
| 171 | + for token in cfg.tokenlist: |
| 172 | + if ( |
| 173 | + token.valueType |
| 174 | + and token.valueType.typeScopeId in unions_by_id |
| 175 | + and token.isName |
| 176 | + and is_zero_initialized(token) |
| 177 | + ): |
| 178 | + id = token.valueType.typeScopeId |
| 179 | + if not unions_by_id[id].is_largest_member_first(): |
| 180 | + cppcheck.reportError( |
| 181 | + token, |
| 182 | + "warning", |
| 183 | + error_message(unions_by_id[id]), |
| 184 | + "unionzeroinit", |
| 185 | + ) |
0 commit comments