|
1 | | -"""Reject new uninitialized reads in generated integer and pointer locals. |
| 1 | +"""Moved to `decomprepair.permuter_initialization`, the standalone repair library; this name stays for the rest of the app |
| 2 | +(both names are one module, so a patch through either is seen by both).""" |
2 | 3 |
|
3 | | -This is neither a C undefined-behavior checker nor a semantic equivalence proof. Unknown syntax, |
4 | | -qualified/shadowed/escaped locals receive no verdict. Existing bindings are rejected only when |
5 | | -the parent has a supported initialized verdict for that binding. Use the bounded local CFG, |
6 | | -with separate initialization transfer rules: its liveness definitions include bare declarations. |
7 | | -""" |
8 | | -import re |
9 | | -from functools import lru_cache |
| 4 | +import sys |
10 | 5 |
|
11 | | -from decomprepair import local_flow |
12 | | -from decomprepair.integer_repair_support import IDENT, INTEGER, NUMBER, view |
13 | | -from decomprepair.pattern_repairs import close |
14 | | -from decomprepair.pointer_pair_repairs import qualified_types |
| 6 | +from decomprepair import permuter_initialization |
15 | 7 |
|
16 | | -# Pointer captures need the same must-initialization check as integer captures. |
17 | | -# Keep unknown pointee aliases, qualifiers, arrays and function pointers opaque. |
18 | | -_TYPE = rf'(?:{INTEGER}(?=\s)|(?:{INTEGER}|void)(?:\s*\*)+)' |
19 | | -_DECL = re.compile(rf'\b(?P<type>{_TYPE})\s*(?P<name>{IDENT})\s*(?:=(?P<initial>[^;{{}}]*))?;') |
20 | | - |
21 | | - |
22 | | -def unsafe_temporary(parent, candidate, name, header=""): |
23 | | - """Whether a new local is unsafe, or an existing local loses proven initialization.""" |
24 | | - original = view(parent, name) |
25 | | - if not original: |
26 | | - return False |
27 | | - old_names = set(re.findall(IDENT, original.clean)) |
28 | | - verdicts = _initialization_verdicts(candidate, name, header) |
29 | | - unsafe = {variable for variable, verdict in verdicts.items() if verdict is True} |
30 | | - if unsafe-old_names: |
31 | | - return True |
32 | | - if not unsafe: |
33 | | - return False |
34 | | - previous = _parent_verdicts(parent, name, header) |
35 | | - return any(previous.get(variable) is False for variable in unsafe) |
36 | | - |
37 | | - |
38 | | -@lru_cache(maxsize=8) |
39 | | -def _parent_verdicts(source, name, header): |
40 | | - # A batch shares its parent. Do not rebuild its CFG for each rejected proposal. |
41 | | - return _initialization_verdicts(source, name, header) |
42 | | - |
43 | | - |
44 | | -def _initialization_verdicts(candidate, name, header): |
45 | | - part = view(candidate, name) |
46 | | - if not part: |
47 | | - return {} |
48 | | - combined = header+"\n"+candidate |
49 | | - macros = set(re.findall(r"^\s*#\s*define\s+("+IDENT+r")", combined, re.M)) |
50 | | - # This guard excludes both const and volatile aliases, including alias chains. |
51 | | - qualified = qualified_types(re.sub(r"\bconst\b", "volatile", combined)) |
52 | | - records = [] |
53 | | - for record in re.finditer(r"\b(?:struct|union)(?:\s+"+IDENT+r")?\s*{", part.body): |
54 | | - start = part.opening+1+record.end()-1 |
55 | | - end = close(part.clean, start, "{", "}") |
56 | | - if end: |
57 | | - records.append((start, end)) |
58 | | - declarations = [] |
59 | | - for decl in _DECL.finditer(part.clean, part.opening+1, part.end): |
60 | | - prefix = part.clean[part.opening+1:decl.start()].rstrip() |
61 | | - variable = decl['name'] |
62 | | - if any(start < decl.start() < end for start, end in records): |
63 | | - continue |
64 | | - if (set(re.findall(IDENT, decl['type'])) | {variable}) & (qualified | macros): |
65 | | - continue |
66 | | - if prefix and prefix[-1] not in ';{}': |
67 | | - continue |
68 | | - if len(re.findall(rf'\b(?:{INTEGER}|void|float|double)(?:\s+|(?:\s*\*)+\s*)' |
69 | | - rf'{variable}\s*(?=[;=,\[])', part.body)) != 1: |
70 | | - continue |
71 | | - if re.search(rf'&\s*(?:\(\s*)*{variable}\b', part.body): |
72 | | - continue |
73 | | - declarations.append(decl) |
74 | | - if not declarations or re.search(r"\bfor\s*\([^;]*;\s*;", part.body): |
75 | | - return {} |
76 | | - flow = local_flow.analyze(_without_type_only_records(candidate, part, macros), name, |
77 | | - declarations=declarations) |
78 | | - if not flow or flow.entry is None: |
79 | | - return {} |
80 | | - # The native walk commonly wraps a single statement in do {...} while (0). |
81 | | - # Prune only its literal-zero back edge; other constant controls receive no verdict. |
82 | | - one_shot_conditions = set() |
83 | | - for hit in re.finditer(r'\bdo\b', part.body): |
84 | | - body = flow.skip(part.opening+1+hit.end(), part.end-1) |
85 | | - end = flow.statement_end(body, part.end-1) |
86 | | - opening, stop = flow.condition(end) |
87 | | - if re.fullmatch(r'\s*0[uUlL]*\s*', part.clean[opening+1:stop-1]): |
88 | | - for index, node in enumerate(flow.nodes): |
89 | | - if node.start == opening+1 and node.end == stop-1: |
90 | | - node.successors = {n for n in node.successors if not body <= flow.nodes[n].start < end} |
91 | | - one_shot_conditions.add(index) |
92 | | - # Unsupported writes to one temporary must not hide a separate unsafe capture. |
93 | | - # Reuse the bounded CFG, but keep each binding's initialization verdict independent. |
94 | | - return {decl['name']: _unsafe_binding(part, candidate, flow, decl, macros, combined, one_shot_conditions) |
95 | | - for decl in declarations} |
96 | | - |
97 | | - |
98 | | -def _without_type_only_records(candidate, part, macros): |
99 | | - """Hide only inert record typedefs from the statement CFG, preserving every offset. |
100 | | -
|
101 | | - The CFG deliberately rejects braced expressions. Literal-sized scalar fields in a local |
102 | | - typedef are not executable statements; VLA bounds, macros and other declarations stay opaque. |
103 | | - This is private to the initialization guard, not permission for lifetime repairs to move code. |
104 | | - """ |
105 | | - scalar = rf'(?:{INTEGER}|float|double|f32|f64)' |
106 | | - field = rf'{scalar}\s+{IDENT}(?:\s*\[\s*{NUMBER}\s*\])?\s*;' |
107 | | - result = list(candidate) |
108 | | - for hit in re.finditer(r'\btypedef\s+struct(?:\s+'+IDENT+r')?\s*{', part.body): |
109 | | - start = part.opening+1+hit.start() |
110 | | - opening = part.opening+1+hit.end()-1 |
111 | | - stop = close(part.clean, opening, '{', '}') |
112 | | - if not stop: |
113 | | - continue |
114 | | - tail = re.match(r'\s*('+IDENT+r')\s*;', part.clean[stop:]) |
115 | | - if not tail: |
116 | | - continue |
117 | | - end = stop+tail.end() |
118 | | - fields = part.clean[opening+1:stop-1] |
119 | | - if (not re.fullmatch(rf'(?:\s*{field})+\s*', fields) |
120 | | - or set(re.findall(IDENT, part.clean[start:end])) & macros): |
121 | | - continue |
122 | | - # The final semicolon becomes an empty statement. All declaration/read positions survive. |
123 | | - for index in range(start, end-1): |
124 | | - if result[index] != '\n': |
125 | | - result[index] = ' ' |
126 | | - return ''.join(result) |
127 | | - |
128 | | - |
129 | | -def _embedded_pointer_copy(text, variable, local_names=()): |
130 | | - """Recognize one unconditional pointer copy in two bounded expression forms. |
131 | | -
|
132 | | - Retain the ordinary indirect store-address copy, or accept a single capture |
133 | | - in another plain local assignment's arithmetic RHS. Calls, conditional |
134 | | - evaluation and other reads/writes of the copied binding remain opaque. |
135 | | - """ |
136 | | - if len(re.findall(rf'\b{variable}\b', text)) != 1: |
137 | | - return False |
138 | | - if not text.lstrip().startswith('*'): |
139 | | - # A single unconditional capture in another plain local's arithmetic RHS. |
140 | | - # No sequencing inference: the copied binding occurs only at this write. |
141 | | - assignment = re.fullmatch(rf'\s*({IDENT})\s*=(?!=)(.*?)\s*;?\s*', text, re.S) |
142 | | - if not assignment or assignment[1] not in local_names or assignment[1] == variable: |
143 | | - return False |
144 | | - rhs = assignment[2] |
145 | | - if (re.search(r'[,?;]|&&|\|\||\+\+|--|(?:<<|>>|[+*/%&|^\-])=', rhs) |
146 | | - or re.search(rf'\b{IDENT}\s*\(', rhs) |
147 | | - or re.search(r'\b(?:sizeof|_Alignof|typeof|__typeof__)\b', rhs)): |
148 | | - return False |
149 | | - capture = re.search(rf'\(\s*{variable}\s*=(?!=)\s*{IDENT}(?:\s*[+\-]\s*(?:{NUMBER}|{IDENT}))?\s*\)', rhs) |
150 | | - if capture is None: |
151 | | - return False |
152 | | - remaining = rhs[:capture.start()]+'0'+rhs[capture.end():] |
153 | | - # Other writes, member/index accesses and calls remain unknown. This is |
154 | | - # an initialization transfer, not an expression purity proof: arithmetic |
155 | | - # (including unary *) may evaluate operands in either order, but none |
156 | | - # reads/writes this p outside its single capture. |
157 | | - return (not re.search(r'=(?!=)|->|[\[\].]', remaining) |
158 | | - and re.fullmatch(r'[\s()A-Za-z_0-9+*/%&|^~<>\-]+', remaining) is not None) |
159 | | - depth = 0 |
160 | | - for pos, char in enumerate(text): |
161 | | - if char in '([': |
162 | | - depth += 1 |
163 | | - elif char in ')]': |
164 | | - depth -= 1 |
165 | | - elif (char == '=' and depth == 0 and text[pos+1:pos+2] != '=' |
166 | | - and text[pos-1:pos] not in '<>!=+-*/%&|^'): |
167 | | - address = text[:pos] |
168 | | - return (not re.search(rf'\b{IDENT}\s*\(', address) |
169 | | - and re.search(rf'\(\s*{variable}\s*=(?!=)\s*{IDENT}\s*\)', address) is not None) |
170 | | - return False |
171 | | - |
172 | | - |
173 | | -def _unsafe_binding(part, candidate, flow, decl, macros, combined, one_shot_conditions): |
174 | | - """True for a possible uninitialized read, False for initialized reads, None for unknown flow.""" |
175 | | - names = {decl['name']} |
176 | | - declarations = [decl] |
177 | | - pointers = names if '*' in decl['type'] else set() |
178 | | - from decomprepair.permuter_macro_effects import transparent_macros |
179 | | - opaque_macros = macros - transparent_macros(combined, names) |
180 | | - local_names = set(flow.names) |
181 | | - transfers = [] |
182 | | - for index, node in enumerate(flow.nodes): |
183 | | - text = part.clean[node.start:node.end] |
184 | | - # The shared CFG does not prune constant conditions or expand macros. |
185 | | - numbers_only = re.sub(rf'(?<![\w.]){NUMBER}(?![\w.])', '0', text) |
186 | | - if ((index not in one_shot_conditions and re.search(r'\d', text) |
187 | | - and re.fullmatch(r'[\s0()+*/%<>=!&|^~.-]+', numbers_only)) |
188 | | - or (not text.strip() and "'" in candidate[node.start:node.end]) |
189 | | - or set(re.findall(IDENT, text)) & opaque_macros |
190 | | - or re.search(r'\b(?:sizeof|_Alignof|typeof|__typeof__|true|false)\b', text)): |
191 | | - return None |
192 | | - # A field named x is not the local x. Preserve the base and index expressions, |
193 | | - # but hide member identifiers from the binding-specific write/sequence checks. |
194 | | - text = re.sub(r'(\.|->)(\s*)('+IDENT+r')', |
195 | | - lambda hit: hit[1]+hit[2]+' '*len(hit[3]), text) |
196 | | - # Expression sequencing, embedded writes and macro-like calls are beyond this guard. |
197 | | - if names & set(re.findall(IDENT, text)) and re.search(r'\?|&&|\|\||\b(?:sizeof|_Alignof|typeof|__typeof__)\b|\b[A-Z_][A-Z_0-9]*\s*\(', text): |
198 | | - return None |
199 | | - uses = set(node.uses) & names |
200 | | - generates, kills = set(), set() |
201 | | - contained = [d for d in declarations if node.start <= d.start() and d.end() <= node.end] |
202 | | - for decl in contained: |
203 | | - variable = decl['name'] |
204 | | - kills.add(variable) |
205 | | - uses.discard(variable) |
206 | | - if decl['initial'] is not None: |
207 | | - initializer = decl['initial'] |
208 | | - if ',' in initializer or re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', initializer): |
209 | | - return None |
210 | | - initial = {hit[0] for hit in re.finditer(IDENT, initializer) |
211 | | - if not re.search(r'(?:\.|->)\s*$', initializer[:hit.start()])} & names |
212 | | - uses |= initial |
213 | | - generates.add(variable) |
214 | | - assignment = re.fullmatch(rf'\s*({IDENT})\s*=(?!=)(.*?);?\s*', text, re.S) |
215 | | - indirect = re.fullmatch(rf'\s*\*\s*({IDENT})\s*=(?!=)(.*?);?\s*', text, re.S) |
216 | | - if indirect and indirect[1] in pointers: |
217 | | - if ',' in indirect[2] or re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', indirect[2]): |
218 | | - return None |
219 | | - # Writing through a pointer reads its value; it does not assign that local. |
220 | | - uses.add(indirect[1]) |
221 | | - elif assignment and assignment[1] in names: |
222 | | - if ',' in assignment[2] or re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', assignment[2]): |
223 | | - return None |
224 | | - generates.add(assignment[1]) |
225 | | - elif not contained and re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', text): |
226 | | - if decl['name'] not in pointers or not _embedded_pointer_copy(text, decl['name'], local_names): |
227 | | - return None |
228 | | - # Completing this supported expression necessarily evaluates its capture. |
229 | | - # Track the copy on this CFG edge, not on paths bypassing the statement. |
230 | | - uses.discard(decl['name']) |
231 | | - generates.add(decl['name']) |
232 | | - transfers.append((uses, generates, kills)) |
233 | | - reachable, pending = set(), [flow.entry] |
234 | | - while pending: |
235 | | - index = pending.pop() |
236 | | - if index not in reachable: |
237 | | - reachable.add(index) |
238 | | - pending.extend(flow.nodes[index].successors) |
239 | | - predecessors = {index: set() for index in reachable} |
240 | | - for index in reachable: |
241 | | - for successor in flow.nodes[index].successors: |
242 | | - predecessors[successor].add(index) |
243 | | - # Greatest fixed point for a must analysis; the entry also has the empty initial state. |
244 | | - outgoing = {index: set(names) for index in reachable} |
245 | | - changed = True |
246 | | - while changed: |
247 | | - changed = False |
248 | | - for index in reachable: |
249 | | - incoming = set.intersection(*(outgoing[p] for p in predecessors[index])) if predecessors[index] else set() |
250 | | - if index == flow.entry: |
251 | | - incoming = set() |
252 | | - _, generates, kills = transfers[index] |
253 | | - result = (incoming-kills) | generates |
254 | | - if result != outgoing[index]: |
255 | | - outgoing[index] = result |
256 | | - changed = True |
257 | | - for index in reachable: |
258 | | - incoming = set.intersection(*(outgoing[p] for p in predecessors[index])) if predecessors[index] else set() |
259 | | - if index == flow.entry: |
260 | | - incoming = set() |
261 | | - uses, _, kills = transfers[index] |
262 | | - if uses - (incoming-kills): |
263 | | - return True |
264 | | - return False |
| 8 | +sys.modules[__name__] = permuter_initialization |
0 commit comments