-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathStructureAnalysis.cs
More file actions
1571 lines (1481 loc) · 58.8 KB
/
Copy pathStructureAnalysis.cs
File metadata and controls
1571 lines (1481 loc) · 58.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
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
#region License
/*
* Copyright (C) 1999-2023 John Källén.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#endregion
using Reko.Core;
using Reko.Core.Absyn;
using Reko.Core.Collections;
using Reko.Core.Diagnostics;
using Reko.Core.Expressions;
using Reko.Core.Graphs;
using Reko.Core.Operators;
using Reko.Core.Types;
using Reko.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Reko.Structure
{
/// <summary>
/// This class starts with the basic block control graph of a decompiled
/// procedure and converts it into high-level structured code.
/// </summary>
/// <remarks>
/// Inspired by the algorithm described in:
/// Native x86 Decompilation using Semantics-Preserving Structural Analysis
/// and Iterative Control-Flow Structuring.
/// </remarks>
public class StructureAnalysis : IStructureAnalysis
{
private static readonly TraceSwitch trace = new TraceSwitch(nameof(StructureAnalysis), "Control ProgramFlow structuring")
{
Level = TraceLevel.Warning,
};
private readonly Program program;
private readonly Procedure proc;
private DirectedGraph<Region> regionGraph;
private Region entry;
private DominatorGraph<Region> doms;
private DominatorGraph<Region> postDoms;
private Queue<(Region, ISet<Region>)> unresolvedCycles;
private Queue<Region> unresolvedSwitches;
private readonly IDecompilerEventListener eventListener;
#nullable disable
public StructureAnalysis(IDecompilerEventListener listener, Program program, Procedure proc)
{
this.eventListener = listener;
this.program = program;
this.proc = proc;
}
#nullable enable
public void Structure()
{
var cfgc = new ControlFlowGraphCleaner(proc);
cfgc.Transform();
var ccc = new CompoundConditionCoalescer(proc);
ccc.Transform();
proc.Body = new List<AbsynStatement>();
var reg = Execute();
//$REVIEW: yeecch. Should return the statements, and
// caller decides what to do with'em. Probably
// return an abstract Procedure, rather than overloading
// the IR procedure.
proc.Body.AddRange(reg.Statements);
// Post processing steps
var iftosw = new IfCascadeToSwitchRewriter(proc);
iftosw.Transform();
var deci = new DeclarationInserter(proc);
deci.Transform();
var flr = new ForLoopRewriter(proc);
flr.Transform();
var trrm = new TailReturnRemover(proc);
trrm.Transform();
var pp = new ProcedurePrettifier(proc);
pp.Transform();
}
/// <summary>
/// Executes the core of the analysis
/// </summary>
/// <remarks>
/// The algorithm visits nodes in post-order in each iteration. This
/// means that all descendants of a node will be visited (and
/// hence had the chance to be reduced) before the node itself.
/// The algorithm’s behavior when visiting node _n_
/// depends on whether the region at _n_
/// is acyclic (has no loop) or not. For an acyclic region, the
/// algorithm tries to match the subgraph
/// at _n_to an acyclic schemas (3.2). If there is no match,
/// and the region is a switch candidate, then it attempts to
/// refine the region at _n_ into a switch region.
///
/// If _n_ is cyclic, the algorithm
/// compares the region at _n_ to the cyclic schemata.
/// If this fails, it refines _n_ into a loop (3.6).
///
/// If both matching and refinement do not make progress, the
/// current node _n_ is then skipped for the current iteration of
/// the algorithm. If there is an iteration in which all
/// nodes are skipped, i.e., the algorithm makes no progress, then
/// the algorithm employs a last resort refinement (3.7) to
/// ensure that progress can be made in the next iteration.
/// </remarks>
public Region Execute()
{
(this.regionGraph, this.entry) = BuildRegionGraph(proc);
int iterations = 0;
int oldCount;
int newCount;
do
{
if (eventListener.IsCanceled())
break;
++iterations;
if (iterations > 1000)
{
eventListener.Warn(
eventListener.CreateProcedureNavigator(program, proc),
"Structure analysis stopped making progress, quitting. Please report this issue at https://github.com/uxmal/reko");
DumpGraph();
break;
}
oldCount = regionGraph.Nodes.Count;
this.doms = new DominatorGraph<Region>(this.regionGraph, this.entry);
this.unresolvedCycles = new Queue<(Region, ISet<Region>)>();
this.unresolvedSwitches = new Queue<Region>();
var postOrder = new DfsIterator<Region>(regionGraph).PostOrder(entry).ToList();
foreach (var n in postOrder)
{
Probe();
bool didReduce;
do
{
if (eventListener.IsCanceled())
break;
didReduce = ReduceAcyclic(n);
if (!didReduce && IsCyclic(n))
{
didReduce = ReduceCyclic(n);
}
} while (didReduce);
}
newCount = regionGraph.Nodes.Count;
if (newCount == oldCount && newCount > 1)
{
// Didn't make any progress this round,
// try refining unstructured regions
ProcessUnresolvedRegions();
}
} while (regionGraph.Nodes.Count > 1);
return entry;
}
/// <summary>
/// Handy place to put breakpoints during debugging of structuring algorithm.
/// </summary>
[Conditional("DEBUG")]
private void Probe()
{
}
private DominatorGraph<Region> BuildPostDoms()
{
var revGraph = new ReverseGraph(regionGraph);
var exitNode = new Region(new Block(proc, proc.EntryAddress, "DummyExitBlock")) { Type = RegionType.Tail };
revGraph.Nodes.Add(exitNode);
var tailRegions = regionGraph.Nodes.Where(n => n.Type == RegionType.Tail);
foreach (var r in tailRegions)
{
revGraph.AddEdge(exitNode, r);
}
return new DominatorGraph<Region>(revGraph, exitNode);
}
/// <summary>
/// Builds a graph of regions based on the basic blocks of the code.
/// </summary>
/// <param name="proc"></param>
/// <returns></returns>
public static (DirectedGraph<Region>, Region) BuildRegionGraph(Procedure proc)
{
var rgb = new RegionGraphBuilder(proc);
return rgb.Build();
}
/// <summary>
/// Determines if n is the header of a cyclic set of regions.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private bool IsCyclic(Region n)
{
return regionGraph.Predecessors(n).Any(pred => pred == n || IsBackEdge(pred, n));
}
private bool IsBackEdge(Region a, Region b)
{
return doms.DominatesStrictly(b, a);
}
/// <summary>
/// Attempts to match and reduce acyclic region.
/// </summary>
/// <param name="n"></param>
/// <returns>True if a reduction occurred</returns>
public bool ReduceAcyclic(Region n)
{
bool didReduce;
switch (n.Type)
{
case RegionType.Condition:
didReduce = ReduceIfRegion(n);
break;
case RegionType.IncSwitch:
didReduce = ReduceSwitchRegion(n);
break;
case RegionType.Linear:
didReduce = ReduceSequence(n);
break;
case RegionType.Tail:
didReduce = false;
break;
default:
throw new NotImplementedException();
}
Probe();
return didReduce;
}
private void EnqueueUnresolvedSwitch(Region switchHead)
{
// Do not refine switch region if there are unresolved cycles
if (unresolvedCycles.Count == 0)
this.unresolvedSwitches.Enqueue(switchHead);
}
private void EnqueueUnresolvedLoop(Region head, ISet<Region> loop)
{
// Do not refine cycle if there are unresolved switches
if (unresolvedSwitches.Count == 0)
this.unresolvedCycles.Enqueue((head, loop));
}
public bool ProcessUnresolvedRegions()
{
if (unresolvedCycles.Count != 0)
{
var cycle = unresolvedCycles.Dequeue();
if (RefineLoop(cycle.Item1, cycle.Item2))
return true;
}
if (unresolvedSwitches.Count != 0)
{
var switchHead = unresolvedSwitches.Dequeue();
RefineIncSwitch(switchHead);
return true;
}
var postOrder = new DfsIterator<Region>(regionGraph).PostOrder(entry).ToList();
foreach (var n in postOrder)
{
if (VirtualizeReturn(n))
return true;
}
foreach (var n in postOrder)
{
if (CoalesceTailRegion(n, regionGraph.Nodes))
return true;
}
foreach (var n in postOrder)
{
if (LastResort(n))
return true;
}
return false;
}
/// <summary>
/// Replace edge to return statement with just return statement.
/// </summary>
private bool VirtualizeReturn(Region n)
{
VirtualEdge? returnEdge = null;
foreach (var s in regionGraph.Successors(n))
if (s.IsReturn)
returnEdge = new VirtualEdge(n, s, VirtualEdgeType.Goto);
if (returnEdge != null)
{
VirtualizeEdge(returnEdge);
return true;
}
return false;
}
/// <summary>
/// Identifies if-then or if-then-else schemas in the region graph
/// and reduces them out of the graph.
/// </summary>
/// <param name="n">The header of the possible if-region</param>
/// <returns></returns>
private bool ReduceIfRegion(Region n)
{
var ss = regionGraph.Successors(n).ToArray();
var cond = n.Expression!;
var el = ss[0];
var th = ss[1];
var elS = LinearSuccessor(el);
var thS = LinearSuccessor(th);
if (elS == th)
{
if (RefinePredecessor(n, el))
return false;
// Collapse (If else) into n.
n.Statements.Add(new AbsynIf(cond.Invert(), el.Statements));
RemoveEdge(n, el);
if (elS != null)
RemoveEdge(el, elS);
RemoveRegion(el);
n.Type = RegionType.Linear;
n.Expression = null;
return true;
}
else if (thS == el)
{
if (RefinePredecessor(n, th))
return false;
// Collapse (if-then) into n
n.Statements.Add(new AbsynIf(cond, th.Statements));
RemoveEdge(n, th);
if (thS != null)
RemoveEdge(th, thS);
RemoveRegion(th);
n.Type = RegionType.Linear;
n.Expression = null;
return true;
}
else if (elS != null && elS == thS)
{
if (RefinePredecessor(n, th) |
RefinePredecessor(n, el))
return false;
// Collapse (If then else) into n.
n.Statements.Add(new AbsynIf(cond.Invert(), el.Statements, th.Statements));
RemoveEdge(n, el);
RemoveEdge(n, th);
RemoveEdge(el, elS);
RemoveEdge(th, thS);
RemoveRegion(th);
RemoveRegion(el);
regionGraph.AddEdge(n, elS);
n.Type = RegionType.Linear;
n.Expression = null;
return true;
}
return false;
}
private bool ReduceSequence(Region n)
{
var s = regionGraph.Successors(n).First();
if (regionGraph.Predecessors(s).Count == 1)
{
// Sequence!
trace.Verbose("Concatenated {0} and {1}", n.Block.DisplayName, s.Block.DisplayName);
n.Type = s.Type;
n.Expression = s.Expression;
n.Statements.AddRange(s.Statements);
RemoveEdge(n, s);
ReplaceSuccessors(s, n);
RemoveRegion(s);
return true;
}
else
return false;
}
/// <summary>
/// Switch regions.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private bool ReduceSwitchRegion(Region n)
{
var follow = GetSwitchFollow(n);
bool irregularEntries = HasIrregularEntries(n, follow);
if (!irregularEntries && (follow != null || AllCasesAreTails(n)))
{
return ReduceIncSwitch(n, follow);
}
// It's a switch region, but we are unable to collapse it.
// Schedule it for refinement after the whole graph has been
// traversed.
EnqueueUnresolvedSwitch(n);
return false;
}
#if NILZ
3.4 Switch Refinement
If the subgraph at node _n_ is acyclic but fails to match a
known schema, we try to refine the subgraph into a switch.
Regions that would match a switch schema in Table 3
but contain extra edges are switch candidates. A switch
candidate can fail to match the switch schema if it has
extra incoming edges or multiple successors. For instance,
the nodes in the IncSwitch [] box in Figure 4 would not
be identified as an IncSwitch [] region because there is an
extra incoming edge to the default case node.
We first refine switch candidates by ensuring that the
switch head is the only predecessor for each case node.
We remove any other incoming edge by virtualizing them.
The next step is to ensure there is a single successor of all
nodes in the switch. To find the successor, we first identify
the immediate post-dominator of the switch head. If this
node is the successor of any of the case nodes, we select
it as the switch successor. If not, we select the node that
(1) is a successor of a case node, (2) is not a case node
itself, and (3) has the highest number of incoming edges
from case nodes. After we have identified the successor,
we remove all outgoing edges from the case nodes to other
nodes by virtualizing them
After refinement, a switch candidate is usually col-
lapsed to a IncSwitch[] region. For instance, a common
implementation strategy for switches is to redirect inputs
handled by the default case (e.g., x > 20) to a default
node, and use a jump table for the remaining cases (e.g.,
x in {0..20}. This relationship is depicted in Figure
4,
along with the corresponding region types. Because the
jump table only handles a few cases, it is recognized as an
IncSwitch[]. However, because the default node handles
all other cases, together they constitute a Switch[].
#endif
/// <summary>Refines an incomplete switch statement</summary>
/// <remarks>
/// A switch candidate is refined by first virtualizing incoming
/// edges to any node other than the switch head.
/// The next step is to ensure there is a single successor of
/// all nodes in the switch. The immediate post-dominator
/// of the switch head is selected as the successor if it is the
/// successor of any of the case nodes. Otherwise, the node
/// that (1) is a successor of a case node, (2) is not a case
/// node itself, and (3) has the highest number of incoming
/// edges from case nodes is chosen as the successor. After
/// the successor has been identified, any outgoing edge from
/// the switch that does not go to the successor is virtualized.
/// [Pavel Tomin's note. Virtualizing of all outgoing edges
/// described by Schwartz causes incorrect refinement of switch
/// with irregular case exits. Use loop lexical nodes definition
/// method to find case body. Then virtualize any edge
/// leaving the case body that does not go to the successor]
/// After refinement, a switch candidate is usually collapsed
/// to a IncSwitch[·] region. For instance, a common
/// implementation strategy for switches is to redirect inputs
/// handled by the default case (e.g., x > 20) to a default
/// node, and use a jump table for the remaining cases (e.g.,
/// x in [0,20]). This relationship is depicted in Figure 4,
/// along with the corresponding region types. Because the
/// jump table only handles a few cases, it is recognized as an
/// IncSwitch[·]. However, because the default node handles
/// all other cases, together they constitute a Switch[·].
/// </remarks>
private void RefineIncSwitch(Region n)
{
if (VirtualizeIrregularSwitchEntries(n))
return;
var follow = FindIrregularSwitchFollowRegion(n);
var switchBody = FindSwitchBody(n, follow);
if (VirtualizeIrregularSwitchExits(switchBody, follow))
return;
var switchNodes = switchBody.Values.Aggregate(
(s, nodes) => { s.UnionWith(nodes); return s; });
foreach (var node in switchNodes)
{
if (CoalesceTailRegion(node, switchNodes))
return;
}
LastResort(switchNodes);
}
/// <summary>
/// Find all irregular switch entries and virtualize them.
/// </summary>
/// <param name="n"></param>
/// <returns>True if one or more irregular entry was virtualized.
/// this opens up the possibility of further refinements.
/// </returns>
private bool VirtualizeIrregularSwitchEntries(Region n)
{
var vEdges = new List<VirtualEdge>();
trace.Verbose(" Virtualizing switch node {0}", n.Block!.DisplayName);
foreach (var s in regionGraph.Successors(n).Distinct())
{
var pp = n;
var ss = s;
trace.Verbose(" Examining {0} which has {1} predecessors", ss, regionGraph.Predecessors(ss).Count);
foreach (var sp in regionGraph.Predecessors(ss))
{
if (sp != pp)
vEdges.Add(new VirtualEdge(sp, ss, VirtualEdgeType.Goto));
}
}
if (vEdges.Count == 0)
return false;
foreach (var vEdge in vEdges)
{
VirtualizeEdge(vEdge);
}
return true;
}
/// <summary>
/// To find the successor, we first identify
/// the immediate post-dominator of the switch head. If this
/// node is the successor of any of the case nodes, we select
/// it as the switch successor. If not, we select the node that
/// (1) is a successor of a case node, (2) is not a case node
/// itself, and (3) has the highest number of incoming edges
/// from case nodes.
/// </summary>
private Region FindIrregularSwitchFollowRegion(Region n)
{
this.postDoms = BuildPostDoms();
var immPDom = this.postDoms.ImmediateDominator(n)!;
var caseNodes = regionGraph.Successors(n).ToHashSet();
if (caseNodes.Any(s => regionGraph.Successors(s).Contains(immPDom)))
return immPDom;
int incoming(Region r)
{
return regionGraph.Predecessors(r)
.Where(p => caseNodes!.Contains(p))
.Count();
}
var candidates = caseNodes.SelectMany(c => regionGraph.Successors(c))
.Where(c => !caseNodes.Contains(c))
.ToList();
var best = candidates
.Select(c => new {
Region = c,
Score = incoming(c)
})
.OrderByDescending(c => c.Score)
.First();
return best.Region;
}
private IDictionary<Region, ISet<Region>> FindSwitchBody(
Region n, Region follow)
{
var caseNodesMap = new Dictionary<Region, ISet<Region>>();
var caseEntries = regionGraph.Successors(n).ToHashSet();
foreach (var c in caseEntries)
{
var caseSet = new HashSet<Region>() { c };
caseNodesMap[c] = GetLexicalNodes(c, follow, caseSet);
}
return caseNodesMap;
}
/// <summary>
/// After we have identified the successor of a switch, we remove
/// any edge leaving the case body that does not go to the successor by
/// virtualizing them.
/// </summary>
private bool VirtualizeIrregularSwitchExits(
IDictionary<Region, ISet<Region>> switchBody, Region follow)
{
foreach (var caseBody in switchBody.Values)
{
if (VirtualizeIrregularCaseExits(follow, caseBody))
return true;
}
return false;
}
private bool VirtualizeIrregularCaseExits(Region follow, ISet<Region> caseBody)
{
bool virtualized = false;
var vEdges = new List<VirtualEdge>();
foreach (var n in caseBody)
{
var leavingNodes = regionGraph.Successors(n).
Where(s => !caseBody.Contains(s) && s != follow);
foreach (var s in leavingNodes)
{
vEdges.Add(new VirtualEdge(n, s, VirtualEdgeType.Goto));
}
}
foreach (var vEdge in vEdges)
{
virtualized = true;
VirtualizeEdge(vEdge);
}
return virtualized;
}
private bool HasIrregularEntries(Region n, Region? follow)
{
foreach (var s in regionGraph.Successors(n).Where(r => r != follow).Distinct())
{
if (regionGraph.Predecessors(s).Any(p => (p != n)))
return true;
}
return false;
}
private Region? GetSwitchFollow(Region n)
{
Region? follow = null;
foreach (var s in regionGraph.Successors(n))
{
if (s == follow)
continue;
var ss = LinearSuccessor(s);
if (s.Type != RegionType.Tail)
{
if (ss == null)
return null;
if (follow == null)
follow = ss;
else if (ss != follow)
return null;
}
}
return follow;
}
private bool AllCasesAreTails(Region n)
{
return regionGraph.Successors(n).All(s => s.Type == RegionType.Tail);
}
private bool ReduceIncSwitch(Region n, Region? follow)
{
Expression exp = n.Expression!;
//$REVIEW: workaround for when the datatype of n.Expression
// is non-integral. What causes this?
if (exp.DataType is not PrimitiveType pt)
{
eventListener.Warn(eventListener.CreateBlockNavigator(this.program, n.Block), "Non-integral switch expression");
pt = PrimitiveType.CreateWord(exp.DataType.BitSize);
}
var (switchExp, offset) = GetConstantOffset(exp);
var cases = CollectSwitchCases(n);
var sw = MakeSwitchStatement(n, switchExp, follow, pt, offset, cases);
n.Statements.Add(sw);
n.Expression = null;
if (follow != null)
{
n.Type = RegionType.Linear;
regionGraph.AddEdge(n, follow);
}
else
{
n.Type = RegionType.Tail;
}
return true;
}
private AbsynSwitch MakeSwitchStatement(Region n, Expression switchExp, Region? follow, PrimitiveType pt, long offset, Dictionary<Region, List<int>> cases)
{
var stms = new List<AbsynStatement>();
foreach (var succ in cases.Keys)
{
foreach (int c in cases[succ])
{
stms.Add(new AbsynCase(Constant.Create(pt, c + offset)));
}
if (succ == follow)
{
stms.Add(new AbsynBreak());
}
else
{
stms.AddRange(succ.Statements);
if (succ.Type != RegionType.Tail)
{
stms.Add(new AbsynBreak());
}
}
cases[succ].ForEach(c => RemoveEdge(n, succ));
if (follow != null)
{
RemoveEdge(succ, follow);
}
if (succ != follow)
{
RemoveRegion(succ);
}
}
var sw = new AbsynSwitch(switchExp, stms);
return sw;
}
private (Expression, long) GetConstantOffset(Expression exp)
{
if (exp is BinaryExpression bin &&
bin.Right is Constant offset &&
offset.IsValid)
{
if (bin.Operator.Type == OperatorType.IAdd)
{
return (bin.Left, -offset.ToInt64());
}
else if (bin.Operator.Type == OperatorType.ISub)
{
return (bin.Left, offset.ToInt64());
}
}
return (exp, 0);
}
/// <summary>
/// Collects the cases of a switch statement such that cases with
/// the same destination region are collected in the same list.
/// </summary>
/// <param name="n">The 'head' of the switch statement.</param>
/// <returns>A mapping from Region to a list of the case values
/// that jump to that region.</returns>
private Dictionary<Region, List<int>> CollectSwitchCases(Region n)
{
var succs = regionGraph.Successors(n).ToArray();
var cases = new Dictionary<Region, List<int>>();
for (int i = 0; i < succs.Length; ++i)
{
if (!cases.ContainsKey(succs[i]))
cases.Add(succs[i], new List<int>());
cases[succs[i]].Add(i);
}
return cases;
}
/// <summary>
/// Finds all predecessors of <paramref name="s"/> that aren't
/// the structured predecessor <paramref name="n"/>.
/// </summary>
/// <param name="n"></param>
/// <param name="s"></param>
/// <returns>True if unstructured predecessors were found.
/// </returns>
private bool RefinePredecessor(Region n, Region s)
{
ISet<Region> unstructuredPreds = new HashSet<Region>(regionGraph.Predecessors(s).Where(p => p != n));
if (unstructuredPreds.Count == 0)
return false;
return true;
}
private void RemoveRegion(Region n)
{
trace.Verbose("Removing region {0} from graph", n.Block.DisplayName);
regionGraph.Nodes.Remove(n);
Probe();
}
private void RemoveEdge(Region from, Region to)
{
trace.Verbose("Removing edge {0} -> {1} from graph", from, to);
regionGraph.RemoveEdge(from, to);
}
/// <summary>
/// If <paramref name="n"/> is linear region, returns
/// its successor. Otherwise returns null.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private Region? LinearSuccessor(Region n)
{
if (n.Type != RegionType.Linear)
return null;
return SingleSuccessor(n);
}
/// <summary>
/// If <paramref name="n"/> has a single successor, returns
/// it. Otherwise returns null.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private Region? SingleSuccessor(Region n)
{
var succ = regionGraph.Successors(n);
if (succ.Count != 1)
return null;
return succ.First();
}
private Region? SinglePredecessor(Region n)
{
var succ = regionGraph.Predecessors(n);
if (succ.Count != 1)
return null;
return succ.First();
}
[Conditional("DEBUG")]
private void DumpGraph()
{
foreach (var n in regionGraph.Nodes)
{
DumpRegion(n);
}
Debug.WriteLine("");
Debug.WriteLine("====");
}
[Conditional("DEBUG")]
private void DumpRegion(Region n)
{
Debug.Print("Node: {0} ({1})", n.Block.DisplayName, n.Type);
Debug.Print(" Pred: {0}", string.Join(" ", regionGraph.Predecessors(n).Select(p => p.Block.DisplayName)));
var sb = new StringWriter();
n.Write(sb);
Debug.Write(sb.ToString());
if (n.Expression != null)
{
Debug.Print(" Condition: {0}", n.Expression);
}
Debug.Print(" Succ: {0}", string.Join(" ", regionGraph.Successors(n).Select(s => s.Block.DisplayName)));
Debug.WriteLine("");
}
private void ReplaceSuccessors(Region old, Region gnu)
{
var oldSuccs = regionGraph.Successors(old).ToList();
foreach (var s in oldSuccs)
{
regionGraph.RemoveEdge(old, s);
regionGraph.AddEdge(gnu, s);
}
Probe();
}
#if NILZ
3.3
Tail Regions and Edge Virtualization
When no subgraphs in the CFG match known schemas,
the algorithm is stuck and the CFG must be refined before
more structure can be recovered. The insight behind
refinement is that removing an edge from the CFG may
allow a schema to match, and iterative refinement
refersto the repeated application of refinement until a match is
possible. Of course, each edge in the CFG represents a
possible control flow, and we must represent this control
flow in some other way to preserve the program semantics.
We call removing the edge in a way that preserves control
flow _virtualizing_ the edge, since the decompiled program
behaves as if the edge was present, even though it is not.
Edges are virtualized collapsing the
source node of the edge into a tail region (see 2.1). Tail
regions explicitly denote that there should be a control
transfer at the end of the region. For instance, to virtualize
the edge (n1, n2) we remove the edge from the CFG,
insert a fresh label _l_ at the start of n2, and collapse
n1 to a tail region that denotes there should be a
goto l statement at the end of region n1
. Tail regions can also be translated into break or
continue statements when used
inside a switch or loop. Because the tail region explicitly
represents the control flow of the virtualized edge, it is
safe to remove the edge from the graph and ignore it when
doing future pattern matches.
#endif
/// <summary>
/// Edges are virtualized by removing them from the
/// graph, then adding a label in the destination block
/// and collapse the source region to a tail.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
public void VirtualizeEdge(VirtualEdge vEdge)
{
AbsynStatement stm;
if (vEdge.To.IsReturn)
{
// Goto to a return statement => just a return statement.
var ret = (AbsynReturn)vEdge.To.Statements[0];
Expression? v = ret.Value?.CloneExpression();
stm = new AbsynReturn(v);
}
else
{
// Determine the type of statement for the non-structured
// transfer.
switch (vEdge.Type)
{
case VirtualEdgeType.Continue: stm = new AbsynContinue(); break;
case VirtualEdgeType.Break: stm = new AbsynBreak(); break;
case VirtualEdgeType.Goto:
stm = new AbsynGoto(vEdge.To.Block.DisplayName);
if (vEdge.To.Statements.Count == 0 || !(vEdge.To.Statements[0] is AbsynLabel))
{
vEdge.To.Statements.Insert(0, new AbsynLabel(vEdge.To.Block.DisplayName));
}
break;
default:
throw new InvalidOperationException();
}
}
CollapseToTailRegion(vEdge.From, vEdge.To, stm);
RemoveEdge(vEdge.From, vEdge.To);
if (regionGraph.Predecessors(vEdge.To).Count == 0 && vEdge.To != entry)
{
if (vEdge.To.IsReturn)
RemoveRegion(vEdge.To);
else
eventListener.Error(
eventListener.CreateProcedureNavigator(program, proc),
string.Format(
"Removing edge ({0}, {1}) caused loss of some code blocks",
vEdge.From.Block.DisplayName,
vEdge.To.Block.DisplayName));
Probe();
}
}
/// <summary>
/// Appends the statement <paramref name="stm"/> to the list
/// of statements in the <paramref name="from"/> region.
///
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="stm"></param>
public void CollapseToTailRegion(Region from, Region to, AbsynStatement stm)
{
switch (from.Type)
{
case RegionType.Condition:
var e = from.Expression!;
var succs = regionGraph.Successors(from).ToArray();
if (succs[0] == to)
{
e = e.Invert();
}
var ifStm = new AbsynIf(e, new List<AbsynStatement> { stm });
from.Statements.Add(ifStm);
from.Expression = null;
Probe();
from.Type = RegionType.Linear;
break;
case RegionType.Linear:
from.Statements.Add(stm);
Probe();
from.Type = RegionType.Tail;
break;
default:
DumpGraph();
throw new NotImplementedException(string.Format("Can't collapse {0} ({1}) => {2}) in procedure {3}", from.Block.DisplayName, from.Type, to.Block.DisplayName, proc.Name));
}
}
#if NILZ
3.5
Cyclic Regions
If the subgraph at node _n_ is cyclic, we first test if it matches
a cyclic pattern. The first step is to identify any loops of
which_n_ is the loop header. It is possible for a node to be
the loop header of multiple loops. For instance, nested
do-while loops share a common loop header. We identify
distinct loops at node n by finding back edges pointing to
n (see 2.1). Each back edge (nb; n)
defines a loop body consisting of the nodes that can reach
nb without going through the loop header,
n.