-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_asmdiff.py
More file actions
2302 lines (1944 loc) · 92.5 KB
/
Copy pathtest_asmdiff.py
File metadata and controls
2302 lines (1944 loc) · 92.5 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
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
"""Unit tests for asmdiff.py. Run: python3 tools/asmdiff/test_asmdiff.py -v"""
import contextlib
import io
import json
import os
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import asmdiff
# Holds the isolation temp dir alive for the module's lifetime.
_ISOLATION = None
def setUpModule():
"""Isolate config discovery from the developer's real environment.
Tests run ``asmdiff.main()`` in-process, and ``find_config`` falls back
to ``$HOME/.config/asmdiff.toml`` (and a ``./asmdiff.toml`` in the CWD).
A real config on the machine - e.g. one whose ``default`` names cross
targets - would otherwise leak into any test that passes no ``--config``,
changing the matrix and masking the arg-validation errors it asserts on.
Point HOME and the CWD at empty temp dirs so discovery finds nothing
unless a test sets one up itself.
"""
global _ISOLATION
_ISOLATION = tempfile.TemporaryDirectory()
home = Path(_ISOLATION.name) / "home"
cwd = Path(_ISOLATION.name) / "cwd"
home.mkdir()
cwd.mkdir()
setUpModule._saved = (os.environ.get("HOME"),
os.environ.get("USERPROFILE"),
os.getcwd())
os.environ["HOME"] = str(home)
os.environ["USERPROFILE"] = str(home) # Path.home() on native Windows
os.chdir(cwd)
def tearDownModule():
home, userprofile, cwd = setUpModule._saved
os.chdir(cwd)
for name, value in (("HOME", home), ("USERPROFILE", userprofile)):
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
_ISOLATION.cleanup()
# Trimmed but structurally faithful `gcc -O3 -S` x86-64 output.
GCC_ASM = """\
\t.file\t"cmp.c"
\t.text
\t.p2align 4
\t.globl\told_const
\t.type\told_const, @function
old_const:
.LFB0:
\t.cfi_startproc
\tmulss\t.LC0(%rip), %xmm0
\tret
\t.cfi_endproc
.LFE0:
\t.size\told_const, .-old_const
\t.p2align 4
\t.globl\tnew_const
\t.type\tnew_const, @function
new_const:
.LFB1:
\t.cfi_startproc
\tmovl\t$-5, %edi
\tjmp\tldexpf@PLT
\t.cfi_endproc
.LFE1:
\t.size\tnew_const, .-new_const
\t.section\t.rodata.cst4,"aM",@progbits,4
.LC0:
\t.long\t1023410176
\t.ident\t"GCC: (GNU) 13.2.0"
"""
# Trimmed but structurally faithful `clang -O3 -S` x86-64 output.
CLANG_ASM = """\
\t.text
\t.file\t"cmp.c"
\t.globl\tnew_const
\t.p2align\t4, 0x90
\t.type\tnew_const,@function
new_const:
\t.cfi_startproc
# %bb.0:
\tmovl\t$-5, %edi
\tjmp\tldexpf@PLT
.Lfunc_end0:
\t.size\tnew_const, .Lfunc_end0-new_const
\t.cfi_endproc
"""
# A function containing a kept local label (loop target).
LOOP_ASM = """\
\t.globl\tlooper
\t.type\tlooper, @function
looper:
\t.cfi_startproc
\txorl\t%eax, %eax
.L2:
\taddl\t$1, %eax
\tcmpl\t$8, %eax
\tjne\t.L2
\tret
\t.cfi_endproc
\t.size\tlooper, .-looper
"""
# A switch lowered to a jump table, faithful to `gcc -O2 -S`. The table is
# emitted *inside* the function body (between the label and `.size`) via a
# .rodata/.text toggle, with self-relative entries `.long .Lx-.L4` — data,
# not instructions, and their .L4 operand must not read as a backward branch.
SWITCH_ASM = """\
\t.globl\tsel
\t.type\tsel, @function
sel:
.LFB0:
\t.cfi_startproc
\tendbr64
\tcmpl\t$4, %edi
\tja\t.L9
\tleaq\t.L4(%rip), %rcx
\tmovl\t%edi, %edi
\tmovslq\t(%rcx,%rdi,4), %rax
\taddq\t%rcx, %rax
\tnotrack jmp\t*%rax
\t.section\t.rodata
\t.align 4
.L4:
\t.long\t.L8-.L4
\t.long\t.L7-.L4
\t.long\t.L6-.L4
\t.long\t.L5-.L4
\t.long\t.L3-.L4
\t.text
\t.p2align 4,,10
.L5:
\tmovl\t%esi, %eax
\txorl\t%edx, %eax
\tret
.L3:
\tmovl\t%esi, %eax
\torl\t%edx, %eax
\tret
.L8:
\tleal\t(%rsi,%rdx), %eax
\tret
.L7:
\tmovl\t%esi, %eax
\tsubl\t%edx, %eax
\tret
.L6:
\tmovl\t%esi, %eax
\timull\t%edx, %eax
\tret
\t.cfi_endproc
\t.size\tsel, .-sel
"""
# Jump tables on other targets use plain (non-self-relative) label entries,
# plus stray inline constants; all are data directives, none are branches.
DATA_DIRECTIVES_ASM = """\
\t.type\ttbl, @function
tbl:
\t.cfi_startproc
\tjx\ta8
.Ltab:
\t.word\t.La
\t.word\t.Lb
\t.byte\t3
\t.quad\t0
.La:
\tadd.n\ta2, a2, a2
\tretw.n
.Lb:
\tretw.n
\t.size\ttbl, .-tbl
"""
# Trimmed but structurally faithful `xtensa-esp32s3-elf-objdump -d` output:
# a ZOL loop, a backward branch, a cross-function call, a symbol-less data
# gap (offset-form header) with a `...` filler, and a $-mangled symbol.
OBJDUMP_ASM = """\
firmware.elf: file format elf32-xtensa-le
Disassembly of section .flash.text:
40370400 <render_lut>:
40370400:\t004136 \tentry\ta1, 32
40370403:\t0c0a \tmovi.n\ta10, 0
40370405:\ta48c76 \tloop\ta4, 40370411 <render_lut+0x11>
40370408:\t3a2a \tadd.n\ta2, a10, a3
4037040a:\t020222 \tl32i\ta0, a2, 0
4037040d:\t0a1a \tadd.n\ta10, a10, a0
4037040f:\tf03d \tnop.n
40370411:\tf01d \tretw.n
40370414 <fx_mix>:
40370414:\t004136 \tentry\ta1, 32
40370417:\te5fffe \tcall8\t40370400 <render_lut>
4037041a:\t0c0a \tmovi.n\ta10, 0
4037041c:\t1baa \taddi.n\ta10, a10, 1
4037041e:\t56faff \tbnez\ta10, 4037041c <fx_mix+0x8>
40370421:\te50c00 \tcall8\t40380000 <memset>
40370424:\tf01d \tretw.n
40370428 <render_lpf_lut$constprop$0-0x1130>:
40370428:\t00000000 \till
\t...
40371558 <render_lpf_lut$constprop$0>:
40371558:\t004136 \tentry\ta1, 32
4037155b:\tf01d \tretw.n
"""
# `-mlongcalls` call sequences as objdump renders them: the linker left
# these out of range, so each is "l32r aN, <lit> (VALUE <sym>)" feeding
# "callx8 aN". Covers: adjacent load, load a few insns back, a literal
# that is a constant (offset-form annotation), no load at all, a load
# with no value annotation, and a load beyond the 8-insn window.
OBJDUMP_LONGCALL_ASM = """\
firmware.elf: file format elf32-xtensa-le
Disassembly of section .flash.text:
40380000 <render_partial>:
40380000:\t004136 \tentry\ta1, 32
40380003:\tc0d681 \tl32r\ta8, 40370100 <_stext+0x100> (40002274 <__divsf3>)
40380006:\t0008e0 \tcallx8\ta8
40380009:\tc19ea1 \tl32r\ta9, 40370104 <_stext+0x104> (473b8000 <_etext+0x100>)
4038000c:\tc0cf81 \tl32r\ta8, 40370100 <_stext+0x100> (40002274 <__divsf3>)
4038000f:\t05bd \tmov.n\ta11, a5
40380011:\t51b8 \tl32i.n\ta11, a1, 20
40380013:\t0008e0 \tcallx8\ta8
40380016:\t0009e0 \tcallx8\ta9
40380019:\t000ae0 \tcallx8\ta10
4038001c:\tf01d \tretw.n
40380020 <far_call>:
40380020:\tc0d681 \tl32r\ta8, 40370100 <_stext+0x100> (40002274 <__divsf3>)
40380023:\tf03d \tnop.n
40380025:\tf03d \tnop.n
40380027:\tf03d \tnop.n
40380029:\tf03d \tnop.n
4038002b:\tf03d \tnop.n
4038002d:\tf03d \tnop.n
4038002f:\tf03d \tnop.n
40380031:\tf03d \tnop.n
40380033:\t0008e0 \tcallx8\ta8
40380036:\tf01d \tretw.n
40380040 <no_annot>:
40380040:\tc0d681 \tl32r\ta8, 40370100
40380043:\t0008e0 \tcallx8\ta8
40380046:\tf01d \tretw.n
40380060 <memberptr>:
40380060:\tc0d681 \tl32r\ta8, 40370108 <_stext+0x108> (3fc90000 <amy_global>)
40380063:\t880848 \tl32i\ta8, a8, 32
40380066:\t0008e0 \tcallx8\ta8
40380069:\tf01d \tretw.n
40380070 <spilled>:
40380070:\tc0d681 \tl32r\ta8, 40370100 <_stext+0x100> (40002274 <__divsf3>)
40380073:\t6189 \ts32i.n\ta8, a1, 24
40380075:\t0008e0 \tcallx8\ta8
40380078:\tf01d \tretw.n
"""
class TestExtractFunctions(unittest.TestCase):
def test_gcc_functions_found(self):
funcs = asmdiff.extract_functions(GCC_ASM)
self.assertEqual(sorted(funcs), ["new_const", "old_const"])
def test_gcc_bodies_cleaned(self):
funcs = asmdiff.extract_functions(GCC_ASM)
self.assertEqual(funcs["old_const"],
["mulss\t.LC0(%rip), %xmm0", "ret"])
self.assertEqual(funcs["new_const"],
["movl\t$-5, %edi", "jmp\tldexpf@PLT"])
def test_rodata_not_captured(self):
funcs = asmdiff.extract_functions(GCC_ASM)
for body in funcs.values():
self.assertNotIn("\t.long\t1023410176", body)
self.assertFalse(any(".long" in line for line in body))
def test_clang_output(self):
funcs = asmdiff.extract_functions(CLANG_ASM)
self.assertEqual(funcs["new_const"],
["movl\t$-5, %edi", "jmp\tldexpf@PLT"])
def test_local_loop_label_kept(self):
funcs = asmdiff.extract_functions(LOOP_ASM)
self.assertIn(".L2:", funcs["looper"])
class TestAnalyze(unittest.TestCase):
def test_fold_case_no_calls(self):
insns, calls = asmdiff.analyze(["mulss\t.LC0(%rip), %xmm0", "ret"])
self.assertEqual((insns, calls), (2, []))
def test_tail_call_detected_plt_stripped(self):
insns, calls = asmdiff.analyze(["movl\t$-5, %edi", "jmp\tldexpf@PLT"])
self.assertEqual((insns, calls), (2, ["ldexpf"]))
def test_plain_call_detected(self):
_, calls = asmdiff.analyze(["call\texp2f@PLT", "mulss\t%xmm1, %xmm0"])
self.assertEqual(calls, ["exp2f"])
def test_local_jumps_and_labels_not_calls(self):
insns, calls = asmdiff.analyze(
[".L2:", "addl\t$1, %eax", "jne\t.L2", "jmp\t.L4",
"jmp\t*%rax", "ret"])
self.assertEqual(calls, [])
self.assertEqual(insns, 5) # .L2: is a label, not an instruction
def test_arm_riscv_xtensa_mnemonics(self):
self.assertEqual(asmdiff.analyze(["bl\tldexpf"])[1], ["ldexpf"])
self.assertEqual(asmdiff.analyze(["blt\ta0, a1, .L2"])[1], [])
self.assertEqual(asmdiff.analyze(["tail\tldexpf@plt"])[1], ["ldexpf"])
self.assertEqual(asmdiff.analyze(["jal\tra, exp2f"])[1], []) # reg first: not a symbol
self.assertEqual(asmdiff.analyze(["call8\texp2f"])[1], ["exp2f"])
self.assertEqual(asmdiff.analyze(["callx8\ta10"])[1], ["a10"])
self.assertEqual(asmdiff.analyze(["j\t.L4"])[1], [])
def test_duplicate_calls_reported_once(self):
_, calls = asmdiff.analyze(["call\tf", "call\tf", "call\tg"])
self.assertEqual(calls, ["f", "g"])
class TestLoopSpans(unittest.TestCase):
def test_simple_backward_branch(self):
lines = ["xorl\t%eax, %eax", ".L2:", "addl\t$1, %eax",
"cmpl\t$8, %eax", "jne\t.L2", "ret"]
self.assertEqual(asmdiff.loop_spans(lines), [(".L2", 3)])
def test_forward_branch_is_not_a_span(self):
lines = ["testl\t%edi, %edi", "jle\t.L4", "addl\t$1, %eax",
".L4:", "ret"]
self.assertEqual(asmdiff.loop_spans(lines), [])
def test_several_backedges_to_one_label_merge(self):
lines = [".L3:", "addl\t$1, %eax", "je\t.L3",
"subl\t$1, %ebx", "jne\t.L3", "ret"]
self.assertEqual(asmdiff.loop_spans(lines), [(".L3", 4)])
def test_nested_spans_reported_separately(self):
lines = [".L1:", "movl\t$0, %ecx", ".L2:", "addl\t$1, %ecx",
"cmpl\t$4, %ecx", "jne\t.L2", "decl\t%edi",
"jnz\t.L1", "ret"]
self.assertEqual(asmdiff.loop_spans(lines),
[(".L1", 6), (".L2", 3)])
def test_xtensa_zero_overhead_loop(self):
# loop* references its END label; the span is what it encloses.
lines = ["loopgt\ta3, .L5", "addi.n\ta2, a2, 1",
"s32i.n\ta2, a4, 0", ".L5:", "retw.n"]
self.assertEqual(asmdiff.loop_spans(lines), [(".L5", 2)])
def test_literal_pool_reference_ignored(self):
# .LC44 lives outside the body, so it is not a span even though
# the operand matches the label-reference pattern.
lines = ["l32r\ta8, .LC44", "ret"]
self.assertEqual(asmdiff.loop_spans(lines), [])
class TestJumpTableData(unittest.TestCase):
"""Inline data (switch jump tables, constants) emitted inside a function
body is not counted as instructions and never reads as a loop span."""
def test_table_entries_stripped_from_body(self):
body = asmdiff.extract_functions(SWITCH_ASM)["sel"]
self.assertFalse(any(".long" in line for line in body))
self.assertIn(".L4:", body) # the table's anchor label is kept
def test_table_entries_not_counted_as_instructions(self):
body = asmdiff.extract_functions(SWITCH_ASM)["sel"]
insns, calls = asmdiff.analyze(body)
self.assertEqual(insns, 22) # 27 before the fix (5 .long entries)
self.assertEqual(calls, []) # notrack jmp *%rax is not a call
def test_self_relative_table_is_not_a_phantom_span(self):
# `.long .L5-.L4` references the table base .L4 from below; without
# stripping, that reads as a backward branch and invents a loop.
body = asmdiff.extract_functions(SWITCH_ASM)["sel"]
self.assertEqual(asmdiff.loop_spans(body), [])
def test_various_data_directives_stripped(self):
# .word/.byte/.quad jump tables and constants on other targets.
body = asmdiff.extract_functions(DATA_DIRECTIVES_ASM)["tbl"]
for directive in (".word", ".byte", ".quad"):
self.assertFalse(any(directive in line for line in body), directive)
insns, _ = asmdiff.analyze(body)
self.assertEqual(insns, 4) # 8 before the fix (4 data entries)
self.assertEqual(asmdiff.loop_spans(body), [])
class TestObjdumpExtract(unittest.TestCase):
"""extract_functions_objdump: linked-ELF `objdump -d` output becomes
the same cleaned-lines shape extract_functions produces, with branch
and loop target addresses rewritten to synthetic local labels so
analyze() and loop_spans() work unchanged."""
def setUp(self):
self.funcs = asmdiff.extract_functions_objdump(OBJDUMP_ASM)
def test_function_headers_found(self):
self.assertEqual(sorted(self.funcs),
["fx_mix", "render_lpf_lut$constprop$0",
"render_lut"])
def test_data_region_headers_skipped(self):
# <sym-0x1130> marks a literal pool / symbol-less gap whose bytes
# disassemble as garbage; nothing from it may leak into a body.
for body in self.funcs.values():
self.assertFalse(any(ln.startswith("ill") for ln in body))
def test_filler_lines_skipped(self):
for body in self.funcs.values():
self.assertNotIn("...", body)
def test_insn_lines_cleaned(self):
self.assertEqual(self.funcs["render_lut"][0], "entry\ta1, 32")
def test_hex_bytes_column_dropped(self):
# The byte dump ("004136") is one token; it must never be read
# as the mnemonic or survive into the cleaned line.
for body in self.funcs.values():
for ln in body:
self.assertNotRegex(ln, r"^[0-9a-f]+\s")
def test_zol_end_label_synthesized(self):
body = self.funcs["render_lut"]
self.assertIn("loop\ta4, .L11_LEND", body)
self.assertEqual(body[-2:], [".L11_LEND:", "retw.n"])
def test_zol_span_via_loop_spans(self):
self.assertEqual(asmdiff.loop_spans(self.funcs["render_lut"]),
[(".L11_LEND", 4)])
def test_backward_branch_label_synthesized(self):
body = self.funcs["fx_mix"]
self.assertIn(".L8:", body)
self.assertIn("bnez\ta10, .L8", body)
def test_backward_branch_span(self):
self.assertEqual(asmdiff.loop_spans(self.funcs["fx_mix"]),
[(".L8", 2)])
def test_cross_function_target_uses_symbol(self):
body = self.funcs["fx_mix"]
self.assertIn("call8\trender_lut", body)
self.assertIn("call8\tmemset", body)
def test_calls_reported_by_analyze(self):
_, calls = asmdiff.analyze(self.funcs["fx_mix"])
self.assertEqual(calls, ["render_lut", "memset"])
def test_zol_body_is_call_free(self):
insns, calls = asmdiff.analyze(self.funcs["render_lut"])
self.assertEqual((insns, calls), (8, []))
class TestLongcallResolver(unittest.TestCase):
"""Xtensa -mlongcalls survivors: a callx8 fed by an "l32r aN, <lit>
(VALUE <sym>)" reports <sym> as the callee; without that evidence
the register is kept (genuinely indirect, or binutils format
drift)."""
def setUp(self):
self.funcs = asmdiff.extract_functions_objdump(OBJDUMP_LONGCALL_ASM)
def test_adjacent_load_resolved(self):
self.assertIn("callx8\t__divsf3", self.funcs["render_partial"])
def test_load_a_few_insns_back_resolved(self):
# Both __divsf3 sites resolve, including the one whose l32r is
# three instructions above the call.
body = self.funcs["render_partial"]
self.assertEqual(body.count("callx8\t__divsf3"), 2)
def test_constant_literal_not_a_callee(self):
# a9's literal annotation is <_etext+0x100> - a value, not a
# function symbol; the call must stay indirect.
self.assertIn("callx8\ta9", self.funcs["render_partial"])
def test_no_load_stays_indirect(self):
self.assertIn("callx8\ta10", self.funcs["render_partial"])
def test_calls_reported_by_analyze(self):
_, calls = asmdiff.analyze(self.funcs["render_partial"])
self.assertEqual(calls, ["__divsf3", "a9", "a10"])
def test_load_beyond_window_stays_indirect(self):
self.assertIn("callx8\ta8", self.funcs["far_call"])
def test_unannotated_load_stays_indirect(self):
self.assertIn("callx8\ta8", self.funcs["no_annot"])
def test_clobbered_register_stays_indirect(self):
# l32r loads a struct address (amy_global) but the l32i then
# replaces a8 with a member function pointer: reporting the
# struct as the callee would be wrong, so the call must stay
# indirect.
self.assertIn("callx8\ta8", self.funcs["memberptr"])
_, calls = asmdiff.analyze(self.funcs["memberptr"])
self.assertNotIn("amy_global", calls)
def test_intervening_store_does_not_block(self):
# s32i.n reads a8 (stores it to the stack) without writing it,
# so the loaded callee is still live at the call.
self.assertIn("callx8\t__divsf3", self.funcs["spilled"])
class TestElfMode(unittest.TestCase):
"""FIRMWARE.elf positional: disassemble a linked binary through the
toolchain's objdump instead of compiling, selecting functions by
name or --filter REGEX."""
def _elf(self, tmp):
p = Path(tmp) / "fw.elf"
p.write_bytes(b"\x7fELF" + b"\0" * 12)
return str(p)
def _run(self, argv):
real = asmdiff.run_objdump
asmdiff.run_objdump = lambda objdump, elf: OBJDUMP_ASM
out = io.StringIO()
try:
with contextlib.redirect_stdout(out):
status = asmdiff.main(argv)
finally:
asmdiff.run_objdump = real
return status, out.getvalue()
def _expect_error(self, argv, fragment):
real = asmdiff.run_objdump
asmdiff.run_objdump = lambda objdump, elf: OBJDUMP_ASM
err = io.StringIO()
try:
with contextlib.redirect_stderr(err), \
self.assertRaises(SystemExit) as ctx:
with contextlib.redirect_stdout(io.StringIO()):
asmdiff.main(argv)
finally:
asmdiff.run_objdump = real
self.assertIn(fragment, err.getvalue() + str(ctx.exception))
def test_is_elf_magic_not_extension(self):
with tempfile.TemporaryDirectory() as tmp:
self.assertTrue(asmdiff.is_elf(self._elf(tmp)))
fake = Path(tmp) / "not-really.elf"
fake.write_text("int main;")
self.assertFalse(asmdiff.is_elf(str(fake)))
self.assertFalse(asmdiff.is_elf(str(Path(tmp) / "absent.elf")))
def test_derive_objdump_swaps_gcc(self):
self.assertEqual(
asmdiff.derive_objdump(
["/tc/bin/xtensa-esp32s3-elf-gcc -O2 -mlongcalls"]),
"/tc/bin/xtensa-esp32s3-elf-objdump")
self.assertEqual(asmdiff.derive_objdump(["gcc -O3"]), "objdump")
self.assertIsNone(asmdiff.derive_objdump(["clang -O3"]))
self.assertEqual(asmdiff.derive_objdump(["clang -O3", "gcc -O2"]),
"objdump")
def test_named_function_listing_and_table(self):
with tempfile.TemporaryDirectory() as tmp:
status, out = self._run([self._elf(tmp), "render_lut",
"--objdump", "od"])
self.assertEqual(status, 0)
self.assertIn("render_lut:", out)
self.assertIn("loop\ta4, .L11_LEND", out)
self.assertIn("function", out) # stats table header
def test_filter_prints_table_without_listings(self):
with tempfile.TemporaryDirectory() as tmp:
status, out = self._run([self._elf(tmp), "--filter", "render_",
"--objdump", "od"])
self.assertEqual(status, 0)
self.assertIn("render_lut", out)
self.assertIn("render_lpf_lut$constprop$0", out)
self.assertNotIn("fx_mix", out)
self.assertNotIn("entry\t", out) # table only, no listings
def test_names_and_filter_combine(self):
with tempfile.TemporaryDirectory() as tmp:
status, out = self._run([self._elf(tmp), "fx_mix",
"--filter", "render_lut$",
"--objdump", "od"])
self.assertEqual(status, 0)
self.assertIn("fx_mix:", out) # named: listed
self.assertIn("render_lut", out) # filtered: in the table
def test_unknown_function_suggests_close_match(self):
with tempfile.TemporaryDirectory() as tmp:
self._expect_error([self._elf(tmp), "rendr_lut",
"--objdump", "od"],
"render_lut")
def test_bare_elf_needs_names_or_filter(self):
with tempfile.TemporaryDirectory() as tmp:
self._expect_error([self._elf(tmp), "--objdump", "od"],
"--filter")
def test_filter_matching_nothing_errors(self):
with tempfile.TemporaryDirectory() as tmp:
self._expect_error([self._elf(tmp), "--filter", "zzz",
"--objdump", "od"], "matched no function")
def test_bad_filter_regex_errors(self):
with tempfile.TemporaryDirectory() as tmp:
self._expect_error([self._elf(tmp), "--filter", "(",
"--objdump", "od"], "bad --filter regex")
def test_compile_flags_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
self._expect_error([self._elf(tmp), "f", "--pair", "a:b",
"--objdump", "od"], "disassembled")
def test_second_file_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
other = Path(tmp) / "b.c"
other.touch()
self._expect_error([self._elf(tmp), str(other),
"--objdump", "od"], "one binary")
def test_filter_without_elf_rejected(self):
self._expect_error(["x.c", "f", "--filter", "r"], "ELF input")
def test_no_gcc_in_matrix_needs_objdump(self):
with tempfile.TemporaryDirectory() as tmp:
self._expect_error([self._elf(tmp), "f", "--cc", "clang -O3"],
"--objdump")
def test_target_db_discovery_not_triggered(self):
# ELF mode never compiles, so a target's compile_commands = true
# must not launch (and fail) database discovery while the target
# is only being used to locate its objdump.
if asmdiff.tomllib is None:
self.skipTest("tomllib requires Python >= 3.11")
with tempfile.TemporaryDirectory() as tmp:
cfg = Path(tmp) / "asmdiff.toml"
cfg.write_text('[t]\ncc = "/tc/bin/xtensa-esp32s3-elf-gcc"\n'
'compile_commands = true\n')
status, out = self._run([self._elf(tmp), "render_lut",
"--config", str(cfg), "--target", "t"])
self.assertEqual(status, 0)
self.assertIn("render_lut:", out)
class TestAutoPairs(unittest.TestCase):
def test_pairs_by_convention(self):
names = ["old_const", "new_const", "old_rt", "new_rt", "helper"]
self.assertEqual(asmdiff.auto_pairs(names),
[("old_const", "new_const"), ("old_rt", "new_rt")])
def test_unmatched_old_ignored(self):
self.assertEqual(asmdiff.auto_pairs(["old_x", "new_y"]), [])
class TestSplitPositionals(unittest.TestCase):
"""SOURCE.c FUNC grammar: extra positionals are files when they
exist, function names when bare, and errors when path-like typos."""
def test_existing_file_is_a_source(self):
with tempfile.TemporaryDirectory() as tmp:
second = Path(tmp) / "b.c"
second.touch()
sources, fns = asmdiff.split_positionals(["a.c", str(second)])
self.assertEqual(sources, ["a.c", str(second)])
self.assertEqual(fns, [])
def test_bare_name_is_a_function(self):
sources, fns = asmdiff.split_positionals(["a.c", "render_lut"])
self.assertEqual(sources, ["a.c"])
self.assertEqual(fns, ["render_lut"])
def test_several_function_names(self):
sources, fns = asmdiff.split_positionals(["a.c", "f", "g"])
self.assertEqual(sources, ["a.c"])
self.assertEqual(fns, ["f", "g"])
def test_missing_source_suffix_arg_errors(self):
with self.assertRaises(SystemExit) as ctx:
asmdiff.split_positionals(["a.c", "typo.c"])
self.assertIn("no such file", str(ctx.exception))
def test_missing_path_separator_arg_errors(self):
with self.assertRaises(SystemExit) as ctx:
asmdiff.split_positionals(["a.c", "src/render"])
self.assertIn("no such file", str(ctx.exception))
def test_uppercase_asm_suffix_is_path_like(self):
with self.assertRaises(SystemExit):
asmdiff.split_positionals(["a.c", "startup.S"])
def test_first_positional_is_always_a_source(self):
sources, fns = asmdiff.split_positionals(["no_suffix_name"])
self.assertEqual(sources, ["no_suffix_name"])
self.assertEqual(fns, [])
class TestAsmOutputName(unittest.TestCase):
def test_short_command_stays_readable(self):
self.assertEqual(asmdiff.asm_output_name("gcc -O3", "h.c"),
"gcc_O3_h.s")
def test_long_command_fits_name_max(self):
cc = "/opt/toolchain/" + "x" * 300 + "/gcc -O2 -I/long/include"
name = asmdiff.asm_output_name(cc, "harness.c")
self.assertLessEqual(len(name), 255)
self.assertTrue(name.endswith("_harness.s"))
def test_truncated_commands_do_not_collide(self):
base = "/opt/toolchain/" + "x" * 300 + "/gcc -O2"
self.assertNotEqual(asmdiff.asm_output_name(base, "h.c"),
asmdiff.asm_output_name(base + " -DX", "h.c"))
class TestBuildMatrix(unittest.TestCase):
CONFIG = {"default": "s3",
"s3": {"cc": "xtensa-gcc", "flags": ["-O2", "-mlongcalls"]},
"host": {"cc": "gcc", "flags": ["-O3"]}}
def test_explicit_cc_used_verbatim(self):
self.assertEqual(asmdiff.build_matrix(["tcc -O1"], [], None, None),
["tcc -O1"])
def test_targets_resolve_and_follow_cc_entries(self):
matrix = asmdiff.build_matrix(["tcc -O1"], ["host"],
self.CONFIG, "cfg.toml")
self.assertEqual(matrix, ["tcc -O1", "gcc -O3"])
def test_config_default_target_used_when_nothing_given(self):
self.assertEqual(asmdiff.build_matrix([], [], self.CONFIG, "c"),
["xtensa-gcc -O2 -mlongcalls"])
def test_config_default_may_be_a_list(self):
cfg = dict(self.CONFIG, default=["s3", "host"])
self.assertEqual(asmdiff.build_matrix([], [], cfg, "c"),
["xtensa-gcc -O2 -mlongcalls", "gcc -O3"])
def test_fallback_is_bare_gcc_and_clang(self):
self.assertEqual(asmdiff.build_matrix([], [], None, None),
["gcc -O3", "clang -O3"])
def test_unknown_target_errors_and_lists_known(self):
with self.assertRaises(SystemExit) as ctx:
asmdiff.build_matrix([], ["nope"], self.CONFIG, "cfg.toml")
self.assertIn("host", str(ctx.exception))
self.assertIn("s3", str(ctx.exception))
def test_target_flags_must_be_an_array(self):
cfg = {"bad": {"cc": "gcc", "flags": "-O3"}}
with self.assertRaises(SystemExit):
asmdiff.build_matrix([], ["bad"], cfg, "cfg.toml")
def test_target_needs_cc_string(self):
cfg = {"bad": {"flags": ["-O3"]}}
with self.assertRaises(SystemExit):
asmdiff.build_matrix([], ["bad"], cfg, "cfg.toml")
class TestIncludeFlags(unittest.TestCase):
"""Lifting include/define flags out of one recorded compile command."""
def test_glued_and_split_include_paths(self):
toks = ["cc", "-Iinc", "-I", "inc2", "-c", "a.c"]
self.assertEqual(asmdiff.include_flags(toks, "/build"),
["-I", "/build/inc", "-I", "/build/inc2"])
def test_absolute_paths_left_alone(self):
self.assertEqual(asmdiff.include_flags(["-I/abs/inc"], "/build"),
["-I", "/abs/inc"])
def test_defines_glued_and_split(self):
self.assertEqual(
asmdiff.include_flags(["-DFOO=1", "-D", "BAR", "-UNDEBUG"], "/b"),
["-DFOO=1", "-DBAR", "-UNDEBUG"])
def test_system_and_forced_include_families(self):
toks = ["-isystem", "sys", "-iquote", "q", "-idirafter", "d",
"-include", "cfg.h", "-imacros", "m.h"]
self.assertEqual(
asmdiff.include_flags(toks, "/build"),
["-isystem", "/build/sys", "-iquote", "/build/q",
"-idirafter", "/build/d", "-include", "/build/cfg.h",
"-imacros", "/build/m.h"])
def test_non_include_flags_and_source_dropped(self):
toks = ["gcc", "-O2", "-std=c11", "-Wall", "-g", "-c", "a.c",
"-o", "a.o", "-Iinc"]
self.assertEqual(asmdiff.include_flags(toks, "/b"), ["-I", "/b/inc"])
def test_dangling_flag_at_end_ignored(self):
self.assertEqual(asmdiff.include_flags(["-Iinc", "-I"], "/b"),
["-I", "/b/inc"])
def test_lowercase_isystem_not_split_as_capital_I(self):
# -isystem must not be read as -I + "system".
self.assertEqual(asmdiff.include_flags(["-isystem", "/s"], ""),
["-isystem", "/s"])
class TestSpecsAndSysroot(unittest.TestCase):
"""Driver flags that change the header environment (-specs, --sysroot)."""
def test_specs_glued_bare_name_not_resolved(self):
# A bare specs name (no path separator) is found in the compiler's
# own search dirs; gluing a directory onto it would break it.
self.assertEqual(
asmdiff.include_flags(["-specs=picolibc.specs"], "/build"),
["-specs=picolibc.specs"])
def test_specs_with_path_resolved_against_directory(self):
self.assertEqual(
asmdiff.include_flags(["-specs=./custom/my.specs"], "/build"),
["-specs=/build/custom/my.specs"])
def test_specs_split_and_double_dash(self):
self.assertEqual(
asmdiff.include_flags(["-specs", "nano.specs",
"--specs=nosys.specs"], "/b"),
["-specs=nano.specs", "--specs=nosys.specs"])
def test_sysroot_glued_and_split(self):
self.assertEqual(
asmdiff.include_flags(["--sysroot=sr", "--sysroot", "/abs"],
"/b"),
["--sysroot=/b/sr", "--sysroot=/abs"])
class TestResponseFiles(unittest.TestCase):
"""GCC @file response files inside compile_commands entries."""
def test_flags_inside_response_file_are_borrowed(self):
with tempfile.TemporaryDirectory() as tmp:
rsp = Path(tmp) / "toolchain" / "cflags"
rsp.parent.mkdir()
rsp.write_text("-mlongcalls\n-specs=picolibc.specs\n-Irspinc\n")
src = Path(tmp) / "a.c"
src.touch()
db = Path(tmp) / "compile_commands.json"
db.write_text(json.dumps([{
"directory": tmp, "file": str(src),
"command": f"cc -Iinc @{rsp} -c a.c"}]))
asmdiff._DB_CACHE.clear()
self.assertEqual(
asmdiff.compile_commands_flags(str(db), str(src)),
["-I", f"{tmp}/inc", "-specs=picolibc.specs",
"-I", f"{tmp}/rspinc"])
def test_relative_response_file_resolves_against_directory(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "cflags").write_text("-DFROMRSP")
self.assertEqual(
asmdiff._expand_response_files(["@cflags"], tmp),
["-DFROMRSP"])
def test_nested_response_files(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "outer").write_text("@inner -DOUTER")
(Path(tmp) / "inner").write_text("-DINNER")
self.assertEqual(
asmdiff._expand_response_files(["@outer"], tmp),
["-DINNER", "-DOUTER"])
def test_missing_response_file_warns_and_continues(self):
err = io.StringIO()
with contextlib.redirect_stderr(err):
out = asmdiff._expand_response_files(["-DKEEP", "@/nope/x"], "/b")
self.assertEqual(out, ["-DKEEP"])
self.assertIn("/nope/x", err.getvalue())
class TestCompileCommandsFlags(unittest.TestCase):
def _db(self, tmp, entries):
path = Path(tmp) / "compile_commands.json"
path.write_text(json.dumps(entries))
asmdiff._DB_CACHE.clear()
return str(path)
def test_matches_by_resolved_path_command_string(self):
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "src" / "foo.c"
src.parent.mkdir()
src.touch()
db = self._db(tmp, [{
"directory": tmp, "file": str(src),
"command": f"cc -Iinc -DX=1 -c {src} -o foo.o"}])
self.assertEqual(asmdiff.compile_commands_flags(db, str(src)),
["-I", f"{tmp}/inc", "-DX=1"])
def test_matches_relative_file_and_arguments_array(self):
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "foo.c"
src.touch()
db = self._db(tmp, [{
"directory": tmp, "file": "foo.c",
"arguments": ["cc", "-Iinc", "-c", "foo.c"]}])
self.assertEqual(asmdiff.compile_commands_flags(db, str(src)),
["-I", f"{tmp}/inc"])
def test_missing_source_errors(self):
with tempfile.TemporaryDirectory() as tmp:
db = self._db(tmp, [{"directory": tmp, "file": f"{tmp}/a.c",
"command": "cc -c a.c"}])
with self.assertRaises(SystemExit) as ctx:
asmdiff.compile_commands_flags(db, f"{tmp}/b.c")
self.assertIn("not found", str(ctx.exception))
def test_same_name_different_path_hint(self):
with tempfile.TemporaryDirectory() as tmp:
db = self._db(tmp, [{"directory": tmp,
"file": f"{tmp}/other/foo.c",
"command": "cc -c foo.c"}])
with self.assertRaises(SystemExit) as ctx:
asmdiff.compile_commands_flags(db, f"{tmp}/foo.c")
self.assertIn("different path", str(ctx.exception))
def test_bad_json_shape_errors(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "cc.json"
path.write_text('{"not": "a list"}')
asmdiff._DB_CACHE.clear()
with self.assertRaises(SystemExit):
asmdiff.compile_commands_flags(str(path), "x.c")
class TestTargetCompileCommands(unittest.TestCase):
def test_target_carries_expanded_db_path(self):
os.environ["ASMDIFF_TEST_DB"] = "/proj/build"
try:
cfg = {"t": {"cc": "gcc", "flags": ["-O2"],
"compile_commands": "$ASMDIFF_TEST_DB/cc.json"}}
matrix = asmdiff.build_matrix([], ["t"], cfg, "c")
self.assertEqual(matrix, ["gcc -O2"]) # str value unchanged
self.assertEqual(matrix[0].compile_commands,
"/proj/build/cc.json") # attribute carried
finally:
del os.environ["ASMDIFF_TEST_DB"]
def test_compile_commands_must_be_a_string(self):
cfg = {"t": {"cc": "gcc", "flags": [], "compile_commands": ["x"]}}
with self.assertRaises(SystemExit):
asmdiff.build_matrix([], ["t"], cfg, "c")
def test_cc_entries_have_no_db_attribute(self):
matrix = asmdiff.build_matrix(["gcc -O3"], [], None, None)
self.assertIsNone(getattr(matrix[0], "compile_commands", None))
@contextlib.contextmanager
def _inside(directory):
"""Run a block with CWD set to ``directory`` (discovery is CWD-based)."""
prev = os.getcwd()
os.chdir(directory)
try:
yield
finally:
os.chdir(prev)
class TestFindCompileCommands(unittest.TestCase):
"""Auto-discovery of compile_commands.json by walking up from the CWD."""
def _touch_db(self, directory):
directory.mkdir(parents=True, exist_ok=True)
(directory / "compile_commands.json").write_text("[]")
def _repo(self, tmp):
"""A fake repo root: .git bounds the walk so tests never escape
the tempdir and pick up a stray database further up."""
root = Path(tmp)
(root / ".git").mkdir()
return root
def test_nearer_hits_win(self):
with tempfile.TemporaryDirectory() as tmp:
root = self._repo(tmp)
cwd = root / "sub"
cwd.mkdir()
for where, expect in [(root / "build", root / "build"),
(root, root),
(cwd / "build", cwd / "build"),