forked from coccinelle/coccinelle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cocci.ml
2370 lines (2123 loc) · 74.9 KB
/
cocci.ml
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
(*
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at http://coccinelle.lip6.fr
*)
open Common
module CCI = Ctlcocci_integration
module TAC = Type_annoter_c
module Ast_to_flow = Control_flow_c_build
(*****************************************************************************)
(* This file is a kind of driver. It gathers all the important functions
* from coccinelle in one place. The different entities in coccinelle are:
* - files
* - astc
* - astcocci
* - flow (contain nodes)
* - ctl (contain rule_elems)
* This file contains functions to transform one in another.
*)
(*****************************************************************************)
(* --------------------------------------------------------------------- *)
(* C related *)
(* --------------------------------------------------------------------- *)
let cprogram_of_file saved_typedefs saved_macros parse_strings cache file =
let (parse_info, _) =
Parse_c.parse_c_and_cpp_keep_typedefs
(if !Flag_cocci.use_saved_typedefs then (Some saved_typedefs) else None)
(Some saved_macros) parse_strings cache file in
parse_info.Parse_c.parse_trees
let cprogram_of_file_cached saved_typedefs parse_strings cache file
has_changes =
Parse_c.parse_cache saved_typedefs parse_strings cache file has_changes
let cfile_of_program program2_with_ppmethod outf =
Unparse_c.pp_program program2_with_ppmethod outf
(* for memoization, contains only one entry, the one for the SP *)
let _hparse = Hashtbl.create 101
let _h_ocaml_init = Hashtbl.create 101
(* --------------------------------------------------------------------- *)
(* Cocci related *)
(* --------------------------------------------------------------------- *)
(* for a given pair (file,iso), only keep an instance for the most recent
virtual rules and virtual_env *)
let sp_of_file2 file iso =
let redo _ =
let new_code =
let (_,_,xs,_,_,_,_,_,_,_) as res = Parse_cocci.process file iso false in
(* if there is already a compiled ML code, do nothing and use that *)
try let _ = Hashtbl.find _h_ocaml_init (file,iso) in res
with Not_found ->
begin
Hashtbl.add _h_ocaml_init (file,iso) ();
match Prepare_ocamlcocci.prepare file xs with
None -> res
| Some ocaml_script_file ->
(* compile file *)
Prepare_ocamlcocci.load_file ocaml_script_file;
(if not !Common.save_tmp_files
then Prepare_ocamlcocci.clean_file ocaml_script_file);
res
end in
Hashtbl.add _hparse (file,iso)
(!Flag.defined_virtual_rules,!Flag.defined_virtual_env,new_code);
new_code in
try
let (rules,env,code) = Hashtbl.find _hparse (file,iso) in
if rules = !Flag.defined_virtual_rules && env = !Flag.defined_virtual_env
then code
else (Hashtbl.remove _hparse (file,iso); redo())
with Not_found -> redo()
let sp_of_file file iso =
Common.profile_code "parse cocci" (fun () -> sp_of_file2 file iso)
(* --------------------------------------------------------------------- *)
(* Flow related *)
(* --------------------------------------------------------------------- *)
let print_flow flow =
Control_flow_c.G.print_ograph_mutable flow "/tmp/test.dot" true
let ast_to_flow_with_error_messages2 x =
let flowopt =
try Ast_to_flow.ast_to_control_flow x
with Ast_to_flow.Error x ->
Ast_to_flow.report_error x;
None
in
flowopt +> do_option (fun flow ->
(* This time even if there is a deadcode, we still have a
* flow graph, so I can try the transformation and hope the
* deadcode will not bother us.
*)
try Ast_to_flow.deadcode_detection flow
with Ast_to_flow.Error (Ast_to_flow.DeadCode x) ->
Ast_to_flow.report_error (Ast_to_flow.DeadCode x);
);
flowopt
let ast_to_flow_with_error_messages a =
Common.profile_code "flow" (fun () -> ast_to_flow_with_error_messages2 a)
(* --------------------------------------------------------------------- *)
(* Ctl related *)
(* --------------------------------------------------------------------- *)
let ctls_of_ast2 ast (ua,fua,fuas) pos =
List.map2
(function ast -> function (ua,fua,fuas,pos) ->
let ast1 =
if !Flag_cocci.popl
then Popl.popl ast
else Asttoctl2.asttoctl ast (ua,fua,fuas) pos in
List.combine ast1 (Asttomember.asttomember ast ua))
ast (Common.combine4 ua fua fuas pos)
let ctls_of_ast ast ua pl =
Common.profile_code "asttoctl2" (fun () -> ctls_of_ast2 ast ua pl)
(*****************************************************************************)
(* Some debugging functions *)
(*****************************************************************************)
let cat file =
let chan = open_in file in
let rec catline () =
print_endline (input_line chan); catline() in
try catline() with End_of_file -> close_in chan
(* the inputs *)
let show_or_not_cfile2 (cfile,_) =
if !Flag_cocci.show_c then begin
Common.pr2_xxxxxxxxxxxxxxxxx ();
pr2 ("processing C file: " ^ cfile);
Common.pr2_xxxxxxxxxxxxxxxxx ();
cat cfile;
end
let show_or_not_cfile a =
Common.profile_code "show_xxx" (fun () -> show_or_not_cfile2 a)
let show_or_not_cfiles cfiles = List.iter show_or_not_cfile cfiles
let show_or_not_cocci2 coccifile isofile =
if !Flag_cocci.show_cocci then begin
Common.pr2_xxxxxxxxxxxxxxxxx ();
pr2 ("processing semantic patch file: " ^ coccifile);
isofile +> (fun s -> pr2 ("with isos from: " ^ s));
Common.pr2_xxxxxxxxxxxxxxxxx ();
cat coccifile;
pr2 "";
end
let show_or_not_cocci a b =
Common.profile_code "show_xxx" (fun () -> show_or_not_cocci2 a b)
(* ---------------------------------------------------------------------- *)
(* the output *)
let fix_sgrep_diffs l =
let l =
List.filter (function s -> (s =~ "^\\+\\+\\+") || not (s =~ "^\\+")) l in
let l = List.rev l in
(* adjust second number for + code *)
let rec loop1 n = function
[] -> []
| s::ss ->
if s =~ "^-" && not(s =~ "^---")
then s :: loop1 (n+1) ss
else if s =~ "^@@"
then
(match Str.split (Str.regexp " ") s with
bef::min::pl::aft ->
let (n1,n2) =
match Str.split (Str.regexp ",") pl with
[n1;n2] -> (n1,n2)
| [n1] -> (n1,"1")
| _ -> failwith "bad + line information" in
let n2 = int_of_string n2 in
(Printf.sprintf "%s %s %s,%d %s" bef min n1 (n2-n)
(String.concat " " aft))
:: loop1 0 ss
| _ -> failwith "bad @@ information")
else s :: loop1 n ss in
let rec loop2 n = function
[] -> []
| s::ss ->
if s =~ "^---"
then s :: loop2 0 ss
else if s =~ "^@@"
then
(match Str.split (Str.regexp " ") s with
bef::min::pl::aft ->
let (m2,n1,n2) =
match (Str.split (Str.regexp ",") min,
Str.split (Str.regexp ",") pl) with
([_;m2],[n1;n2]) -> (m2,n1,n2)
| ([_],[n1;n2]) -> ("1",n1,n2)
| ([_;m2],[n1]) -> (m2,n1,"1")
| ([_],[n1]) -> ("1",n1,"1")
| _ -> failwith "bad -/+ line information" in
let n1 =
int_of_string (String.sub n1 1 ((String.length n1)-1)) in
let m2 = int_of_string m2 in
let n2 = int_of_string n2 in
(Printf.sprintf "%s %s +%d,%d %s" bef min (n1-n) n2
(String.concat " " aft))
:: loop2 (n+(m2-n2)) ss
| _ -> failwith "bad @@ information")
else s :: loop2 n ss in
loop2 0 (List.rev (loop1 0 l))
let normalize_path file =
let fullpath =
if String.get file 0 = '/' then file else (Sys.getcwd()) ^ "/" ^ file in
let elements = Str.split_delim (Str.regexp "/") fullpath in
let rec loop prev = function
[] -> String.concat "/" (List.rev prev)
| "." :: rest -> loop prev rest
| ".." :: rest ->
(match prev with
x::xs -> loop xs rest
| _ -> failwith "bad path")
| x::rest -> loop (x::prev) rest in
loop [] elements
let generated_patches = Hashtbl.create(100)
let show_or_not_diff2 cfile outfile =
let show_diff =
!Flag_cocci.show_diff &&
(!Flag_cocci.force_diff ||
(not(Common.fst(Compare_c.compare_to_original cfile outfile) =
Compare_c.Correct))) in (* diff only in spacing, etc *)
if show_diff
then
begin
(* may need --strip-trailing-cr under windows *)
pr2 "diff = ";
let line =
match !Flag_parsing_c.diff_lines with
| None -> "diff -u -p " ^ cfile ^ " " ^ outfile
| Some n -> "diff -U "^n^" -p "^cfile^" "^outfile in
let res = Common.cmd_to_list line in
(match res with
[] -> ()
| _ ->
let res =
List.map
(function l ->
match Str.split (Str.regexp "[ \t]+") l with
"---"::file::date -> "--- "^file
| "+++"::file::date -> "+++ "^file
| _ -> l)
res in
let xs =
match (!Flag.patch,res) with
(* create something that looks like the output of patch *)
(Some prefix,minus_file::plus_file::rest) ->
let prefix =
let lp = String.length prefix in
if String.get prefix (lp-1) = '/'
then String.sub prefix 0 (lp-1)
else prefix in
let fail file =
pr2 (Printf.sprintf "prefix %s doesn't match file %s"
prefix file);
file in
let drop_prefix file =
let file = normalize_path file in
if Str.string_match (Str.regexp prefix) file 0
then
let lp = String.length prefix in
let lf = String.length file in
if lp < lf
then String.sub file lp (lf - lp)
else fail file
else fail file in
let diff_line =
match List.rev(Str.split (Str.regexp " ") line) with
new_file::old_file::cmdrev ->
let old_base_file = drop_prefix old_file in
if !Flag.sgrep_mode2
then
String.concat " "
(List.rev
(("/tmp/nothing"^old_base_file)
:: old_file :: cmdrev))
else
String.concat " "
(List.rev
(("b"^old_base_file)::("a"^old_base_file)::
cmdrev))
| _ -> failwith "bad command" in
let (minus_line,plus_line) =
match (Str.split (Str.regexp "[ \t]") minus_file,
Str.split (Str.regexp "[ \t]") plus_file) with
("---"::old_file::old_rest,"+++"::new_file::new_rest) ->
let old_base_file = drop_prefix old_file in
if !Flag.sgrep_mode2
then (minus_file,"+++ /tmp/nothing"^old_base_file)
else
(String.concat " "
("---"::("a"^old_base_file)::old_rest),
String.concat " "
("+++"::("b"^old_base_file)::new_rest))
| (l1,l2) ->
failwith
(Printf.sprintf "bad diff header lines: %s %s"
(String.concat ":" l1) (String.concat ":" l2)) in
diff_line::minus_line::plus_line::rest
| _ -> res in
let xs = if !Flag.sgrep_mode2 then fix_sgrep_diffs xs else xs in
let cfile = normalize_path cfile in
let patches =
try Hashtbl.find generated_patches cfile
with Not_found ->
let cell = ref [] in
Hashtbl.add generated_patches cfile cell;
cell in
if List.mem xs !patches
then ()
else
begin
patches := xs :: !patches;
xs +> List.iter pr
end)
end
let show_or_not_diff a b =
Common.profile_code "show_xxx" (fun () -> show_or_not_diff2 a b)
(* the derived input *)
let show_or_not_ctl_tex2 astcocci ctls =
if !Flag_cocci.show_ctl_tex then begin
let ctls =
List.map
(List.map
(function ((Asttoctl2.NONDECL ctl | Asttoctl2.CODE ctl),x) ->
(ctl,x)))
ctls in
Ctltotex.totex ("/tmp/__cocci_ctl.tex") astcocci ctls;
Common.command2 ("cd /tmp; latex __cocci_ctl.tex; " ^
"dvips __cocci_ctl.dvi -o __cocci_ctl.ps;" ^
"gv __cocci_ctl.ps &");
end
let show_or_not_ctl_tex a b =
Common.profile_code "show_xxx" (fun () -> show_or_not_ctl_tex2 a b)
let show_or_not_rule_name ast rulenb =
if !Flag_cocci.show_ctl_text || !Flag.show_trying ||
!Flag.show_transinfo || !Flag_cocci.show_binding_in_out
then
begin
let name =
match ast with
Ast_cocci.CocciRule (nm, (deps, drops, exists), x, _, _) -> nm
| Ast_cocci.ScriptRule (nm, _, _, _, _, _,_) -> nm
| _ -> string_of_int rulenb in
Common.pr_xxxxxxxxxxxxxxxxx ();
pr (name ^ " = ");
Common.pr_xxxxxxxxxxxxxxxxx ()
end
let show_or_not_scr_rule_name name =
if !Flag_cocci.show_ctl_text || !Flag.show_trying ||
!Flag.show_transinfo || !Flag_cocci.show_binding_in_out
then
begin
Common.pr_xxxxxxxxxxxxxxxxx ();
pr ("script " ^ name ^ " = ");
Common.pr_xxxxxxxxxxxxxxxxx ()
end
let show_or_not_ctl_text2 ctl mvs ast rulenb =
if !Flag_cocci.show_ctl_text then begin
adjust_pp_with_indent (fun () ->
Format.force_newline();
Pretty_print_cocci.print_plus_flag := true;
Pretty_print_cocci.print_minus_flag := true;
Pretty_print_cocci.unparse mvs ast;
);
pr "CTL = ";
let ((Asttoctl2.CODE ctl | Asttoctl2.NONDECL ctl),_) = ctl in
adjust_pp_with_indent (fun () ->
Format.force_newline();
Pretty_print_engine.pp_ctlcocci
!Flag_cocci.show_mcodekind_in_ctl !Flag_cocci.inline_let_ctl ctl;
);
pr "";
end
let show_or_not_ctl_text a b c d =
Common.profile_code "show_xxx" (fun () -> show_or_not_ctl_text2 a b c d)
(* running information *)
let get_celem celem : string =
match celem with
Ast_c.Definition ({Ast_c.f_name = namefuncs;},_) ->
Ast_c.str_of_name namefuncs
| Ast_c.Declaration
(Ast_c.DeclList ([{Ast_c.v_namei = Some (name, _);}, _], _)) ->
Ast_c.str_of_name name
| _ -> ""
(* Warning The following function has the absolutely essential property of
setting Flag.current_element, whether or not one wants to print tracing
information! This is probably not smart... *)
let show_or_not_celem2 prelude celem start_end =
Flag.current_element_pos := start_end;
let (tag,trying) =
(match celem with
| Ast_c.Definition ({Ast_c.f_name = namefuncs},_) ->
let funcs = Ast_c.str_of_name namefuncs in
Flag.current_element := funcs;
(" function: ",Some (funcs,namefuncs))
| Ast_c.Declaration
(Ast_c.DeclList ([{Ast_c.v_namei = Some (name,_)}, _], _)) ->
let s = Ast_c.str_of_name name in
Flag.current_element := s;
(" variable ",Some(s,name));
| Ast_c.MacroTop(nm,_,_) ->
Flag.current_element := nm;
(" macro ",None);
| _ ->
Flag.current_element := "something_else";
(" ",None);
) in
if !Flag.show_trying
then
match trying with
Some(str,name) ->
let info = Ast_c.info_of_name name in
let file = Filename.basename(Ast_c.file_of_info info) in
let line = Ast_c.line_of_info info in
pr2 (Printf.sprintf "%s%s%s: %s:%d" prelude tag str file line)
| None -> pr2 (Printf.sprintf "%s%s something else" prelude tag)
let show_or_not_celem a b =
Common.profile_code "show_xxx" (fun () -> show_or_not_celem2 a b)
let show_or_not_trans_info2 trans_info =
(* drop witness tree indices for printing *)
if !Flag.show_transinfo then begin
let trans_info =
List.map (function (index,trans_info) -> trans_info) trans_info in
if trans_info = [] then pr2 "transformation info is empty"
else begin
pr2 "transformation info returned:";
let trans_info =
List.sort (function (i1,_,_) -> function (i2,_,_) -> compare i1 i2)
trans_info
in
indent_do (fun () ->
trans_info +> List.iter (fun (i, subst, re) ->
pr2 ("transform state: " ^ (string_of_int i));
indent_do (fun () ->
adjust_pp_with_indent_and_header "with rule_elem: " (fun () ->
Pretty_print_cocci.print_plus_flag := true;
Pretty_print_cocci.print_minus_flag := true;
Pretty_print_cocci.rule_elem "" re;
);
adjust_pp_with_indent_and_header "with binding: " (fun () ->
Pretty_print_engine.pp_binding subst;
);
)
);
)
end
end
let show_or_not_trans_info a =
Common.profile_code "show_xxx" (fun () -> show_or_not_trans_info2 a)
let show_or_not_binding2 s binding =
if !Flag_cocci.show_binding_in_out then begin
adjust_pp_with_indent_and_header ("binding " ^ s ^ " = ") (fun () ->
Pretty_print_engine.pp_binding binding
)
end
let show_or_not_binding a b =
Common.profile_code "show_xxx" (fun () -> show_or_not_binding2 a b)
(*****************************************************************************)
(* Some helper functions *)
(*****************************************************************************)
let worth_trying2 cfiles (tokens,_,query,_) =
(* drop the following line for a list of list by rules. since we don't
allow multiple minirules, all the tokens within a rule should be in
a single CFG entity *)
let res =
match (!Flag_cocci.windows,!Flag.scanner,tokens,query,cfiles) with
(true,_,_,_,_) | (_,_,None,_,_) | (_,_,_,None,_) | (_,Flag.CocciGrep,_,_,_)
| (_,Flag.GitGrep,_,_,_)
-> true
| (_,_,_,Some (q1,q2,_),[(cfile,_)]) -> Cocci_grep.interpret (q1,q2) cfile
| (_,_,Some tokens,_,_) ->
(* could also modify the code in get_constants.ml *)
let tokens = tokens +> List.map (fun s ->
match () with
| _ when s =~ "^[A-Za-z_][A-Za-z_0-9]*$" ->
"\\b" ^ s ^ "\\b"
| _ when s =~ "^[A-Za-z_]" ->
"\\b" ^ s
| _ when s =~ ".*[A-Za-z_]$" ->
s ^ "\\b"
| _ -> s
) in
let com =
Printf.sprintf "egrep -q '(%s)' %s"
(String.concat "|" tokens)
(String.concat " " (List.map fst cfiles)) in
(match Sys.command com with
| 0 (* success *) -> true
| _ (* failure *) ->
(if !Flag.show_misc
then pr2 ("grep failed: " ^ com));
false (* no match, so not worth trying *)) in
(match (res,tokens) with
(false,Some tokens) ->
pr2_once ("Expected tokens " ^ (String.concat " " tokens));
pr2 ("Skipping: " ^ (String.concat " " (List.map fst cfiles)))
| _ -> ());
res
let worth_trying a b =
Common.profile_code "worth_trying" (fun () ->
try worth_trying2 a b
with Flag.UnreadableFile file ->
begin
pr2 ("Skipping unreadable file: " ^ file);
false
end)
let check_macro_in_sp_and_adjust = function
None -> ()
| Some tokens ->
tokens +> List.iter (fun s ->
if Hashtbl.mem !Parse_c._defs s
then begin
if !Flag_cocci.verbose_cocci then begin
pr2 "warning: macro in semantic patch was in macro definitions";
pr2 ("disabling macro expansion for " ^ s);
end;
Hashtbl.remove !Parse_c._defs s
end)
let contain_loop gopt =
match gopt with
| Some g ->
Control_flow_c.KeyMap.exists (fun xi node ->
Control_flow_c.extract_is_loop node
) g#nodes
| None -> true (* means nothing, if no g then will not model check *)
let sp_contain_typed_metavar_z toplevel_list_list =
let bind x y = x || y in
let option_default = false in
let mcode _ _ = option_default in
let donothing r k e = k e in
let expression r k e =
match Ast_cocci.unwrap e with
| Ast_cocci.MetaExpr (_,_,_,Some t,_,_,_bitfield) -> true
| _ -> k e
in
let combiner =
Visitor_ast.combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode mcode mcode mcode
donothing donothing donothing donothing donothing donothing donothing
donothing expression donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing
in
toplevel_list_list +>
List.exists
(function (nm,_,rule) ->
(List.exists combiner.Visitor_ast.combiner_top_level rule))
let sp_contain_typed_metavar rules =
sp_contain_typed_metavar_z
(List.map
(function x ->
match x with
Ast_cocci.CocciRule (a,b,c,d,_) -> (a,b,c)
| _ -> failwith "error in filter")
(List.filter
(function x ->
match x with
Ast_cocci.CocciRule (a,b,c,d,Ast_cocci.Normal) -> true
| _ -> false)
rules))
let rec interpret_dependencies local global d =
let rec loop local = function
Ast_cocci.Dep s -> List.mem s local
| Ast_cocci.AntiDep s ->
(if !Flag_ctl.steps != None
then failwith "steps and ! dependency incompatible");
not (List.mem s local)
| Ast_cocci.EverDep s -> List.mem s global
| Ast_cocci.NeverDep s ->
(if !Flag_ctl.steps != None
then failwith "steps and ! dependency incompatible");
not (List.mem s global)
| Ast_cocci.AndDep(s1,s2) -> (loop local s1) && (loop local s2)
| Ast_cocci.OrDep(s1,s2) -> (loop local s1) || (loop local s2)
| Ast_cocci.FileIn _ | Ast_cocci.NotFileIn _ -> true in
match d with
Ast_cocci.NoDep -> true
| Ast_cocci.FailDep -> false
| Ast_cocci.ExistsDep d ->
if local = []
then loop [] d (* rely on globals *)
else List.exists (fun l -> loop l d) local
| Ast_cocci.ForallDep d ->
if local = []
then loop [] d (* rely on globals *)
else List.for_all (fun l -> loop l d) local
let rec interpret_file file d =
let rec loop = function
Ast_cocci.Dep _ | Ast_cocci.AntiDep _
| Ast_cocci.EverDep _ | Ast_cocci.NeverDep _ -> true
| Ast_cocci.AndDep(s1,s2) ->
(loop s1) && (loop s2)
| Ast_cocci.OrDep(s1,s2) -> (loop s1) || (loop s2)
| Ast_cocci.FileIn s ->
(s = file || Str.string_match (Str.regexp (s^"/")) file 0)
| Ast_cocci.NotFileIn s ->
not (s = file || Str.string_match (Str.regexp (s^"/")) file 0) in
match d with
Ast_cocci.NoDep -> true
| Ast_cocci.FailDep -> failwith "FailDep not possible"
| Ast_cocci.ExistsDep d -> loop d
| Ast_cocci.ForallDep d -> loop d
let print_dependencies str local global dep =
if !Flag_cocci.show_dependencies
then
begin
pr2 str;
let seen = ref [] in
let rec loop local = function
Ast_cocci.Dep s | Ast_cocci.AntiDep s ->
if not (List.mem s !seen)
then
begin
if List.mem s local
then pr2 (s^" satisfied")
else pr2 (s^" not satisfied");
seen := s :: !seen
end
| Ast_cocci.EverDep s | Ast_cocci.NeverDep s ->
if not (List.mem s !seen)
then
begin
if List.mem s global
then pr2 (s^" satisfied")
else pr2 (s^" not satisfied");
seen := s :: !seen
end
| Ast_cocci.AndDep(s1,s2) ->
loop local s1;
loop local s2
| Ast_cocci.OrDep(s1,s2) ->
loop local s1;
loop local s2
| Ast_cocci.FileIn _ | Ast_cocci.NotFileIn _ -> () in
match dep with
Ast_cocci.NoDep -> ()
| Ast_cocci.FailDep -> pr2 "False not satisfied"
| Ast_cocci.ExistsDep d | Ast_cocci.ForallDep d ->
if local = []
then loop [] d
else List.iter (fun l -> loop l d) local
end
(* --------------------------------------------------------------------- *)
(* #include relative position in the file *)
(* --------------------------------------------------------------------- *)
(* compute the set of new prefixes
* on
* "a/b/x"; (* in fact it is now a list of string so ["a";"b";"x"] *)
* "a/b/c/x";
* "a/x";
* "b/x";
* it would give for the first element
* ""; "a"; "a/b"; "a/b/x"
* for the second
* "a/b/c/x"
*
* update: if the include is inside a ifdef a put nothing. cf -test incl.
* this is because we don't want code added inside ifdef.
*)
let compute_new_prefixes xs =
xs +> Common.map_withenv (fun already xs ->
let subdirs_prefixes = Common.inits xs in
let new_first = subdirs_prefixes +> List.filter (fun x ->
not (List.mem x already)
)
in
new_first,
new_first @ already
) []
+> fst
(* does via side effect on the ref in the Include in Ast_c *)
let rec update_include_rel_pos cs =
let only_include = cs +> Common.map_filter (fun c ->
match c with
| Ast_c.CppTop (Ast_c.Include {Ast_c.i_include = ((x,_));
i_rel_pos = aref;
i_overall_rel_pos = oref;
i_is_in_ifdef = inifdef}) ->
(match x with
| Ast_c.Weird _ -> None
| _ ->
if inifdef
then None
else Some (x, (aref, oref))
)
| _ -> None
)
in
let (locals, nonlocals) =
only_include +> Common.partition_either (fun (c, refs) ->
match c with
| Ast_c.Local x -> Left (x, refs)
| Ast_c.NonLocal x -> Right (x, refs)
| Ast_c.Weird x -> raise (Impossible 161)
) in
let all =
only_include +> List.map (fun (c, refs) ->
match c with
| Ast_c.Local x -> (x, refs)
| Ast_c.NonLocal x -> (x, refs)
| Ast_c.Weird x -> raise (Impossible 161)
) in
update_rel_pos_bis fst locals;
update_rel_pos_bis fst nonlocals;
update_rel_pos_bis snd all;
cs
and update_rel_pos_bis choose_ref xs =
let xs' = List.map fst xs in
let the_first = compute_new_prefixes xs' in
let the_last = List.rev (compute_new_prefixes (List.rev xs')) in
let merged = Common.zip xs (Common.zip the_first the_last) in
merged +> List.iter (fun ((x, refs), (the_first, the_last)) ->
(choose_ref refs) := Some
{
Ast_c.first_of = the_first;
Ast_c.last_of = the_last;
}
)
(*****************************************************************************)
(* All the information needed around the C elements and Cocci rules *)
(*****************************************************************************)
type toplevel_c_info = {
ast_c: Ast_c.toplevel; (* contain refs so can be modified *)
start_end: (Ast_c.posl * Ast_c.posl) Lazy.t;
tokens_c: Parser_c.token list;
fullstring: string;
flow: Control_flow_c.cflow option; (* it's the "fixed" flow *)
contain_loop: bool;
env_typing_before: TAC.environment;
env_typing_after: TAC.environment;
was_modified: bool ref;
all_typedefs: (string, Lexer_parser.identkind) Common.scoped_h_env;
all_macros: (string, Cpp_token_c.define_def) Hashtbl.t;
(* id: int *)
}
type rule_info = {
rulename: string;
dependencies: Ast_cocci.dependency;
used_after: Ast_cocci.meta_name list;
ruleid: int;
was_matched: bool ref;
}
type toplevel_cocci_info_script_rule = {
scr_ast_rule:
string *
(Ast_cocci.script_meta_name * Ast_cocci.meta_name *
Ast_cocci.metavar * Ast_cocci.mvinit) list *
Ast_cocci.meta_name list (*fresh vars*) * Ast_cocci.script_position *
string;
language: string;
scr_pos: Ast_cocci.script_position;
script_code: string;
scr_rule_info: rule_info;
}
type toplevel_cocci_info_cocci_rule = {
ctl: Asttoctl2.top_formula * (CCI.pred list list);
metavars: Ast_cocci.metavar list;
ast_rule: Ast_cocci.rule;
isexp: bool; (* true if + code is an exp, only for Flag.make_hrule *)
(* There are also some hardcoded rule names in parse_cocci.ml:
* let reserved_names = ["all";"optional_storage";"optional_qualifier"]
*)
dropped_isos: string list;
free_vars: Ast_cocci.meta_name list;
special_pos_vars:
Ast_cocci.meta_name list (*negated*) *
Ast_cocci.meta_name list (*"all"*);
positions: Ast_cocci.meta_name list;
ruletype: Ast_cocci.ruletype;
rule_info: rule_info;
constraint_languages: Common.StringSet.t;
}
type toplevel_cocci_info =
ScriptRuleCocciInfo of toplevel_cocci_info_script_rule
| InitialScriptRuleCocciInfo of toplevel_cocci_info_script_rule
| FinalScriptRuleCocciInfo of toplevel_cocci_info_script_rule
| CocciRuleCocciInfo of toplevel_cocci_info_cocci_rule
type merge_vars = string array list * string array list
let union_merge_vars (ocaml_merges, python_merges)
(ocaml_merges', python_merges') =
let all_ocaml_merges = List.rev_append ocaml_merges ocaml_merges' in
let all_python_merges = List.rev_append python_merges python_merges' in
(all_ocaml_merges, all_python_merges)
type cocci_info = toplevel_cocci_info list * bool (* true if no changes *)
* bool (* parsing of format strings needed *)
* ((string * (int * string array)) list *
string array) (* merge/local variables for Python *)
type constant_info =
(string list option (*grep tokens*) *
string list option (*glimpse tokens*) *
(Str.regexp * Str.regexp list * string list)
option (*coccigrep/gitgrep tokens*) *
Get_constants2.combine option)
type kind_file = Header | Source
let string_of_kind_file = function
| Header -> "Header"
| Source -> "Source"
type file_info = {
fname : string;
full_fname : string;
was_modified_once: bool ref;
asts: toplevel_c_info list;
fpath : string;
fkind : kind_file;
}
let string_of_file_info fi =
let field name value = name ^ " = " ^ value in
let structure fields =
"{ " ^ (String.concat "; " fields ) ^ " }" in
structure [
field "fname" fi.fname;
field "full_name" fi.full_fname;
field "was_modified_once" (string_of_bool !(fi.was_modified_once));
field "asts" (string_of_int (List.length fi.asts));
field "fpath" fi.fpath;
field "fkind" (string_of_kind_file fi.fkind)
]
let g_contain_typedmetavar = ref false
let last_env_toplevel_c_info xs =
(Common.last xs).env_typing_after
let concat_headers_and_c (ccs: file_info list)
: (toplevel_c_info * string * string) list =
(List.concat
(ccs +>
List.map
(fun x -> x.asts +> List.map (fun x' -> (x', x.fname, x.full_fname)))))
let for_unparser xs =
xs +> List.map (fun x ->
(x.ast_c, (x.fullstring, x.tokens_c)), Unparse_c.PPviastr
)
let gen_pdf_graph () =
(Ctl_engine.get_graph_files ()) +> List.iter (fun outfile ->
Printf.printf "Generation of %s%!" outfile;
let filename_stack = Ctl_engine.get_graph_comp_files outfile in
List.iter (fun filename ->
ignore (Unix.system ("dot " ^ filename ^ " -Tpdf -o " ^ filename ^ ".pdf;"))
) filename_stack;
let (head,tail) = (List.hd filename_stack, List.tl filename_stack) in
ignore(Unix.system ("cp " ^ head ^ ".pdf " ^ outfile ^ ".pdf;"));
tail +> List.iter (fun filename ->
ignore(Unix.system ("mv " ^ outfile ^ ".pdf /tmp/tmp.pdf;"));
ignore(Unix.system ("pdftk " ^ filename ^ ".pdf /tmp/tmp.pdf cat output " ^ outfile ^ ".pdf"));
);
ignore(Unix.system ("rm /tmp/tmp.pdf;"));
List.iter (fun filename ->
ignore (Unix.system ("rm " ^ filename ^ " " ^ filename ^ ".pdf;"))
) filename_stack;
Printf.printf " - Done\n")
let local_python_code = "\
from coccinelle import *
from coccilib.iteration import Iteration
"
let python_code =
"import coccinelle\n"^
"import coccilib\n"^
"import coccilib.org\n"^
"import coccilib.report\n" ^
"import coccilib.xml_firehose\n" ^
local_python_code ^
"cocci = Cocci()\n"
let make_init lang pos code rule_info mv =
{
scr_ast_rule = (lang, mv, [], pos, code);
language = lang;
scr_pos = pos;
script_code = (if lang = "python" then python_code else "") ^code;
scr_rule_info = rule_info;
}
(* --------------------------------------------------------------------- *)
let prepare_cocci ctls free_var_lists negated_pos_lists
(ua,fua,fuas) positions_list metavars astcocci =
let gathered = Common.index_list_1
(zip (zip (zip (zip (zip (zip (zip (zip ctls metavars) astcocci)
free_var_lists)
negated_pos_lists) ua) fua) fuas) positions_list)
in
gathered +> List.map
(fun (((((((((ctl_toplevel_list,metavars),ast),free_var_list),
negated_pos_list),ua),fua),fuas),positions_list),rulenb) ->
let build_rule_info rulename deps =
{rulename = rulename;
dependencies = deps;
used_after = (List.hd ua) @ (List.hd fua);
ruleid = rulenb;
was_matched = ref false;} in
let is_script_rule r =
match r with
Ast_cocci.ScriptRule _
| Ast_cocci.InitialScriptRule _ | Ast_cocci.FinalScriptRule _ -> true
| _ -> false in
if not (List.length ctl_toplevel_list = 1) && not (is_script_rule ast)