-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathjava_bytecode_convert_method.cpp
More file actions
2509 lines (2217 loc) · 78.2 KB
/
java_bytecode_convert_method.cpp
File metadata and controls
2509 lines (2217 loc) · 78.2 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
/*******************************************************************\
Module: JAVA Bytecode Language Conversion
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
/// \file
/// JAVA Bytecode Language Conversion
#ifdef DEBUG
#include <iostream>
#endif
#include "java_bytecode_convert_method.h"
#include "java_bytecode_convert_method_class.h"
#include "bytecode_info.h"
#include "java_types.h"
#include <util/arith_tools.h>
#include <util/c_types.h>
#include <util/ieee_float.h>
#include <util/invariant.h>
#include <util/namespace.h>
#include <util/prefix.h>
#include <util/simplify_expr.h>
#include <util/std_expr.h>
#include <util/string2int.h>
#include <linking/zero_initializer.h>
#include <goto-programs/cfg.h>
#include <analyses/cfg_dominators.h>
#include <limits>
#include <algorithm>
#include <functional>
#include <unordered_set>
class patternt
{
public:
explicit patternt(const char *_p):p(_p)
{
}
// match with '?'
bool operator==(const irep_idt &what) const
{
for(std::size_t i=0; i<what.size(); i++)
if(p[i]==0)
return false;
else if(p[i]!='?' && p[i]!=what[i])
return false;
return p[what.size()]==0;
}
protected:
const char *p;
};
static bool operator==(const irep_idt &what, const patternt &pattern)
{
return pattern==what;
}
const size_t SLOTS_PER_INTEGER(1u);
const size_t INTEGER_WIDTH(64u);
static size_t count_slots(
const size_t value,
const code_typet::parametert ¶m)
{
const std::size_t width(param.type().get_unsigned_int(ID_width));
return value+SLOTS_PER_INTEGER+width/INTEGER_WIDTH;
}
static size_t get_variable_slots(const code_typet::parametert ¶m)
{
return count_slots(0, param);
}
static irep_idt strip_java_namespace_prefix(const irep_idt to_strip)
{
const auto to_strip_str=id2string(to_strip);
assert(has_prefix(to_strip_str, "java::"));
return to_strip_str.substr(6, std::string::npos);
}
// name contains <init> or <clinit>
bool java_bytecode_convert_methodt::is_constructor(
const class_typet::methodt &method)
{
const std::string &name(id2string(method.get_name()));
const std::string::size_type &npos(std::string::npos);
return npos!=name.find("<init>") || npos!=name.find("<clinit>");
}
exprt::operandst java_bytecode_convert_methodt::pop(std::size_t n)
{
if(stack.size()<n)
{
error() << "malformed bytecode (pop too high)" << eom;
throw 0;
}
exprt::operandst operands;
operands.resize(n);
for(std::size_t i=0; i<n; i++)
operands[i]=stack[stack.size()-n+i];
stack.resize(stack.size()-n);
return operands;
}
/// removes minimum(n, stack.size()) elements from the stack
void java_bytecode_convert_methodt::pop_residue(std::size_t n)
{
std::size_t residue_size=std::min(n, stack.size());
stack.resize(stack.size()-residue_size);
}
void java_bytecode_convert_methodt::push(const exprt::operandst &o)
{
stack.resize(stack.size()+o.size());
for(std::size_t i=0; i<o.size(); i++)
stack[stack.size()-o.size()+i]=o[i];
}
// JVM program locations
irep_idt java_bytecode_convert_methodt::label(const irep_idt &address)
{
return "pc"+id2string(address);
}
symbol_exprt java_bytecode_convert_methodt::tmp_variable(
const std::string &prefix,
const typet &type)
{
irep_idt base_name=prefix+"_tmp"+std::to_string(tmp_vars.size());
irep_idt identifier=id2string(current_method)+"::"+id2string(base_name);
auxiliary_symbolt tmp_symbol;
tmp_symbol.base_name=base_name;
tmp_symbol.is_static_lifetime=false;
tmp_symbol.mode=ID_java;
tmp_symbol.name=identifier;
tmp_symbol.type=type;
symbol_table.add(tmp_symbol);
symbol_exprt result(identifier, type);
result.set(ID_C_base_name, base_name);
tmp_vars.push_back(result);
return result;
}
const exprt java_bytecode_convert_methodt::variable(
const exprt &arg,
char type_char,
size_t address,
java_bytecode_convert_methodt::variable_cast_argumentt do_cast)
{
mp_integer number;
bool ret=to_integer(to_constant_expr(arg), number);
CHECK_RETURN(!ret);
std::size_t number_int=integer2size_t(number);
typet t=java_type_from_char(type_char);
variablest &var_list=variables[number_int];
// search variable in list for correct frame / address if necessary
const variablet &var=
find_variable_for_slot(address, var_list);
if(var.symbol_expr.get_identifier().empty())
{
// an unnamed local variable
irep_idt base_name="anonlocal::"+std::to_string(number_int)+type_char;
irep_idt identifier=id2string(current_method)+"::"+id2string(base_name);
symbol_exprt result(identifier, t);
result.set(ID_C_base_name, base_name);
used_local_names.insert(result);
return result;
}
else
{
exprt result=var.symbol_expr;
if(do_cast==CAST_AS_NEEDED && t!=result.type())
result=typecast_exprt(result, t);
return result;
}
}
/// This creates a method symbol in the symtab, but doesn't actually perform
/// method conversion just yet. The caller should call
/// java_bytecode_convert_method later to give the symbol/method a body.
/// \par parameters: `class_symbol`: class this method belongs to
/// `method_identifier`: fully qualified method name, including type signature
/// (e.g. "x.y.z.f:(I)")
/// `m`: parsed method object to convert
/// `symbol_table`: global symbol table (will be modified)
void java_bytecode_convert_method_lazy(
const symbolt &class_symbol,
const irep_idt &method_identifier,
const java_bytecode_parse_treet::methodt &m,
symbol_tablet &symbol_table)
{
symbolt method_symbol;
typet member_type=java_type_from_string(m.signature);
method_symbol.name=method_identifier;
method_symbol.base_name=m.base_name;
method_symbol.mode=ID_java;
method_symbol.location=m.source_location;
method_symbol.location.set_function(method_identifier);
if(m.is_public)
member_type.set(ID_access, ID_public);
else if(m.is_protected)
member_type.set(ID_access, ID_protected);
else if(m.is_private)
member_type.set(ID_access, ID_private);
else
member_type.set(ID_access, ID_default);
if(method_symbol.base_name=="<init>")
{
method_symbol.pretty_name=
id2string(class_symbol.pretty_name)+"."+
id2string(class_symbol.base_name)+"()";
member_type.set(ID_constructor, true);
}
else
method_symbol.pretty_name=
id2string(class_symbol.pretty_name)+"."+
id2string(m.base_name)+"()";
// do we need to add 'this' as a parameter?
if(!m.is_static)
{
code_typet &code_type=to_code_type(member_type);
code_typet::parameterst ¶meters=code_type.parameters();
code_typet::parametert this_p;
const reference_typet object_ref_type=
java_reference_type(symbol_typet(class_symbol.name));
this_p.type()=object_ref_type;
this_p.set_this();
parameters.insert(parameters.begin(), this_p);
}
method_symbol.type=member_type;
symbol_table.add(method_symbol);
}
void java_bytecode_convert_methodt::convert(
const symbolt &class_symbol,
const methodt &m)
{
const irep_idt method_identifier=
id2string(class_symbol.name)+"."+id2string(m.name)+":"+m.signature;
method_id=method_identifier;
const auto &old_sym=symbol_table.lookup(method_identifier);
typet member_type=old_sym.type;
code_typet &code_type=to_code_type(member_type);
method_return_type=code_type.return_type();
code_typet::parameterst ¶meters=code_type.parameters();
variables.clear();
// find parameter names in the local variable table:
for(const auto &v : m.local_variable_table)
{
if(v.start_pc!=0) // Local?
continue;
typet t=java_type_from_string(v.signature);
std::ostringstream id_oss;
id_oss << method_id << "::" << v.name;
irep_idt identifier(id_oss.str());
symbol_exprt result(identifier, t);
result.set(ID_C_base_name, v.name);
variables[v.index].push_back(variablet());
auto &newv=variables[v.index].back();
newv.symbol_expr=result;
newv.start_pc=v.start_pc;
newv.length=v.length;
}
// set up variables array
std::size_t param_index=0;
for(const auto ¶m : parameters)
{
variables[param_index].resize(1);
param_index+=get_variable_slots(param);
}
// assign names to parameters
param_index=0;
for(auto ¶m : parameters)
{
irep_idt base_name, identifier;
if(param_index==0 && param.get_this())
{
base_name="this";
identifier=id2string(method_identifier)+"::"+id2string(base_name);
param.set_base_name(base_name);
param.set_identifier(identifier);
}
else
{
// in the variable table?
base_name=variables[param_index][0].symbol_expr.get(ID_C_base_name);
identifier=variables[param_index][0].symbol_expr.get(ID_identifier);
if(base_name.empty())
{
const typet &type=param.type();
char suffix=java_char_from_type(type);
base_name="arg"+std::to_string(param_index)+suffix;
identifier=id2string(method_identifier)+"::"+id2string(base_name);
}
param.set_base_name(base_name);
param.set_identifier(identifier);
}
// add to symbol table
parameter_symbolt parameter_symbol;
parameter_symbol.base_name=base_name;
parameter_symbol.mode=ID_java;
parameter_symbol.name=identifier;
parameter_symbol.type=param.type();
symbol_table.add(parameter_symbol);
// add as a JVM variable
std::size_t slots=get_variable_slots(param);
variables[param_index][0].symbol_expr=parameter_symbol.symbol_expr();
variables[param_index][0].is_parameter=true;
variables[param_index][0].start_pc=0;
variables[param_index][0].length=std::numeric_limits<size_t>::max();
variables[param_index][0].is_parameter=true;
param_index+=slots;
assert(param_index>0);
}
const bool is_virtual=!m.is_static && !m.is_final;
#if 0
class_type.methods().push_back(class_typet::methodt());
class_typet::methodt &method=class_type.methods().back();
#else
class_typet::methodt method;
#endif
method.set_base_name(m.base_name);
method.set_name(method_identifier);
method.set(ID_abstract, m.is_abstract);
method.set(ID_is_virtual, is_virtual);
if(is_constructor(method))
method.set(ID_constructor, true);
method.type()=member_type;
// we add the symbol for the method
symbolt method_symbol;
method_symbol.name=method.get_name();
method_symbol.base_name=method.get_base_name();
method_symbol.mode=ID_java;
method_symbol.location=m.source_location;
method_symbol.location.set_function(method_identifier);
if(method.get_base_name()=="<init>")
method_symbol.pretty_name=id2string(class_symbol.pretty_name)+"."+
id2string(class_symbol.base_name)+"()";
else
method_symbol.pretty_name=id2string(class_symbol.pretty_name)+"."+
id2string(method.get_base_name())+"()";
method_symbol.type=member_type;
if(is_constructor(method))
method_symbol.type.set(ID_constructor, true);
current_method=method_symbol.name;
method_has_this=code_type.has_this();
tmp_vars.clear();
if((!m.is_abstract) && (!m.is_native))
method_symbol.value=convert_instructions(m, code_type);
// Replace the existing stub symbol with the real deal:
const auto s_it=symbol_table.symbols.find(method.get_name());
assert(s_it!=symbol_table.symbols.end());
symbol_table.symbols.erase(s_it);
symbol_table.add(method_symbol);
}
const bytecode_infot &java_bytecode_convert_methodt::get_bytecode_info(
const irep_idt &statement)
{
for(const bytecode_infot *p=bytecode_info; p->mnemonic!=nullptr; p++)
if(statement==p->mnemonic)
return *p;
error() << "failed to find bytecode mnemonic `"
<< statement << '\'' << eom;
throw 0;
}
static irep_idt get_if_cmp_operator(const irep_idt &stmt)
{
if(stmt==patternt("if_?cmplt"))
return ID_lt;
if(stmt==patternt("if_?cmple"))
return ID_le;
if(stmt==patternt("if_?cmpgt"))
return ID_gt;
if(stmt==patternt("if_?cmpge"))
return ID_ge;
if(stmt==patternt("if_?cmpeq"))
return ID_equal;
if(stmt==patternt("if_?cmpne"))
return ID_notequal;
throw "unhandled java comparison instruction";
}
static member_exprt to_member(const exprt &pointer, const exprt &fieldref)
{
symbol_typet class_type(fieldref.get(ID_class));
exprt pointer2=
typecast_exprt(pointer, java_reference_type(class_type));
const dereference_exprt obj_deref(pointer2, class_type);
return member_exprt(
obj_deref,
fieldref.get(ID_component_name),
fieldref.type());
}
codet java_bytecode_convert_methodt::get_array_bounds_check(
const exprt &arraystruct,
const exprt &idx,
const source_locationt &original_sloc)
{
constant_exprt intzero=from_integer(0, java_int_type());
binary_relation_exprt gezero(idx, ID_ge, intzero);
const member_exprt length_field(arraystruct, "length", java_int_type());
binary_relation_exprt ltlength(idx, ID_lt, length_field);
code_blockt bounds_checks;
bounds_checks.add(code_assertt(gezero));
bounds_checks.operands().back().add_source_location()=original_sloc;
bounds_checks.operands().back().add_source_location()
.set_comment("Array index < 0");
bounds_checks.operands().back().add_source_location()
.set_property_class("array-index-out-of-bounds-low");
bounds_checks.add(code_assertt(ltlength));
bounds_checks.operands().back().add_source_location()=original_sloc;
bounds_checks.operands().back().add_source_location()
.set_comment("Array index >= length");
bounds_checks.operands().back().add_source_location()
.set_property_class("array-index-out-of-bounds-high");
// TODO make this throw ArrayIndexOutOfBoundsException instead of asserting.
return bounds_checks;
}
/// Find all goto statements in 'repl' that target 'old_label' and redirect them
/// to 'new_label'.
/// \par parameters: 'repl', a block of code in which to perform replacement,
/// and
/// an old_label that should be replaced throughout by new_label.
/// \return None (side-effects on repl)
void java_bytecode_convert_methodt::replace_goto_target(
codet &repl,
const irep_idt &old_label,
const irep_idt &new_label)
{
const auto &stmt=repl.get_statement();
if(stmt==ID_goto)
{
auto &g=to_code_goto(repl);
if(g.get_destination()==old_label)
g.set_destination(new_label);
}
else
{
for(auto &op : repl.operands())
if(op.id()==ID_code)
replace_goto_target(to_code(op), old_label, new_label);
}
}
/// 'tree' describes a tree of code_blockt objects; this_block is the
/// corresponding block (thus they are both trees with the same shape). The
/// caller is looking for the single block in the tree that most closely
/// encloses bytecode address range [address_start,address_limit).
/// 'next_block_start_address' is the start address of 'tree's successor sibling
/// and is used to determine when the range spans out of its bounds.
/// \par parameters: 'tree', a code block descriptor, and 'this_block', the
/// corresponding
/// actual code_blockt. 'address_start' and 'address_limit', the Java
/// bytecode offsets searched for. 'next_block_start_address', the
/// bytecode offset of tree/this_block's successor sibling, or UINT_MAX
/// if none exists.
/// \return Returns the code_blockt most closely enclosing the given address
/// range.
code_blockt &java_bytecode_convert_methodt::get_block_for_pcrange(
block_tree_nodet &tree,
code_blockt &this_block,
unsigned address_start,
unsigned address_limit,
unsigned next_block_start_address)
{
address_mapt dummy;
return get_or_create_block_for_pcrange(
tree,
this_block,
address_start,
address_limit,
next_block_start_address,
dummy,
false);
}
/// As above, but this version can additionally create a new branch in the
/// block_tree-node and code_blockt trees to envelop the requested address
/// range. For example, if the tree was initially flat, with nodes (1-10),
/// (11-20), (21-30) and the caller asked for range 13-28, this would build a
/// surrounding tree node, leaving the tree of shape (1-10), ^( (11-20), (21-30)
/// )^, and return a reference to the new branch highlighted with ^^. 'tree' and
/// 'this_block' trees are always maintained with equal shapes. ('this_block'
/// may additionally contain code_declt children which are ignored for this
/// purpose)
/// \par parameters: See above, plus the bytecode address map 'amap' and
/// 'allow_merge'
/// which is always true except when called from get_block_for_pcrange
/// \return See above, plus potential side-effects on 'tree' and 'this_block' as
/// described in 'Purpose'
code_blockt &java_bytecode_convert_methodt::get_or_create_block_for_pcrange(
block_tree_nodet &tree,
code_blockt &this_block,
unsigned address_start,
unsigned address_limit,
unsigned next_block_start_address,
const address_mapt &amap,
bool allow_merge)
{
// Check the tree shape invariant:
assert(tree.branch.size()==tree.branch_addresses.size());
// If there are no child blocks, return this.
if(tree.leaf)
return this_block;
assert(!tree.branch.empty());
// Find child block starting > address_start:
const auto afterstart=
std::upper_bound(
tree.branch_addresses.begin(),
tree.branch_addresses.end(),
address_start);
assert(afterstart!=tree.branch_addresses.begin());
auto findstart=afterstart;
--findstart;
auto child_offset=
std::distance(tree.branch_addresses.begin(), findstart);
// Find child block starting >= address_limit:
auto findlim=
std::lower_bound(
tree.branch_addresses.begin(),
tree.branch_addresses.end(),
address_limit);
unsigned findlim_block_start_address=
findlim==tree.branch_addresses.end() ?
next_block_start_address :
(*findlim);
// If all children are in scope, return this.
if(findstart==tree.branch_addresses.begin() &&
findlim==tree.branch_addresses.end())
return this_block;
// Find the child code_blockt where the queried range begins:
auto child_iter=this_block.operands().begin();
// Skip any top-of-block declarations;
// all other children are labelled subblocks.
while(child_iter!=this_block.operands().end() &&
to_code(*child_iter).get_statement()==ID_decl)
++child_iter;
assert(child_iter!=this_block.operands().end());
std::advance(child_iter, child_offset);
assert(child_iter!=this_block.operands().end());
auto &child_label=to_code_label(to_code(*child_iter));
auto &child_block=to_code_block(child_label.code());
bool single_child(afterstart==findlim);
if(single_child)
{
// Range wholly contained within a child block
return get_or_create_block_for_pcrange(
tree.branch[child_offset],
child_block,
address_start,
address_limit,
findlim_block_start_address,
amap,
allow_merge);
}
// Otherwise we're being asked for a range of subblocks, but not all of them.
// If it's legal to draw a new lexical scope around the requested subset,
// do so; otherwise just return this block.
// This can be a new lexical scope if all incoming edges target the
// new block header, or come from within the suggested new block.
// If modifying the block tree is forbidden, give up and return this:
if(!allow_merge)
return this_block;
// Check for incoming control-flow edges targeting non-header
// blocks of the new proposed block range:
auto checkit=amap.find(*findstart);
assert(checkit!=amap.end());
++checkit; // Skip the header, which can have incoming edges from outside.
for(;
checkit!=amap.end() && (checkit->first)<(findlim_block_start_address);
++checkit)
{
for(auto p : checkit->second.predecessors)
{
if(p<(*findstart) || p>=findlim_block_start_address)
{
debug() << "Warning: refusing to create lexical block spanning "
<< (*findstart) << "-" << findlim_block_start_address
<< " due to incoming edge " << p << " -> "
<< checkit->first << eom;
return this_block;
}
}
}
// All incoming edges are acceptable! Create a new block wrapping
// the relevant children. Borrow the header block's label, and redirect
// any block-internal edges to target the inner header block.
const irep_idt child_label_name=child_label.get_label();
std::string new_label_str=as_string(child_label_name);
new_label_str+='$';
irep_idt new_label_irep(new_label_str);
code_labelt newlabel(child_label_name, code_blockt());
code_blockt &newblock=to_code_block(newlabel.code());
auto nblocks=std::distance(findstart, findlim);
assert(nblocks>=2);
debug() << "Combining " << std::distance(findstart, findlim)
<< " blocks for addresses " << (*findstart) << "-"
<< findlim_block_start_address << eom;
// Make a new block containing every child of interest:
auto &this_block_children=this_block.operands();
assert(tree.branch.size()==this_block_children.size());
for(auto blockidx=child_offset, blocklim=child_offset+nblocks;
blockidx!=blocklim;
++blockidx)
newblock.move_to_operands(this_block_children[blockidx]);
// Relabel the inner header:
to_code_label(to_code(newblock.operands()[0])).set_label(new_label_irep);
// Relabel internal gotos:
replace_goto_target(newblock, child_label_name, new_label_irep);
// Remove the now-empty sibling blocks:
auto delfirst=this_block_children.begin();
std::advance(delfirst, child_offset+1);
auto dellim=delfirst;
std::advance(dellim, nblocks-1);
this_block_children.erase(delfirst, dellim);
this_block_children[child_offset].swap(newlabel);
// Perform the same transformation on the index tree:
block_tree_nodet newnode;
auto branchstart=tree.branch.begin();
std::advance(branchstart, child_offset);
auto branchlim=branchstart;
std::advance(branchlim, nblocks);
for(auto branchiter=branchstart; branchiter!=branchlim; ++branchiter)
newnode.branch.push_back(std::move(*branchiter));
++branchstart;
tree.branch.erase(branchstart, branchlim);
assert(tree.branch.size()==this_block_children.size());
auto branchaddriter=tree.branch_addresses.begin();
std::advance(branchaddriter, child_offset);
auto branchaddrlim=branchaddriter;
std::advance(branchaddrlim, nblocks);
newnode.branch_addresses.insert(
newnode.branch_addresses.begin(),
branchaddriter,
branchaddrlim);
++branchaddriter;
tree.branch_addresses.erase(branchaddriter, branchaddrlim);
tree.branch[child_offset]=std::move(newnode);
assert(tree.branch.size()==tree.branch_addresses.size());
return
to_code_block(
to_code_label(
to_code(this_block_children[child_offset])).code());
}
static void gather_symbol_live_ranges(
unsigned pc,
const exprt &e,
std::map<irep_idt, java_bytecode_convert_methodt::variablet> &result)
{
if(e.id()==ID_symbol)
{
const auto &symexpr=to_symbol_expr(e);
auto findit=
result.insert({ // NOLINT(whitespace/braces)
symexpr.get_identifier(),
java_bytecode_convert_methodt::variablet()});
auto &var=findit.first->second;
if(findit.second)
{
var.symbol_expr=symexpr;
var.start_pc=pc;
var.length=1;
}
else
{
if(pc<var.start_pc)
{
var.length+=(var.start_pc-pc);
var.start_pc=pc;
}
else
{
var.length=std::max(var.length, (pc-var.start_pc)+1);
}
}
}
else
{
forall_operands(it, e)
gather_symbol_live_ranges(pc, *it, result);
}
}
static unsigned get_bytecode_type_width(const typet &ty)
{
if(ty.id()==ID_pointer)
return 32;
return ty.get_unsigned_int(ID_width);
}
codet java_bytecode_convert_methodt::convert_instructions(
const methodt &method,
const code_typet &method_type)
{
const instructionst &instructions=method.instructions;
// Run a worklist algorithm, assuming that the bytecode has not
// been tampered with. See "Leroy, X. (2003). Java bytecode
// verification: algorithms and formalizations. Journal of Automated
// Reasoning, 30(3-4), 235-269." for a more complete treatment.
// first pass: get targets and map addresses to instructions
address_mapt address_map;
std::set<unsigned> targets;
std::vector<unsigned> jsr_ret_targets;
std::vector<instructionst::const_iterator> ret_instructions;
for(instructionst::const_iterator
i_it=instructions.begin();
i_it!=instructions.end();
i_it++)
{
converted_instructiont ins=converted_instructiont(i_it, code_skipt());
std::pair<address_mapt::iterator, bool> a_entry=
address_map.insert(std::make_pair(i_it->address, ins));
assert(a_entry.second);
// addresses are strictly increasing, hence we must have inserted
// a new maximal key
assert(a_entry.first==--address_map.end());
if(i_it->statement!="goto" &&
i_it->statement!="return" &&
!(i_it->statement==patternt("?return")) &&
i_it->statement!="athrow" &&
i_it->statement!="jsr" &&
i_it->statement!="jsr_w" &&
i_it->statement!="ret")
{
instructionst::const_iterator next=i_it;
if(++next!=instructions.end())
a_entry.first->second.successors.push_back(next->address);
}
if(i_it->statement=="athrow" ||
i_it->statement=="invokestatic" ||
i_it->statement=="invokevirtual" ||
i_it->statement=="invokespecial" ||
i_it->statement=="invokeinterface")
{
// find the corresponding try-catch blocks and add the handlers
// to the targets
for(const auto &exception_row : method.exception_table)
{
if(i_it->address>=exception_row.start_pc &&
i_it->address<exception_row.end_pc)
{
a_entry.first->second.successors.push_back(
exception_row.handler_pc);
targets.insert(exception_row.handler_pc);
}
}
}
if(i_it->statement=="goto" ||
i_it->statement==patternt("if_?cmp??") ||
i_it->statement==patternt("if??") ||
i_it->statement=="ifnonnull" ||
i_it->statement=="ifnull" ||
i_it->statement=="jsr" ||
i_it->statement=="jsr_w")
{
assert(!i_it->args.empty());
unsigned target;
bool ret=to_unsigned_integer(to_constant_expr(i_it->args[0]), target);
DATA_INVARIANT(!ret, "target expected to be unsigned integer");
targets.insert(target);
a_entry.first->second.successors.push_back(target);
if(i_it->statement=="jsr" ||
i_it->statement=="jsr_w")
{
instructionst::const_iterator next=i_it+1;
assert(
next!=instructions.end() &&
"jsr without valid return address?");
targets.insert(next->address);
jsr_ret_targets.push_back(next->address);
}
}
else if(i_it->statement=="tableswitch" ||
i_it->statement=="lookupswitch")
{
bool is_label=true;
for(const auto &arg : i_it->args)
{
if(is_label)
{
unsigned target;
bool ret=to_unsigned_integer(to_constant_expr(arg), target);
DATA_INVARIANT(!ret, "target expected to be unsigned integer");
targets.insert(target);
a_entry.first->second.successors.push_back(target);
}
is_label=!is_label;
}
}
else if(i_it->statement=="ret")
{
// Finish these later, once we've seen all jsr instructions.
ret_instructions.push_back(i_it);
}
}
// Draw edges from every `ret` to every `jsr` successor. Could do better with
// flow analysis to distinguish multiple subroutines within the same function.
for(const auto retinst : ret_instructions)
{
auto &a_entry=address_map.at(retinst->address);
a_entry.successors.insert(
a_entry.successors.end(),
jsr_ret_targets.begin(),
jsr_ret_targets.end());
}
for(const auto &address : address_map)
{
for(unsigned s : address.second.successors)
{
address_mapt::iterator a_it=address_map.find(s);
assert(a_it!=address_map.end());
a_it->second.predecessors.insert(address.first);
}
}
// Now that the control flow graph is built, set up our local variables
// (these require the graph to determine live ranges)
setup_local_variables(method, address_map);
std::set<unsigned> working_set;
if(!instructions.empty())
working_set.insert(instructions.front().address);
while(!working_set.empty())
{
std::set<unsigned>::iterator cur=working_set.begin();
address_mapt::iterator a_it=address_map.find(*cur);
assert(a_it!=address_map.end());
unsigned cur_pc=*cur;
working_set.erase(cur);
if(a_it->second.done)
continue;
working_set
.insert(a_it->second.successors.begin(), a_it->second.successors.end());
instructionst::const_iterator i_it=a_it->second.source;
stack.swap(a_it->second.stack);
a_it->second.stack.clear();
codet &c=a_it->second.code;
assert(
stack.empty() ||
a_it->second.predecessors.size()<=1 ||
has_prefix(
stack.front().get_string(ID_C_base_name),
"$stack"));
irep_idt statement=i_it->statement;
exprt arg0=i_it->args.size()>=1?i_it->args[0]:nil_exprt();
exprt arg1=i_it->args.size()>=2?i_it->args[1]:nil_exprt();
const bytecode_infot &bytecode_info=get_bytecode_info(statement);
// deal with _idx suffixes
if(statement.size()>=2 &&
statement[statement.size()-2]=='_' &&
isdigit(statement[statement.size()-1]))
{
arg0=
from_integer(
string2integer(
std::string(id2string(statement), statement.size()-1, 1)),
java_int_type());
statement=std::string(id2string(statement), 0, statement.size()-2);
}
// we throw away the first statement in an exception handler
// as we don't know if a function call had a normal or exceptional return
auto it=method.exception_table.begin();
for(; it!=method.exception_table.end(); ++it)
{
if(cur_pc==it->handler_pc)
{
exprt exc_var=variable(
arg0, statement[0],
i_it->address,
NO_CAST);
// throw away the operands
pop_residue(bytecode_info.pop);
// add a CATCH-PUSH signaling a handler
side_effect_expr_catcht catch_handler_expr;
// pack the exception variable so that it can be used
// later for instrumentation
catch_handler_expr.get_sub().resize(1);
catch_handler_expr.get_sub()[0]=exc_var;
code_expressiont catch_handler(catch_handler_expr);
code_labelt newlabel(label(std::to_string(cur_pc)),
code_blockt());
code_blockt label_block=to_code_block(newlabel.code());
code_blockt handler_block;
handler_block.move_to_operands(c);
handler_block.move_to_operands(catch_handler);