-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinstrumenter.py
More file actions
371 lines (331 loc) · 12.8 KB
/
instrumenter.py
File metadata and controls
371 lines (331 loc) · 12.8 KB
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
from __future__ import annotations
import json
from dataclasses import replace
from enum import Enum
from functools import cache
from itertools import dropwhile, takewhile
from pathlib import Path
from diopter.compiler import (
ClangTool,
ClangToolMode,
CompilerExe,
SourceFile,
SourceProgram,
)
from program_markers.iprogram import InstrumentedFile, InstrumentedProgram
from program_markers.markers import (
DCEMarker,
EnableEmitter,
FunctionCallDetectionStrategy,
Marker,
VRMarker,
)
# TODO: The various hardcoded strings, e.g., "//MARKER_DIRECTIVES\n"
# should not be manually copied, instead either have some common file
# where they are defined or read them from some kind of info output,
# e.g., instrumenter --info
def __get_vr_macro_type_map(instrumented_code: str) -> dict[str, str]:
"""Finds the variable type for each VRMarker instance
in the instrumented code.
Args:
instrumented_code (str):
the output of the instrumenter (the variable types
of VRMarkers are parsed from the instrumented_code)
Returns:
dict[str,str]:
the variable type for each instance of VRMarkerX_
in the instrumented code
"""
def convert_variable_type(variable_type: str) -> str:
type_map = {
"_Bool": "bool",
"signed char": "char",
"uint8_t": "unsigned int",
"int8_t": "int",
"uint16_t": "unsigned short",
"int16_t": "short",
"uint32_t": "unsigned int",
"int32_t": "int",
"uint64_t": "unsigned long",
"int64_t": "long",
}
if variable_type in type_map:
variable_type = type_map[variable_type]
assert variable_type in [
"bool",
"char",
"short",
"int",
"long",
"long long",
"unsigned char",
"unsigned short",
"unsigned int",
"unsigned long",
"unsigned long long",
], f"Unexpected variable type for VRMarker: {variable_type} in {line}"
return variable_type
macroprefix = VRMarker.macroprefix()
vr_macro_type_map = {}
for line in instrumented_code.splitlines():
if macroprefix not in line:
continue
line = line[line.index(macroprefix) :]
line = line[: line.find(")")]
macro = line.split("(")[0]
variable_type = convert_variable_type(
(line.split(",")[1].replace('"', "")).strip()
)
vr_macro_type_map[macro.replace(macroprefix, VRMarker.prefix())] = variable_type
return vr_macro_type_map
def __str_to_marker(marker_macro: str, vr_macro_type_map: dict[str, str]) -> Marker:
"""Converts the `marker_macro` string into a `Marker.
Args:
marker_macro (str):
a marker in the form PrefixMarkerX_, e.g., DCEMarker32_.
vr_macro_type_map (dict[str,str]):
a mapping from VRMarker macros to their variable types
e.g., {"VRMarker0_": "int", "VRMarker1_": "short"}
Returns:
Marker:
a `Marker` object
"""
if marker_macro.startswith(DCEMarker.prefix()):
return DCEMarker.from_str(marker_macro)
else:
assert marker_macro.startswith(VRMarker.prefix()), marker_macro
return VRMarker.from_str(marker_macro, vr_macro_type_map[marker_macro])
class NoInstrumentationAddedError(Exception):
pass
@cache
def get_instrumenter(
instrumenter: ClangTool | None = None, clang: CompilerExe | None = None
) -> ClangTool:
if not instrumenter:
if not clang:
# TODO: move this to diopter
try:
clang = CompilerExe.get_system_clang()
except: # noqa: E722
pass
if not clang:
for clang_path in ("clang-16", "clang-15", "clang-14"):
try:
clang = CompilerExe.from_path(Path(clang_path))
break
except: # noqa: E722
pass
assert clang, "Could not find clang"
instrumenter = ClangTool.init_with_paths_from_clang(
Path(__file__).parent / "program-markers", clang
)
return instrumenter
def parse_marker_names(instrumenter_output: str) -> list[str]:
markers_start = "//MARKERS START\n"
markers_end = "//MARKERS END\n"
lines: list[str] = list(
dropwhile(
lambda x: x.startswith(markers_start),
instrumenter_output.strip().splitlines(),
)
)
if not lines:
raise NoInstrumentationAddedError
return list(takewhile(lambda x: not x.startswith(markers_end), lines[1:]))[:-1]
class InstrumenterMode(Enum):
DCE = 0
VR = 1
DCE_AND_VR = 2
def add_temporary_disable_directives(source: str, markers: list[Marker]) -> str:
temp_directives = ["//TEMP_DIRECTIVES_START\n"]
for marker in markers:
assert isinstance(marker, DCEMarker)
temp_directives.append(f"#define {marker.macro()}")
temp_directives.append("//TEMP_DIRECTIVES_END\n")
return "\n".join(temp_directives) + "\n" + source
def remove_temporary_disable_directives(source: str) -> str:
lines = source.strip().splitlines()
pre_lines = list(
takewhile(lambda x: not x.startswith("//TEMP_DIRECTIVES_START"), lines)
)
post_lines = list(
dropwhile(
lambda x: not x.startswith("//TEMP_DIRECTIVES_END"), lines[len(pre_lines) :]
)
)
return "\n".join(pre_lines) + "\n" + "\n".join(post_lines)
def instrument_program(
program: SourceProgram,
ignore_functions_with_macros: bool = False,
mode: InstrumenterMode = InstrumenterMode.DCE,
instrumenter: ClangTool | None = None,
clang: CompilerExe | None = None,
timeout: int | None = None,
) -> InstrumentedProgram:
"""Instrument a given program i.e. put markers in the source code.
Args:
program (Source):
The program to be instrumented.
ignore_functions_with_macros (bool):
Whether to ignore instrumenting functions that contain macro expansions
instrumenter (ClangTool):
The instrumenter
clang (CompilerExe):
Which clang to use for searching the standard include paths
timeout (int | None):
Optional timeout in seconds for the instrumenter
Returns:
InstrumentedProgram: The instrumented version of program
"""
instrumenter_resolved = get_instrumenter(instrumenter, clang)
flags = ["--no-preprocessor-directives"]
if ignore_functions_with_macros:
flags.append("--ignore-functions-with-macros=1")
else:
flags.append("--ignore-functions-with-macros=0")
def get_code_and_markers(mode: str) -> tuple[str, list[Marker]]:
result = instrumenter_resolved.run_on_program(
program,
flags + [f"--mode={mode}"],
ClangToolMode.CAPTURE_OUT_ERR_AND_READ_MODIFIED_FILED,
timeout=timeout,
)
assert result.modified_source_code
assert result.stdout
instrumented_code = result.modified_source_code
marker_names = parse_marker_names(result.stdout)
if mode == "vr":
vr_macro_type_map = __get_vr_macro_type_map(instrumented_code)
else:
vr_macro_type_map = {}
return instrumented_code, [
__str_to_marker(marker_name, vr_macro_type_map)
for marker_name in marker_names
]
match mode:
case InstrumenterMode.DCE:
instrumented_code, markers = get_code_and_markers("dce")
case InstrumenterMode.VR:
instrumented_code, markers = get_code_and_markers("vr")
case InstrumenterMode.DCE_AND_VR:
result = instrumenter_resolved.run_on_program(
program,
flags + ["--mode=dce"],
ClangToolMode.CAPTURE_OUT_ERR_AND_READ_MODIFIED_FILED,
timeout=timeout,
)
assert result.modified_source_code
assert result.stdout
dce_markers = [
__str_to_marker(name, {}) for name in parse_marker_names(result.stdout)
]
program_dce = replace(
program,
code=add_temporary_disable_directives(
result.modified_source_code, dce_markers
),
)
result = instrumenter_resolved.run_on_program(
program_dce,
flags + ["--mode=vr"],
ClangToolMode.CAPTURE_OUT_ERR_AND_READ_MODIFIED_FILED,
timeout=timeout,
)
assert result.modified_source_code
assert result.stdout
instrumented_code = remove_temporary_disable_directives(
result.modified_source_code
)
vr_macro_type_map = __get_vr_macro_type_map(instrumented_code)
vr_markers = list(
__str_to_marker(name, vr_macro_type_map)
for name in parse_marker_names(result.stdout)
)
if len(vr_markers) > 0 and len(dce_markers) > 0:
# There will be overlap between the two sets of marker ids
max_vr_id = max(vr_marker.id for vr_marker in vr_markers)
replacements = []
new_dce_markers = []
for dce_marker in dce_markers:
old_macro = dce_marker.macro()
old_id = dce_marker.id
new_id = old_id + max_vr_id + 1
new_marker = replace(
dce_marker,
id=new_id,
name=dce_marker.name.replace(str(old_id), str(new_id)),
)
new_macro = new_marker.macro()
replacements.append((old_macro, new_macro))
new_dce_markers.append(new_marker)
dce_markers = new_dce_markers
for old_macro, new_macro in replacements:
instrumented_code = instrumented_code.replace(
old_macro, new_macro, 1
)
markers = dce_markers + vr_markers
ee = EnableEmitter(FunctionCallDetectionStrategy())
return InstrumentedProgram(
code=instrumented_code,
marker_strategy=FunctionCallDetectionStrategy(),
language=program.language,
defined_macros=tuple(),
include_paths=program.include_paths,
system_include_paths=program.system_include_paths,
flags=program.flags,
markers=tuple(markers),
directive_emitters={m: ee for m in markers},
)
# Instrument_file calls instrument_program and writes the result to a file
# (filename argument) plus an include file for the directives. It can use
# the temp InstrumentedProgram to serialize everything and read it back in.
# I can also add a debug mode that checks if the parsed is the same as the original.
def instrument_file(
file: SourceFile,
output: Path,
ignore_functions_with_macros: bool = False,
mode: InstrumenterMode = InstrumenterMode.DCE,
instrumenter: ClangTool | None = None,
clang: CompilerExe | None = None,
timeout: int | None = None,
) -> InstrumentedFile:
# TODO: operate directly on a SourceFile
program = SourceProgram(
language=file.language,
defined_macros=file.defined_macros,
include_paths=file.include_paths + (str(file.filename.parent.resolve()),),
system_include_paths=file.system_include_paths,
flags=file.flags,
code=open(file.filename, "r").read(),
)
iprogram = instrument_program(
program, ignore_functions_with_macros, mode, instrumenter, clang, timeout
)
output = output.resolve()
inc_file = output.with_suffix(".h").with_stem(output.stem + "_program_markers")
with open(output, "w") as f:
f.write(program.code)
with open(inc_file, "w") as f:
f.write(iprogram.generate_preprocessor_directives())
jprogram = iprogram.to_json_dict()
del jprogram["code"]
del jprogram["language"]
del jprogram["include_paths"]
del jprogram["system_include_paths"]
del jprogram["flags"]
j_file = output.with_suffix(".json")
with open(j_file, "w") as f:
json.dump(jprogram, f)
return InstrumentedFile(
marker_strategy=iprogram.marker_strategy,
markers=iprogram.markers,
directive_emitters=iprogram.directive_emitters,
directives_include_file=inc_file,
directives_json_file=j_file,
filename=output,
language=program.language,
defined_macros=program.defined_macros,
include_paths=program.include_paths,
system_include_paths=program.system_include_paths,
flags=program.flags + (f"-include {str(inc_file)}",),
)