2 * Copyright 2010, INRIA, University of Copenhagen
3 * Julia Lawall, Rene Rydhof Hansen, Gilles Muller, Nicolas Palix
4 * Copyright 2005-2009, Ecole des Mines de Nantes, University of Copenhagen
5 * Yoann Padioleau, Julia Lawall, Rene Rydhof Hansen, Henrik Stuart, Gilles Muller, Nicolas Palix
6 * This file is part of Coccinelle.
8 * Coccinelle is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, according to version 2 of the License.
12 * Coccinelle is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Coccinelle. If not, see <http://www.gnu.org/licenses/>.
20 * The authors reserve the right to distribute this or future versions of
21 * Coccinelle under other licenses.
27 module CCI
= Ctlcocci_integration
28 module TAC
= Type_annoter_c
30 module Ast_to_flow
= Control_flow_c_build
32 (*****************************************************************************)
33 (* This file is a kind of driver. It gathers all the important functions
34 * from coccinelle in one place. The different entities in coccinelle are:
38 * - flow (contain nodes)
39 * - ctl (contain rule_elems)
40 * This file contains functions to transform one in another.
42 (*****************************************************************************)
44 (* --------------------------------------------------------------------- *)
46 (* --------------------------------------------------------------------- *)
47 let cprogram_of_file file
=
48 let (program2
, _stat
) = Parse_c.parse_c_and_cpp file
in
51 let cprogram_of_file_cached file
=
52 let (program2
, _stat
) = Parse_c.parse_cache file
in
53 if !Flag_cocci.ifdef_to_if
55 program2
+> Parse_c.with_program2
(fun asts
->
56 Cpp_ast_c.cpp_ifdef_statementize asts
60 let cfile_of_program program2_with_ppmethod outf
=
61 Unparse_c.pp_program program2_with_ppmethod outf
63 (* for memoization, contains only one entry, the one for the SP *)
64 let _hparse = Hashtbl.create
101
65 let _hctl = Hashtbl.create
101
67 (* --------------------------------------------------------------------- *)
69 (* --------------------------------------------------------------------- *)
70 let sp_of_file2 file iso
=
71 Common.memoized
_hparse (file
, iso
) (fun () ->
72 let (_
,xs
,_
,_
,_
,_
,_
,_
) as res
= Parse_cocci.process file iso
false in
73 (match Prepare_ocamlcocci.prepare file xs
with
75 | Some ocaml_script_file
->
77 Prepare_ocamlcocci.load_file ocaml_script_file
;
78 if not
!Common.save_tmp_files
79 then Prepare_ocamlcocci.clean_file ocaml_script_file
);
81 let sp_of_file file iso
=
82 Common.profile_code
"parse cocci" (fun () -> sp_of_file2 file iso
)
85 (* --------------------------------------------------------------------- *)
87 (* --------------------------------------------------------------------- *)
89 Ograph_extended.print_ograph_mutable flow
"/tmp/test.dot" true
92 let ast_to_flow_with_error_messages2 x
=
94 try Ast_to_flow.ast_to_control_flow x
95 with Ast_to_flow.Error x
->
96 Ast_to_flow.report_error x
;
99 flowopt +> do_option
(fun flow
->
100 (* This time even if there is a deadcode, we still have a
101 * flow graph, so I can try the transformation and hope the
102 * deadcode will not bother us.
104 try Ast_to_flow.deadcode_detection flow
105 with Ast_to_flow.Error
(Ast_to_flow.DeadCode x
) ->
106 Ast_to_flow.report_error
(Ast_to_flow.DeadCode x
);
109 let ast_to_flow_with_error_messages a
=
110 Common.profile_code
"flow" (fun () -> ast_to_flow_with_error_messages2 a
)
113 (* --------------------------------------------------------------------- *)
115 (* --------------------------------------------------------------------- *)
117 let ctls_of_ast2 ast
(ua
,fua
,fuas
) pos
=
119 (function ast
-> function (ua
,(fua
,(fuas
,pos
))) ->
123 else Asttoctl2.asttoctl ast
(ua
,fua
,fuas
) pos
)
124 (Asttomember.asttomember ast ua
))
125 ast
(List.combine ua
(List.combine fua
(List.combine fuas pos
)))
127 let ctls_of_ast ast ua
=
128 Common.profile_code
"asttoctl2" (fun () -> ctls_of_ast2 ast ua
)
130 (*****************************************************************************)
131 (* Some debugging functions *)
132 (*****************************************************************************)
136 let show_or_not_cfile2 cfile
=
137 if !Flag_cocci.show_c
then begin
138 Common.pr2_xxxxxxxxxxxxxxxxx
();
139 pr2
("processing C file: " ^ cfile
);
140 Common.pr2_xxxxxxxxxxxxxxxxx
();
141 Common.command2
("cat " ^ cfile
);
143 let show_or_not_cfile a
=
144 Common.profile_code
"show_xxx" (fun () -> show_or_not_cfile2 a
)
146 let show_or_not_cfiles cfiles
= List.iter
show_or_not_cfile cfiles
149 let show_or_not_cocci2 coccifile isofile
=
150 if !Flag_cocci.show_cocci
then begin
151 Common.pr2_xxxxxxxxxxxxxxxxx
();
152 pr2
("processing semantic patch file: " ^ coccifile
);
153 isofile
+> (fun s
-> pr2
("with isos from: " ^ s
));
154 Common.pr2_xxxxxxxxxxxxxxxxx
();
155 Common.command2
("cat " ^ coccifile
);
158 let show_or_not_cocci a b
=
159 Common.profile_code
"show_xxx" (fun () -> show_or_not_cocci2 a b
)
161 (* ---------------------------------------------------------------------- *)
164 let fix_sgrep_diffs l
=
166 List.filter
(function s
-> (s
=~
"^\\+\\+\\+") || not
(s
=~
"^\\+")) l in
167 let l = List.rev
l in
168 (* adjust second number for + code *)
169 let rec loop1 n
= function
172 if s
=~
"^-" && not
(s
=~
"^---")
173 then s
:: loop1 (n
+1) ss
176 (match Str.split
(Str.regexp
" ") s
with
179 match Str.split
(Str.regexp
",") pl
with
182 | _
-> failwith
"bad + line information" in
183 let n2 = int_of_string
n2 in
184 (Printf.sprintf
"%s %s %s,%d %s" bef min n1
(n2-n
)
185 (String.concat
" " aft
))
187 | _
-> failwith
"bad @@ information")
188 else s
:: loop1 n ss
in
189 let rec loop2 n
= function
196 (match Str.split
(Str.regexp
" ") s
with
199 match (Str.split
(Str.regexp
",") min
,
200 Str.split
(Str.regexp
",") pl
) with
201 ([_
;m2
],[n1
;n2]) -> (m2
,n1
,n2)
202 | ([_
],[n1
;n2]) -> ("1",n1
,n2)
203 | ([_
;m2
],[n1
]) -> (m2
,n1
,"1")
204 | ([_
],[n1
]) -> ("1",n1
,"1")
205 | _
-> failwith
"bad -/+ line information" in
207 int_of_string
(String.sub
n1 1 ((String.length
n1)-1)) in
208 let m2 = int_of_string
m2 in
209 let n2 = int_of_string
n2 in
210 (Printf.sprintf
"%s %s +%d,%d %s" bef min
(n1-n
) n2
211 (String.concat
" " aft
))
212 :: loop2 (n
+(m2-n2)) ss
213 | _
-> failwith
"bad @@ information")
214 else s
:: loop2 n ss
in
215 loop2 0 (List.rev
(loop1 0 l))
217 let normalize_path file
=
219 if String.get file
0 = '
/'
then file
else (Sys.getcwd
()) ^
"/" ^ file
in
220 let elements = Str.split_delim
(Str.regexp
"/") fullpath in
221 let rec loop prev
= function
222 [] -> String.concat
"/" (List.rev prev
)
223 | "." :: rest
-> loop prev rest
226 x
::xs
-> loop xs rest
227 | _
-> failwith
"bad path")
228 | x
::rest
-> loop (x
::prev
) rest
in
231 let show_or_not_diff2 cfile outfile
=
232 if !Flag_cocci.show_diff
then begin
233 match Common.fst
(Compare_c.compare_to_original cfile outfile
) with
234 Compare_c.Correct
-> () (* diff only in spacing, etc *)
236 (* may need --strip-trailing-cr under windows *)
240 match !Flag_parsing_c.diff_lines
with
241 | None
-> "diff -u -p " ^ cfile ^
" " ^ outfile
242 | Some n
-> "diff -U "^n^
" -p "^cfile^
" "^outfile
in
244 let res = Common.cmd_to_list
line in
245 match (!Flag.patch
,res) with
246 (* create something that looks like the output of patch *)
247 (Some prefix
,minus_file
::plus_file
::rest
) ->
249 let lp = String.length
prefix in
250 if String.get
prefix (lp-1) = '
/'
251 then String.sub
prefix 0 (lp-1)
253 let drop_prefix file
=
254 let file = normalize_path file in
255 if Str.string_match
(Str.regexp
prefix) file 0
257 let lp = String.length
prefix in
258 let lf = String.length
file in
260 then String.sub
file lp (lf - lp)
263 (Printf.sprintf
"prefix %s doesn't match file %s"
267 (Printf.sprintf
"prefix %s doesn't match file %s"
270 match List.rev
(Str.split
(Str.regexp
" ") line) with
271 new_file
::old_file
::cmdrev
->
272 let old_base_file = drop_prefix old_file
in
277 (("/tmp/nothing"^
old_base_file)
278 :: old_file
:: cmdrev
))
282 (("b"^
old_base_file)::("a"^
old_base_file)::cmdrev
))
283 | _
-> failwith
"bad command" in
284 let (minus_line
,plus_line
) =
285 match (Str.split
(Str.regexp
"[ \t]") minus_file
,
286 Str.split
(Str.regexp
"[ \t]") plus_file
) with
287 ("---"::old_file
::old_rest
,"+++"::new_file
::new_rest
) ->
288 let old_base_file = drop_prefix old_file
in
290 then (minus_file
,"+++ /tmp/nothing"^
old_base_file)
293 ("---"::("a"^
old_base_file)::old_rest
),
295 ("+++"::("b"^
old_base_file)::new_rest
))
298 (Printf.sprintf
"bad diff header lines: %s %s"
299 (String.concat
":" l1
) (String.concat
":" l2
)) in
300 diff_line::minus_line
::plus_line
::rest
302 let xs = if !Flag.sgrep_mode2
then fix_sgrep_diffs xs else xs in
305 let show_or_not_diff a b
=
306 Common.profile_code
"show_xxx" (fun () -> show_or_not_diff2 a b
)
309 (* the derived input *)
311 let show_or_not_ctl_tex2 astcocci ctls
=
312 if !Flag_cocci.show_ctl_tex
then begin
313 Ctltotex.totex
("/tmp/__cocci_ctl.tex") astcocci ctls
;
314 Common.command2
("cd /tmp; latex __cocci_ctl.tex; " ^
315 "dvips __cocci_ctl.dvi -o __cocci_ctl.ps;" ^
316 "gv __cocci_ctl.ps &");
318 let show_or_not_ctl_tex a b
=
319 Common.profile_code
"show_xxx" (fun () -> show_or_not_ctl_tex2 a b
)
322 let show_or_not_rule_name ast rulenb
=
323 if !Flag_cocci.show_ctl_text
or !Flag.show_trying
or
324 !Flag.show_transinfo
or !Flag_cocci.show_binding_in_out
329 Ast_cocci.CocciRule
(nm
, (deps
, drops
, exists
), x
, _
, _
) -> nm
330 | _
-> i_to_s rulenb
in
331 Common.pr_xxxxxxxxxxxxxxxxx
();
333 Common.pr_xxxxxxxxxxxxxxxxx
()
336 let show_or_not_scr_rule_name rulenb
=
337 if !Flag_cocci.show_ctl_text
or !Flag.show_trying
or
338 !Flag.show_transinfo
or !Flag_cocci.show_binding_in_out
341 let name = i_to_s rulenb
in
342 Common.pr_xxxxxxxxxxxxxxxxx
();
343 pr
("script rule " ^
name ^
" = ");
344 Common.pr_xxxxxxxxxxxxxxxxx
()
347 let show_or_not_ctl_text2 ctl ast rulenb
=
348 if !Flag_cocci.show_ctl_text
then begin
350 adjust_pp_with_indent
(fun () ->
351 Format.force_newline
();
352 Pretty_print_cocci.print_plus_flag
:= true;
353 Pretty_print_cocci.print_minus_flag
:= true;
354 Pretty_print_cocci.unparse ast
;
359 adjust_pp_with_indent
(fun () ->
360 Format.force_newline
();
361 Pretty_print_engine.pp_ctlcocci
362 !Flag_cocci.show_mcodekind_in_ctl
!Flag_cocci.inline_let_ctl ctl
;
366 let show_or_not_ctl_text a b c
=
367 Common.profile_code
"show_xxx" (fun () -> show_or_not_ctl_text2 a b c
)
371 (* running information *)
372 let get_celem celem
: string =
374 Ast_c.Definition
({Ast_c.f_name
= namefuncs
;},_
) ->
375 Ast_c.str_of_name namefuncs
377 (Ast_c.DeclList
([{Ast_c.v_namei
= Some
(name, _
);}, _
], _
)) ->
378 Ast_c.str_of_name
name
381 let show_or_not_celem2 prelude celem
=
384 | Ast_c.Definition
({Ast_c.f_name
= namefuncs
},_
) ->
385 let funcs = Ast_c.str_of_name namefuncs
in
386 Flag.current_element
:= funcs;
387 (" function: ",funcs)
389 (Ast_c.DeclList
([{Ast_c.v_namei
= Some
(name,_
)}, _
], _
)) ->
390 let s = Ast_c.str_of_name
name in
391 Flag.current_element
:= s;
394 Flag.current_element
:= "something_else";
395 (" ","something else");
397 if !Flag.show_trying
then pr2
(prelude ^ tag ^ trying
)
399 let show_or_not_celem a b
=
400 Common.profile_code
"show_xxx" (fun () -> show_or_not_celem2 a b
)
403 let show_or_not_trans_info2 trans_info
=
404 (* drop witness tree indices for printing *)
406 List.map
(function (index
,trans_info) -> trans_info) trans_info in
407 if !Flag.show_transinfo
then begin
408 if null
trans_info then pr2
"transformation info is empty"
410 pr2
"transformation info returned:";
412 List.sort
(function (i1
,_
,_
) -> function (i2
,_
,_
) -> compare i1 i2
)
416 trans_info +> List.iter
(fun (i
, subst
, re
) ->
417 pr2
("transform state: " ^
(Common.i_to_s i
));
419 adjust_pp_with_indent_and_header
"with rule_elem: " (fun () ->
420 Pretty_print_cocci.print_plus_flag
:= true;
421 Pretty_print_cocci.print_minus_flag
:= true;
422 Pretty_print_cocci.rule_elem
"" re
;
424 adjust_pp_with_indent_and_header
"with binding: " (fun () ->
425 Pretty_print_engine.pp_binding subst
;
432 let show_or_not_trans_info a
=
433 Common.profile_code
"show_xxx" (fun () -> show_or_not_trans_info2 a
)
437 let show_or_not_binding2 s binding
=
438 if !Flag_cocci.show_binding_in_out
then begin
439 adjust_pp_with_indent_and_header
("binding " ^
s ^
" = ") (fun () ->
440 Pretty_print_engine.pp_binding binding
443 let show_or_not_binding a b
=
444 Common.profile_code
"show_xxx" (fun () -> show_or_not_binding2 a b
)
448 (*****************************************************************************)
449 (* Some helper functions *)
450 (*****************************************************************************)
452 let worth_trying cfiles tokens
=
453 (* drop the following line for a list of list by rules. since we don't
454 allow multiple minirules, all the tokens within a rule should be in
455 a single CFG entity *)
456 match (!Flag_cocci.windows
,tokens
) with
457 (true,_
) | (_
,None
) -> true
459 (* could also modify the code in get_constants.ml *)
460 let tokens = tokens +> List.map
(fun s ->
462 | _
when s =~
"^[A-Za-z_][A-Za-z_0-9]*$" ->
465 | _
when s =~
"^[A-Za-z_]" ->
468 | _
when s =~
".*[A-Za-z_]$" ->
473 let com = sprintf
"egrep -q '(%s)' %s" (join
"|" tokens) (join
" " cfiles
)
475 (match Sys.command
com with
476 | 0 (* success *) -> true
479 then Printf.printf
"grep failed: %s\n" com);
480 false (* no match, so not worth trying *))
482 let check_macro_in_sp_and_adjust = function
485 tokens +> List.iter
(fun s ->
486 if Hashtbl.mem
!Parse_c._defs
s
488 if !Flag_cocci.verbose_cocci
then begin
489 pr2
"warning: macro in semantic patch was in macro definitions";
490 pr2
("disabling macro expansion for " ^
s);
492 Hashtbl.remove
!Parse_c._defs
s
496 let contain_loop gopt
=
499 g#nodes#tolist
+> List.exists
(fun (xi
, node
) ->
500 Control_flow_c.extract_is_loop node
502 | None
-> true (* means nothing, if no g then will not model check *)
506 let sp_contain_typed_metavar_z toplevel_list_list
=
507 let bind x y
= x
or y
in
508 let option_default = false in
509 let mcode _ _
= option_default in
510 let donothing r k e
= k e
in
512 let expression r k e
=
513 match Ast_cocci.unwrap e
with
514 | Ast_cocci.MetaExpr
(_
,_
,_
,Some t
,_
,_
) -> true
515 | Ast_cocci.MetaExpr
(_
,_
,_
,_
,Ast_cocci.LocalID
,_
) -> true
520 Visitor_ast.combiner bind option_default
521 mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode
522 donothing donothing donothing donothing donothing
523 donothing expression donothing donothing donothing donothing donothing
524 donothing donothing donothing donothing donothing
526 toplevel_list_list
+>
528 (function (nm
,_
,rule
) ->
529 (List.exists
combiner.Visitor_ast.combiner_top_level rule
))
531 let sp_contain_typed_metavar rules
=
532 sp_contain_typed_metavar_z
536 Ast_cocci.CocciRule
(a
,b
,c
,d
,_
) -> (a
,b
,c
)
537 | _
-> failwith
"error in filter")
541 Ast_cocci.CocciRule
(a
,b
,c
,d
,Ast_cocci.Normal
) -> true
547 (* finding among the #include the one that we need to parse
548 * because they may contain useful type definition or because
549 * we may have to modify them
551 * For the moment we base in part our heuristic on the name of the file, e.g.
552 * serio.c is related we think to #include <linux/serio.h>
554 let rec search_include_path searchlist relpath
=
555 match searchlist
with
558 let file = Filename.concat hd relpath
in
559 if Sys.file_exists
file then
562 search_include_path tail relpath
564 let interpret_include_path relpath
=
566 match !Flag_cocci.include_path
with
570 search_include_path searchlist relpath
572 let (includes_to_parse
:
573 (Common.filename
* Parse_c.program2
) list
->
574 Flag_cocci.include_options
-> 'a
) = fun xs choose_includes
->
575 match choose_includes
with
576 Flag_cocci.I_UNSPECIFIED
-> failwith
"not possible"
577 | Flag_cocci.I_NO_INCLUDES
-> []
579 let all_includes = x
=*= Flag_cocci.I_ALL_INCLUDES
in
580 xs +> List.map
(fun (file, cs
) ->
581 let dir = Common.dirname
file in
583 cs
+> Common.map_filter
(fun (c
,_info_item
) ->
587 {Ast_c.i_include
= ((x
,ii
)); i_rel_pos
= info_h_pos
;}) ->
590 let relpath = Common.join
"/" xs in
591 let f = Filename.concat
dir (relpath) in
592 if (Sys.file_exists
f) then
595 if !Flag_cocci.relax_include_path
596 (* for our tests, all the files are flat in the current dir *)
598 let attempt2 = Filename.concat
dir (Common.last
xs) in
599 if not
(Sys.file_exists
attempt2) && all_includes
601 interpret_include_path relpath
604 if all_includes then interpret_include_path relpath
607 | Ast_c.NonLocal
xs ->
608 let relpath = Common.join
"/" xs in
610 Common.fileprefix
(Common.last
xs) =$
= Common.fileprefix
file
612 interpret_include_path relpath
614 | Ast_c.Weird _
-> None
620 let rec interpret_dependencies local global
= function
621 Ast_cocci.Dep
s -> List.mem
s local
622 | Ast_cocci.AntiDep
s ->
623 (if !Flag_ctl.steps
!= None
624 then failwith
"steps and ! dependency incompatible");
625 not
(List.mem
s local
)
626 | Ast_cocci.EverDep
s -> List.mem
s global
627 | Ast_cocci.NeverDep
s ->
628 (if !Flag_ctl.steps
!= None
629 then failwith
"steps and ! dependency incompatible");
630 not
(List.mem
s global
)
631 | Ast_cocci.AndDep
(s1
,s2
) ->
632 (interpret_dependencies local global s1
) &&
633 (interpret_dependencies local global s2
)
634 | Ast_cocci.OrDep
(s1
,s2
) ->
635 (interpret_dependencies local global s1
) or
636 (interpret_dependencies local global s2
)
637 | Ast_cocci.NoDep
-> true
638 | Ast_cocci.FailDep
-> false
640 let rec print_dependencies str local global dep
=
641 if !Flag_cocci.show_dependencies
646 let rec loop = function
647 Ast_cocci.Dep
s | Ast_cocci.AntiDep
s ->
648 if not
(List.mem
s !seen)
652 then pr2
(s^
" satisfied")
653 else pr2
(s^
" not satisfied");
656 | Ast_cocci.EverDep
s | Ast_cocci.NeverDep
s ->
657 if not
(List.mem
s !seen)
661 then pr2
(s^
" satisfied")
662 else pr2
(s^
" not satisfied");
665 | Ast_cocci.AndDep
(s1
,s2
) ->
668 | Ast_cocci.OrDep
(s1
,s2
) ->
671 | Ast_cocci.NoDep
-> ()
672 | Ast_cocci.FailDep
-> pr2
"False not satisfied" in
676 (* --------------------------------------------------------------------- *)
677 (* #include relative position in the file *)
678 (* --------------------------------------------------------------------- *)
680 (* compute the set of new prefixes
682 * "a/b/x"; (* in fact it is now a list of string so ["a";"b";"x"] *)
686 * it would give
for the first element
687 * ""; "a"; "a/b"; "a/b/x"
691 * update
: if the
include is inside a ifdef a put nothing
. cf
-test incl
.
692 * this is because we dont want code added inside ifdef
.
695 let compute_new_prefixes xs =
696 xs +> Common.map_withenv
(fun already
xs ->
697 let subdirs_prefixes = Common.inits
xs in
698 let new_first = subdirs_prefixes +> List.filter
(fun x
->
699 not
(List.mem x already
)
708 (* does via side effect on the ref in the Include in Ast_c *)
709 let rec update_include_rel_pos cs
=
710 let only_include = cs
+> Common.map_filter
(fun c
->
712 | Ast_c.CppTop
(Ast_c.Include
{Ast_c.i_include
= ((x
,_
));
714 i_is_in_ifdef
= inifdef
}) ->
716 | Ast_c.Weird _
-> None
725 let (locals
, nonlocals
) =
726 only_include +> Common.partition_either
(fun (c
, aref
) ->
728 | Ast_c.Local x
-> Left
(x
, aref
)
729 | Ast_c.NonLocal x
-> Right
(x
, aref
)
730 | Ast_c.Weird x
-> raise Impossible
733 update_rel_pos_bis locals
;
734 update_rel_pos_bis nonlocals
;
736 and update_rel_pos_bis
xs =
737 let xs'
= List.map fst
xs in
738 let the_first = compute_new_prefixes xs'
in
739 let the_last = List.rev
(compute_new_prefixes (List.rev
xs'
)) in
740 let merged = Common.zip
xs (Common.zip
the_first the_last) in
741 merged +> List.iter
(fun ((x
, aref
), (the_first, the_last)) ->
744 Ast_c.first_of
= the_first;
745 Ast_c.last_of
= the_last;
750 (*****************************************************************************)
751 (* All the information needed around the C elements and Cocci rules *)
752 (*****************************************************************************)
754 type toplevel_c_info
= {
755 ast_c
: Ast_c.toplevel
; (* contain refs so can be modified *)
756 tokens_c
: Parser_c.token list
;
759 flow
: Control_flow_c.cflow
option; (* it's the "fixed" flow *)
762 env_typing_before
: TAC.environment
;
763 env_typing_after
: TAC.environment
;
765 was_modified
: bool ref;
772 dependencies
: Ast_cocci.dependency
;
773 used_after
: Ast_cocci.meta_name list
;
775 was_matched
: bool ref;
778 type toplevel_cocci_info_script_rule
= {
781 (Ast_cocci.script_meta_name
* Ast_cocci.meta_name
*
782 Ast_cocci.metavar
) list
*
783 Ast_cocci.meta_name list
(*fresh vars*) *
787 scr_rule_info
: rule_info
;
790 type toplevel_cocci_info_cocci_rule
= {
791 ctl
: Lib_engine.ctlcocci
* (CCI.pred list list
);
792 metavars
: Ast_cocci.metavar list
;
793 ast_rule
: Ast_cocci.rule
;
794 isexp
: bool; (* true if + code is an exp, only for Flag.make_hrule *)
796 (* There are also some hardcoded rule names in parse_cocci.ml:
797 * let reserved_names = ["all";"optional_storage";"optional_qualifier"]
799 dropped_isos
: string list
;
800 free_vars
: Ast_cocci.meta_name list
;
801 negated_pos_vars
: Ast_cocci.meta_name list
;
802 positions
: Ast_cocci.meta_name list
;
804 ruletype
: Ast_cocci.ruletype
;
806 rule_info
: rule_info
;
809 type toplevel_cocci_info
=
810 ScriptRuleCocciInfo
of toplevel_cocci_info_script_rule
811 | InitialScriptRuleCocciInfo
of toplevel_cocci_info_script_rule
812 | FinalScriptRuleCocciInfo
of toplevel_cocci_info_script_rule
813 | CocciRuleCocciInfo
of toplevel_cocci_info_cocci_rule
815 type cocci_info
= toplevel_cocci_info list
* string list
option (* tokens *)
817 type kind_file
= Header
| Source
821 was_modified_once
: bool ref;
822 asts
: toplevel_c_info list
;
827 let g_contain_typedmetavar = ref false
830 let last_env_toplevel_c_info xs =
831 (Common.last
xs).env_typing_after
833 let concat_headers_and_c (ccs
: file_info list
)
834 : (toplevel_c_info
* string) list
=
835 (List.concat
(ccs
+> List.map
(fun x
->
836 x
.asts
+> List.map
(fun x'
->
839 let for_unparser xs =
840 xs +> List.map
(fun x
->
841 (x
.ast_c
, (x
.fullstring
, x
.tokens_c
)), Unparse_c.PPviastr
844 let gen_pdf_graph () =
845 (Ctl_engine.get_graph_files
()) +> List.iter
(fun outfile
->
846 Printf.printf
"Generation of %s%!" outfile
;
847 let filename_stack = Ctl_engine.get_graph_comp_files outfile
in
848 List.iter
(fun filename
->
849 ignore
(Unix.system
("dot " ^ filename ^
" -Tpdf -o " ^ filename ^
".pdf;"))
851 let (head
,tail
) = (List.hd
filename_stack, List.tl
filename_stack) in
852 ignore
(Unix.system
("cp " ^ head ^
".pdf " ^ outfile ^
".pdf;"));
853 tail
+> List.iter
(fun filename
->
854 ignore
(Unix.system
("mv " ^ outfile ^
".pdf /tmp/tmp.pdf;"));
855 ignore
(Unix.system
("pdftk " ^ filename ^
".pdf /tmp/tmp.pdf cat output " ^ outfile ^
".pdf"));
857 ignore
(Unix.system
("rm /tmp/tmp.pdf;"));
858 List.iter
(fun filename
->
859 ignore
(Unix.system
("rm " ^ filename ^
" " ^ filename ^
".pdf;"))
861 Printf.printf
" - Done\n")
863 let local_python_code =
864 "from coccinelle import *\n"
867 "import coccinelle\n"^
869 "import coccilib.org\n"^
870 "import coccilib.report\n" ^
874 let make_init lang code rule_info
=
877 scr_ast_rule
= (lang
, mv, [], code
);
879 script_code
= (if lang
= "python" then python_code else "") ^code
;
880 scr_rule_info
= rule_info
;
883 (* --------------------------------------------------------------------- *)
884 let prepare_cocci ctls free_var_lists negated_pos_lists
885 (ua
,fua
,fuas
) positions_list metavars astcocci
=
887 let gathered = Common.index_list_1
888 (zip
(zip
(zip
(zip
(zip
(zip
(zip
(zip ctls metavars
) astcocci
)
890 negated_pos_lists
) ua
) fua
) fuas
) positions_list
)
893 (fun (((((((((ctl_toplevel_list
,metavars
),ast
),free_var_list
),
894 negated_pos_list
),ua
),fua
),fuas
),positions_list
),rulenb
) ->
896 let build_rule_info rulename deps
=
897 {rulename
= rulename
;
899 used_after
= (List.hd ua
) @ (List.hd fua
);
901 was_matched
= ref false;} in
903 let is_script_rule r
=
905 Ast_cocci.ScriptRule _
906 | Ast_cocci.InitialScriptRule _
| Ast_cocci.FinalScriptRule _
-> true
909 if not
(List.length ctl_toplevel_list
=|= 1) && not
(is_script_rule ast
)
910 then failwith
"not handling multiple minirules";
913 Ast_cocci.ScriptRule
(name,lang
,deps
,mv,script_vars
,code
) ->
916 scr_ast_rule
= (lang
, mv, script_vars
, code
);
919 scr_rule_info
= build_rule_info name deps
;
921 in ScriptRuleCocciInfo
r
922 | Ast_cocci.InitialScriptRule
(name,lang
,deps
,code
) ->
923 let r = make_init lang code
(build_rule_info name deps
) in
924 InitialScriptRuleCocciInfo
r
925 | Ast_cocci.FinalScriptRule
(name,lang
,deps
,code
) ->
929 scr_ast_rule
= (lang
, mv, [], code
);
932 scr_rule_info
= build_rule_info name deps
;
934 in FinalScriptRuleCocciInfo
r
935 | Ast_cocci.CocciRule
936 (rulename
,(dependencies
,dropped_isos
,z
),restast
,isexp
,ruletype
) ->
939 ctl
= List.hd ctl_toplevel_list
;
942 isexp
= List.hd isexp
;
943 dropped_isos
= dropped_isos
;
944 free_vars
= List.hd free_var_list
;
945 negated_pos_vars
= List.hd negated_pos_list
;
946 positions
= List.hd positions_list
;
948 rule_info
= build_rule_info rulename dependencies
;
952 (* --------------------------------------------------------------------- *)
954 let build_info_program cprogram env
=
956 let (cs
, parseinfos
) =
957 Common.unzip cprogram
in
960 parseinfos
+> List.map
(fun (s,toks
) -> toks
) +> List.flatten
in
962 (* I use cs' but really annotate_xxx work by doing side effects on cs *)
964 Comment_annotater_c.annotate_program
alltoks cs in
966 Type_annoter_c.annotate_program env
(*!g_contain_typedmetavar*) cs'
969 zip
cs_with_envs parseinfos
+> List.map
(fun ((c
, (enva
,envb
)), parseinfo
)->
970 let (fullstr
, tokens) = parseinfo
in
973 ast_to_flow_with_error_messages c
+>
974 Common.map_option
(fun flow ->
975 let flow = Ast_to_flow.annotate_loop_nodes
flow in
977 (* remove the fake nodes for julia *)
978 let fixed_flow = CCI.fix_flow_ctl
flow in
980 if !Flag_cocci.show_flow
then print_flow fixed_flow;
981 if !Flag_cocci.show_before_fixed_flow
then print_flow flow;
988 ast_c
= c
; (* contain refs so can be modified *)
990 fullstring
= fullstr
;
994 contain_loop = contain_loop flow;
996 env_typing_before
= enva
;
997 env_typing_after
= envb
;
999 was_modified
= ref false;
1005 (* Optimisation. Try not unparse/reparse the whole file when have modifs *)
1006 let rebuild_info_program cs file isexp
=
1007 cs +> List.map
(fun c
->
1008 if !(c
.was_modified
)
1010 let file = Common.new_temp_file
"cocci_small_output" ".c" in
1012 [(c
.ast_c
, (c
.fullstring
, c
.tokens_c
)), Unparse_c.PPnormal
]
1015 (* Common.command2 ("cat " ^ file); *)
1016 let cprogram = cprogram_of_file file in
1017 let xs = build_info_program cprogram c
.env_typing_before
in
1019 (* TODO: assert env has not changed,
1020 * if yes then must also reparse what follows even if not modified.
1021 * Do that only if contain_typedmetavar of course, so good opti.
1023 (* Common.list_init xs *) (* get rid of the FinalDef *)
1029 let rebuild_info_c_and_headers ccs isexp
=
1030 ccs
+> List.iter
(fun c_or_h
->
1031 if c_or_h
.asts
+> List.exists
(fun c
-> !(c
.was_modified
))
1032 then c_or_h
.was_modified_once
:= true;
1034 ccs
+> List.map
(fun c_or_h
->
1037 rebuild_info_program c_or_h
.asts c_or_h
.full_fname isexp
}
1042 let prepare_c files choose_includes
: file_info list
=
1043 let cprograms = List.map
cprogram_of_file_cached files
in
1044 let includes = includes_to_parse
(zip files
cprograms) choose_includes
in
1046 (* todo?: may not be good to first have all the headers and then all the c *)
1048 (includes +> List.map
(fun hpath
-> Right hpath
))
1050 ((zip files
cprograms) +>
1051 List.map
(fun (file, asts
) -> Left
(file, asts
)))
1054 let env = ref !TAC.initial_env
in
1056 let ccs = all +> Common.map_filter
(fun x
->
1059 if not
(Common.lfile_exists hpath
)
1061 pr2
("TYPE: header " ^ hpath ^
" not found");
1065 let h_cs = cprogram_of_file_cached hpath
in
1066 let info_h_cs = build_info_program h_cs !env in
1070 else last_env_toplevel_c_info info_h_cs
1073 fname
= Common.basename hpath
;
1076 was_modified_once
= ref false;
1080 | Left
(file, cprogram) ->
1081 (* todo?: don't update env ? *)
1082 let cs = build_info_program cprogram !env in
1083 (* we do that only for the c, not for the h *)
1084 ignore
(update_include_rel_pos (cs +> List.map
(fun x
-> x
.ast_c
)));
1086 fname
= Common.basename
file;
1089 was_modified_once
= ref false;
1098 (*****************************************************************************)
1099 (* Processing the ctls and toplevel C elements *)
1100 (*****************************************************************************)
1102 (* The main algorithm =~
1103 * The algorithm is roughly:
1104 * for_all ctl rules in SP
1105 * for_all minirule in rule (no more)
1106 * for_all binding (computed during previous phase)
1107 * for_all C elements
1108 * match control flow of function vs minirule
1109 * with the binding and update the set of possible
1110 * bindings, and returned the possibly modified function.
1111 * pretty print modified C elements and reparse it.
1114 * On ne prends que les newbinding ou returned_any_state est vrai.
1115 * Si ca ne donne rien, on prends ce qu'il y avait au depart.
1116 * Mais au nouveau depart de quoi ?
1117 * - si ca donne rien apres avoir traité toutes les fonctions avec ce binding ?
1118 * - ou alors si ca donne rien, apres avoir traité toutes les fonctions
1119 * avec tous les bindings du round d'avant ?
1121 * Julia pense qu'il faut prendre la premiere solution.
1122 * Example: on a deux environnements candidats, E1 et E2 apres avoir traité
1123 * la regle ctl 1. On arrive sur la regle ctl 2.
1124 * E1 ne donne rien pour la regle 2, on garde quand meme E1 pour la regle 3.
1125 * E2 donne un match a un endroit et rend E2' alors on utilise ca pour
1128 * I have not to look at used_after_list to decide to restart from
1129 * scratch. I just need to look if the binding list is empty.
1130 * Indeed, let's suppose that a SP have 3 regions/rules. If we
1131 * don't find a match for the first region, then if this first
1132 * region does not bind metavariable used after, that is if
1133 * used_after_list is empty, then mysat(), even if does not find a
1134 * match, will return a Left, with an empty transformation_info,
1135 * and so current_binding will grow. On the contrary if the first
1136 * region must bind some metavariables used after, and that we
1137 * dont find any such region, then mysat() will returns lots of
1138 * Right, and current_binding will not grow, and so we will have
1139 * an empty list of binding, and we will catch such a case.
1141 * opti: julia says that because the binding is
1142 * determined by the used_after_list, the items in the list
1143 * are kind of sorted, so could optimise the insert_set operations.
1147 (* r(ule), c(element in C code), e(nvironment) *)
1150 let rec loop k
= function
1154 then Some
(x
, function n
-> k
(n
:: xs))
1155 else loop (function vs
-> k
(x
:: vs
)) xs in
1156 loop (function x
-> x
) l
1158 let merge_env new_e old_e
=
1161 (function (ext
,old_e
) ->
1162 function (e
,rules
) as elem
->
1163 match findk (function (e1
,_
) -> e
=*= e1
) old_e
with
1164 None
-> (elem
:: ext
,old_e
)
1165 | Some
((_
,old_rules
),k
) ->
1166 (ext
,k
(e
,Common.union_set rules old_rules
)))
1168 old_e
@ (List.rev ext
)
1170 let contains_binding e
(_
,(r,m
),_
) =
1172 let _ = List.find
(function ((re
, rm
), _) -> r =*= re
&& m
=$
= rm
) e
in
1174 with Not_found
-> false
1176 let python_application mv ve script_vars
r =
1180 ((Some x
,None
),y
,z
) -> (x
,y
,z
)
1183 (Printf.sprintf
"unexpected ast metavar in rule %s"
1184 r.scr_rule_info
.rulename
))
1187 Pycocci.build_classes
(List.map
(function (x
,y
) -> x
) ve
);
1188 Pycocci.construct_variables
mv ve
;
1189 Pycocci.construct_script_variables script_vars
;
1190 let _ = Pycocci.pyrun_simplestring
(local_python_code ^
r.script_code
) in
1191 if !Pycocci.inc_match
1192 then Some
(Pycocci.retrieve_script_variables script_vars
)
1194 with Pycocci.Pycocciexception
->
1195 (pr2
("Failure in " ^
r.scr_rule_info
.rulename
);
1196 raise
Pycocci.Pycocciexception
)
1198 let ocaml_application mv ve script_vars
r =
1201 Run_ocamlcocci.run
mv ve script_vars
1202 r.scr_rule_info
.rulename
r.script_code
in
1203 if !Coccilib.inc_match
1204 then Some
script_vals
1206 with e
-> (pr2
("Failure in " ^
r.scr_rule_info
.rulename
); raise e
)
1208 let apply_script_rule r cache newes e rules_that_have_matched
1209 rules_that_have_ever_matched script_application
=
1210 Common.profile_code
r.language
(fun () ->
1211 show_or_not_scr_rule_name r.scr_rule_info
.ruleid
;
1212 if not
(interpret_dependencies rules_that_have_matched
1213 !rules_that_have_ever_matched
r.scr_rule_info
.dependencies
)
1216 print_dependencies "dependencies for script not satisfied:"
1217 rules_that_have_matched
1218 !rules_that_have_ever_matched
r.scr_rule_info
.dependencies
;
1219 show_or_not_binding "in environment" e
;
1220 (cache
, (e
, rules_that_have_matched
)::newes
)
1224 let (_, mv, script_vars
, _) = r.scr_ast_rule
in
1226 (List.map
(function (n
,v
) -> (("virtual",n
),Ast_c.MetaIdVal
(v
,[])))
1227 !Flag.defined_virtual_env
) @ e
in
1228 let not_bound x
= not
(contains_binding ve x
) in
1229 (match List.filter
not_bound mv with
1231 let relevant_bindings =
1233 (function ((re
,rm
),_) ->
1234 List.exists
(function (_,(r,m
),_) -> r =*= re
&& m
=$
= rm
) mv)
1237 match List.assoc
relevant_bindings cache
with
1238 None
-> (cache
,newes
)
1239 | Some
script_vals ->
1241 "dependencies for script satisfied, but cached:"
1242 rules_that_have_matched
1243 !rules_that_have_ever_matched
1244 r.scr_rule_info
.dependencies
;
1245 show_or_not_binding "in" e
;
1246 (* env might be bigger than what was cached against, so have to
1247 merge with newes anyway *)
1248 let new_e = (List.combine script_vars
script_vals) @ e
in
1252 (fun (s,v
) -> List.mem
s r.scr_rule_info
.used_after
) in
1253 (cache
,merge_env [(new_e, rules_that_have_matched
)] newes
)
1256 print_dependencies "dependencies for script satisfied:"
1257 rules_that_have_matched
1258 !rules_that_have_ever_matched
1259 r.scr_rule_info
.dependencies
;
1260 show_or_not_binding "in" e
;
1261 match script_application
mv ve script_vars
r with
1263 (* failure means we should drop e, no new bindings *)
1264 (((relevant_bindings,None
) :: cache
), newes
)
1265 | Some
script_vals ->
1267 List.map
(function x
-> Ast_c.MetaIdVal
(x
,[]))
1270 (List.combine script_vars
script_vals) @ e
in
1274 (fun (s,v
) -> List.mem
s r.scr_rule_info
.used_after
) in
1275 r.scr_rule_info
.was_matched
:= true;
1276 (((relevant_bindings,Some
script_vals) :: cache
),
1279 r.scr_rule_info
.rulename
:: rules_that_have_matched
)]
1283 (if !Flag_cocci.show_dependencies
1285 let m2c (_,(r,x
),_) = r^
"."^x
in
1286 pr2
(Printf.sprintf
"script not applied: %s not bound"
1287 (String.concat
", " (List.map
m2c unbound
))));
1291 (fun (s,v
) -> List.mem
s r.scr_rule_info
.used_after
) in
1292 (cache
, merge_env [(e, rules_that_have_matched
)] newes
))
1295 let rec apply_cocci_rule r rules_that_have_ever_matched es
1296 (ccs:file_info list
ref) =
1297 Common.profile_code
r.rule_info
.rulename
(fun () ->
1298 show_or_not_rule_name r.ast_rule
r.rule_info
.ruleid
;
1299 show_or_not_ctl_text r.ctl
r.ast_rule
r.rule_info
.ruleid
;
1301 let reorganized_env =
1302 reassociate_positions
r.free_vars
r.negated_pos_vars
!es
in
1304 (* looping over the environments *)
1305 let (_,newes
(* envs for next round/rule *)) =
1307 (function (cache
,newes
) ->
1308 function ((e,rules_that_have_matched
),relevant_bindings) ->
1309 if not
(interpret_dependencies rules_that_have_matched
1310 !rules_that_have_ever_matched
1311 r.rule_info
.dependencies
)
1315 ("dependencies for rule "^
r.rule_info
.rulename^
1317 rules_that_have_matched
1318 !rules_that_have_ever_matched
r.rule_info
.dependencies
;
1319 show_or_not_binding "in environment" e;
1324 (fun (s,v
) -> List.mem
s r.rule_info
.used_after
),
1325 rules_that_have_matched
)]
1330 try List.assoc
relevant_bindings cache
1334 ("dependencies for rule "^
r.rule_info
.rulename^
1336 rules_that_have_matched
1337 !rules_that_have_ever_matched
1338 r.rule_info
.dependencies
;
1339 show_or_not_binding "in" e;
1340 show_or_not_binding "relevant in" relevant_bindings;
1342 (* applying the rule *)
1343 (match r.ruletype
with
1345 (* looping over the functions and toplevel elements in
1348 (concat_headers_and_c !ccs +>
1349 List.fold_left
(fun children_e
(c
,f) ->
1352 (* does also some side effects on c and r *)
1354 process_a_ctl_a_env_a_toplevel
r
1355 relevant_bindings c
f in
1356 match processed with
1357 | None
-> children_e
1358 | Some newbindings
->
1361 (fun children_e newbinding
->
1362 if List.mem newbinding children_e
1364 else newbinding
:: children_e
)
1368 | Ast_cocci.Generated
->
1369 process_a_generated_a_env_a_toplevel
r
1370 relevant_bindings !ccs;
1373 let old_bindings_to_keep =
1377 (fun (s,v
) -> List.mem
s r.rule_info
.used_after
)) in
1379 if null
new_bindings
1382 (*use the old bindings, specialized to the used_after_list*)
1383 if !Flag_ctl.partial_match
1386 "Empty list of bindings, I will restart from old env\n";
1387 [(old_bindings_to_keep,rules_that_have_matched
)]
1390 (* combine the new bindings with the old ones, and
1391 specialize to the used_after_list *)
1392 let old_variables = List.map fst
old_bindings_to_keep in
1393 (* have to explicitly discard the inherited variables
1394 because we want the inherited value of the positions
1395 variables not the extended one created by
1396 reassociate_positions. want to reassociate freshly
1397 according to the free variables of each rule. *)
1398 let new_bindings_to_add =
1404 (* see comment before combine_pos *)
1405 (s,Ast_c.MetaPosValList
[]) -> false
1407 List.mem
s r.rule_info
.used_after
&&
1408 not
(List.mem
s old_variables)))) in
1410 (function new_binding_to_add
->
1413 old_bindings_to_keep new_binding_to_add
),
1414 r.rule_info
.rulename
::rules_that_have_matched
))
1415 new_bindings_to_add in
1416 ((relevant_bindings,new_bindings)::cache
,
1417 merge_env new_e newes
))
1418 ([],[]) reorganized_env in (* end iter es *)
1419 if !(r.rule_info
.was_matched
)
1420 then Common.push2
r.rule_info
.rulename rules_that_have_ever_matched
;
1424 (* apply the tagged modifs and reparse *)
1425 if not
!Flag.sgrep_mode2
1426 then ccs := rebuild_info_c_and_headers !ccs r.isexp
)
1428 and reassociate_positions free_vars negated_pos_vars envs
=
1429 (* issues: isolate the bindings that are relevant to a given rule.
1430 separate out the position variables
1431 associate all of the position variables for a given set of relevant
1432 normal variable bindings with each set of relevant normal variable
1433 bindings. Goal: if eg if@p (E) matches in two places, then both inherited
1434 occurrences of E should see both bindings of p, not just its own.
1435 Otherwise, a position constraint for something that matches in two
1436 places will never be useful, because the position can always be
1437 different from the other one. *)
1441 List.filter
(function (x
,_) -> List.mem x free_vars
) e)
1443 let splitted_relevant =
1444 (* separate the relevant variables into the non-position ones and the
1449 (function (non_pos
,pos
) ->
1450 function (v
,_) as x
->
1451 if List.mem v negated_pos_vars
1452 then (non_pos
,x
::pos
)
1453 else (x
::non_pos
,pos
))
1456 let splitted_relevant =
1458 (function (non_pos
,pos
) ->
1459 (List.sort compare non_pos
,List.sort compare pos
))
1460 splitted_relevant in
1463 (function non_pos
->
1465 if List.mem np non_pos
then non_pos
else np
::non_pos
)
1466 [] splitted_relevant in
1467 let extended_relevant =
1468 (* extend the position variables with the values found at other identical
1469 variable bindings *)
1471 (function non_pos
->
1474 (function (other_non_pos
,other_pos
) ->
1475 (* do we want equal? or just somehow compatible? eg non_pos
1476 binds only E, but other_non_pos binds both E and E1 *)
1477 non_pos
=*= other_non_pos
)
1478 splitted_relevant in
1482 (combine_pos negated_pos_vars
1483 (List.map
(function (_,x
) -> x
) others)))))
1486 (List.map
(function (non_pos
,_) -> List.assoc non_pos
extended_relevant)
1489 (* If the negated posvar is not bound at all, this function will
1490 nevertheless bind it to []. If we get rid of these bindings, then the
1491 matching of the term the position variable with the constraints will fail
1492 because some variables are unbound. So we let the binding be [] and then
1493 we will have to clean these up afterwards. This should be the only way
1494 that a position variable can have an empty binding. *)
1495 and combine_pos negated_pos_vars
others =
1501 (function positions ->
1502 function other_list
->
1504 match List.assoc posvar other_list
with
1505 Ast_c.MetaPosValList l1
->
1506 Common.union_set l1
positions
1507 | _ -> failwith
"bad value for a position variable"
1508 with Not_found
-> positions)
1510 (posvar
,Ast_c.MetaPosValList
positions))
1513 and process_a_generated_a_env_a_toplevel2
r env = function
1518 (rule
,_) when rule
=$
= r.rule_info
.rulename
-> false
1519 | (_,"ARGS") -> false
1522 let env_domain = List.map
(function (nm
,vl
) -> nm
) env in
1526 let (rl
,_) = Ast_cocci.get_meta_name md
in rl
=$
= r.rule_info
.rulename
)
1528 if Common.include_set
free_vars env_domain
1529 then Unparse_hrule.pp_rule
metavars r.ast_rule
env cfile
.full_fname
1530 | _ -> failwith
"multiple files not supported"
1532 and process_a_generated_a_env_a_toplevel rule
env ccs =
1533 Common.profile_code
"process_a_ctl_a_env_a_toplevel"
1534 (fun () -> process_a_generated_a_env_a_toplevel2 rule
env ccs)
1536 (* does side effects on C ast and on Cocci info rule *)
1537 and process_a_ctl_a_env_a_toplevel2
r e c
f =
1538 indent_do
(fun () ->
1539 show_or_not_celem "trying" c
.ast_c
;
1540 Flag.currentfile
:= Some
(f ^
":" ^
get_celem c
.ast_c
);
1541 let (trans_info, returned_any_states
, inherited_bindings
, newbindings
) =
1542 Common.save_excursion
Flag_ctl.loop_in_src_code
(fun () ->
1543 Flag_ctl.loop_in_src_code
:= !Flag_ctl.loop_in_src_code
||c
.contain_loop;
1545 (***************************************)
1546 (* !Main point! The call to the engine *)
1547 (***************************************)
1548 let model_ctl = CCI.model_for_ctl
r.dropped_isos
(Common.some c
.flow) e
1549 in CCI.mysat
model_ctl r.ctl
(r.rule_info
.used_after
, e)
1552 if not returned_any_states
1555 show_or_not_celem "found match in" c
.ast_c
;
1556 show_or_not_trans_info trans_info;
1557 List.iter
(show_or_not_binding "out") newbindings
;
1559 r.rule_info
.was_matched
:= true;
1561 if not
(null
trans_info) &&
1562 not
(!Flag.sgrep_mode2
&& not
!Flag_cocci.show_diff
)
1564 c
.was_modified
:= true;
1566 (* les "more than one var in a decl" et "already tagged token"
1567 * font crasher coccinelle. Si on a 5 fichiers, donc on a 5
1568 * failed. Le try limite le scope des crashes pendant la
1569 * trasformation au fichier concerne. *)
1571 (* modify ast via side effect *)
1572 ignore
(Transformation_c.transform
r.rule_info
.rulename
r.dropped_isos
1573 inherited_bindings
trans_info (Common.some c
.flow));
1574 with Timeout
-> raise Timeout
| UnixExit i
-> raise
(UnixExit i
)
1577 Some
(List.map
(function x
-> x
@inherited_bindings
) newbindings
)
1581 and process_a_ctl_a_env_a_toplevel a b c
f=
1582 Common.profile_code
"process_a_ctl_a_env_a_toplevel"
1583 (fun () -> process_a_ctl_a_env_a_toplevel2 a b c
f)
1586 let rec bigloop2 rs
(ccs: file_info list
) =
1587 let init_es = [(Ast_c.emptyMetavarsBinding
,[])] in
1588 let es = ref init_es in
1589 let ccs = ref ccs in
1590 let rules_that_have_ever_matched = ref [] in
1592 (* looping over the rules *)
1593 rs
+> List.iter
(fun r ->
1595 InitialScriptRuleCocciInfo
r | FinalScriptRuleCocciInfo
r -> ()
1596 | ScriptRuleCocciInfo
r ->
1597 if !Flag_cocci.show_ctl_text
then begin
1598 Common.pr_xxxxxxxxxxxxxxxxx
();
1599 pr
("script: " ^
r.language
);
1600 Common.pr_xxxxxxxxxxxxxxxxx
();
1602 adjust_pp_with_indent
(fun () ->
1603 Format.force_newline
();
1604 let (l,mv,script_vars
,code
) = r.scr_ast_rule
in
1605 let nm = r.scr_rule_info
.rulename
in
1606 let deps = r.scr_rule_info
.dependencies
in
1607 Pretty_print_cocci.unparse
1608 (Ast_cocci.ScriptRule
(nm,l,deps,mv,script_vars
,code
)));
1611 if !Flag.show_misc
then print_endline
"RESULT =";
1615 (function (cache
, newes
) ->
1616 function (e, rules_that_have_matched
) ->
1617 match r.language
with
1619 apply_script_rule r cache newes
e rules_that_have_matched
1620 rules_that_have_ever_matched python_application
1622 apply_script_rule r cache newes
e rules_that_have_matched
1623 rules_that_have_ever_matched ocaml_application
1625 concat_headers_and_c !ccs +> List.iter
(fun (c
,_) ->
1628 Printf.printf
"Flow: %s\r\nFlow!\r\n%!" c
.fullstring
);
1631 Printf.printf
"Unknown language: %s\n" r.language
;
1635 (if !(r.scr_rule_info
.was_matched
)
1637 Common.push2
r.scr_rule_info
.rulename
rules_that_have_ever_matched);
1639 es := newes
(*(if newes = [] then init_es else newes)*);
1640 | CocciRuleCocciInfo
r ->
1641 apply_cocci_rule r rules_that_have_ever_matched
1644 if !Flag.sgrep_mode2
1646 (* sgrep can lead to code that is not parsable, but we must
1647 * still call rebuild_info_c_and_headers to pretty print the
1648 * action (MINUS), so that later the diff will show what was
1649 * matched by sgrep. But we don't want the parsing error message
1650 * hence the following flag setting. So this code propably
1651 * will generate a NotParsedCorrectly for the matched parts
1652 * and the very final pretty print and diff will work
1654 Flag_parsing_c.verbose_parsing
:= false;
1655 ccs := rebuild_info_c_and_headers !ccs false
1657 !ccs (* return final C asts *)
1660 Common.profile_code
"bigloop" (fun () -> bigloop2 a b
)
1662 type init_final
= Initial
| Final
1664 let initial_final_bigloop2 ty rebuild
r =
1665 if !Flag_cocci.show_ctl_text
then
1667 Common.pr_xxxxxxxxxxxxxxxxx
();
1668 pr
((match ty
with Initial
-> "initial" | Final
-> "final") ^
": " ^
1670 Common.pr_xxxxxxxxxxxxxxxxx
();
1672 adjust_pp_with_indent
(fun () ->
1673 Format.force_newline
();
1674 Pretty_print_cocci.unparse
(rebuild
r.scr_ast_rule
r.scr_rule_info
.dependencies
));
1677 match r.language
with
1679 (* include_match makes no sense in an initial or final rule, although
1680 we have no way to prevent it *)
1681 let _ = apply_script_rule r [] [] [] [] (ref []) python_application in
1683 | "ocaml" when ty
= Initial
-> () (* nothing to do *)
1685 (* include_match makes no sense in an initial or final rule, although
1686 we have no way to prevent it *)
1687 let _ = apply_script_rule r [] [] [] [] (ref []) ocaml_application in
1690 failwith
("Unknown language for initial/final script: "^
1693 let initial_final_bigloop a b c
=
1694 Common.profile_code
"initial_final_bigloop"
1695 (fun () -> initial_final_bigloop2 a b c
)
1697 (*****************************************************************************)
1698 (* The main functions *)
1699 (*****************************************************************************)
1701 let pre_engine2 (coccifile
, isofile
) =
1702 show_or_not_cocci coccifile isofile
;
1703 Pycocci.set_coccifile coccifile
;
1706 if not
(Common.lfile_exists
isofile)
1708 pr2
("warning: Can't find default iso file: " ^
isofile);
1711 else Some
isofile in
1713 (* useful opti when use -dir *)
1714 let (metavars,astcocci
,
1715 free_var_lists
,negated_pos_lists
,used_after_lists
,
1716 positions_lists
,toks
,_) =
1717 sp_of_file coccifile
isofile in
1718 let ctls = ctls_of_ast astcocci used_after_lists positions_lists
in
1720 g_contain_typedmetavar := sp_contain_typed_metavar astcocci
;
1722 check_macro_in_sp_and_adjust toks
;
1724 show_or_not_ctl_tex astcocci
ctls;
1727 prepare_cocci ctls free_var_lists negated_pos_lists
1728 used_after_lists positions_lists
metavars astcocci
in
1730 let used_languages =
1732 (function languages
->
1734 ScriptRuleCocciInfo
(r) ->
1735 if List.mem
r.language languages
then
1738 r.language
::languages
1742 let initialized_languages =
1744 (function languages
->
1746 InitialScriptRuleCocciInfo
(r) ->
1747 (if List.mem
r.language languages
1750 ("double initializer found for "^
r.language
));
1751 if interpret_dependencies [] [] r.scr_rule_info
.dependencies
1754 initial_final_bigloop Initial
1755 (fun (x
,_,_,y
) -> fun deps ->
1756 Ast_cocci.InitialScriptRule
(r.scr_rule_info
.rulename
,x
,deps,y
))
1758 r.language
::languages
1764 let uninitialized_languages =
1766 (fun used
-> not
(List.mem used
initialized_languages))
1772 dependencies
= Ast_cocci.NoDep
;
1775 was_matched
= ref false;} in
1776 initial_final_bigloop Initial
1777 (fun (x
,_,_,y
) -> fun deps ->
1778 Ast_cocci.InitialScriptRule
("",x
,deps,y
))
1779 (make_init lgg
"" rule_info))
1780 uninitialized_languages;
1785 Common.profile_code
"pre_engine" (fun () -> pre_engine2 a
)
1787 let full_engine2 (cocci_infos,toks
) cfiles
=
1789 show_or_not_cfiles cfiles
;
1791 (* optimisation allowing to launch coccinelle on all the drivers *)
1792 if !Flag_cocci.worth_trying_opt
&& not
(worth_trying cfiles toks
)
1798 pr2
("No matches found for " ^
(Common.join
" " toks
)
1799 ^
"\nSkipping:" ^
(Common.join
" " cfiles
)));
1800 cfiles
+> List.map
(fun s -> s, None
)
1805 if !Flag.show_misc
then Common.pr_xxxxxxxxxxxxxxxxx
();
1806 if !Flag.show_misc
then pr
"let's go";
1807 if !Flag.show_misc
then Common.pr_xxxxxxxxxxxxxxxxx
();
1809 let choose_includes =
1810 match !Flag_cocci.include_options
with
1811 Flag_cocci.I_UNSPECIFIED
->
1812 if !g_contain_typedmetavar
1813 then Flag_cocci.I_NORMAL_INCLUDES
1814 else Flag_cocci.I_NO_INCLUDES
1816 let c_infos = prepare_c cfiles
choose_includes in
1818 (* ! the big loop ! *)
1819 let c_infos'
= bigloop cocci_infos c_infos in
1821 if !Flag.show_misc
then Common.pr_xxxxxxxxxxxxxxxxx
();
1822 if !Flag.show_misc
then pr
"Finished";
1823 if !Flag.show_misc
then Common.pr_xxxxxxxxxxxxxxxxx
();
1824 if !Flag_ctl.graphical_trace
then gen_pdf_graph ();
1826 c_infos'
+> List.map
(fun c_or_h
->
1827 if !(c_or_h
.was_modified_once
)
1831 Common.new_temp_file
"cocci-output" ("-" ^ c_or_h
.fname
) in
1833 if c_or_h
.fkind
=*= Header
1834 then pr2
("a header file was modified: " ^ c_or_h
.fname
);
1836 (* and now unparse everything *)
1837 cfile_of_program (for_unparser c_or_h
.asts
) outfile;
1839 show_or_not_diff c_or_h
.fpath
outfile;
1842 if !Flag.sgrep_mode2
then None
else Some
outfile)
1844 else (c_or_h
.fpath
, None
))
1847 let full_engine a b
=
1848 Common.profile_code
"full_engine"
1849 (fun () -> let res = full_engine2 a b
in (*Gc.print_stat stderr; *)res)
1851 let post_engine2 (cocci_infos,_) =
1854 (function languages
->
1856 FinalScriptRuleCocciInfo
(r) ->
1857 (if List.mem
r.language languages
1858 then failwith
("double finalizer found for "^
r.language
));
1859 initial_final_bigloop Final
1860 (fun (x
,_,_,y
) -> fun deps ->
1861 Ast_cocci.FinalScriptRule
(r.scr_rule_info
.rulename
,x
,deps,y
))
1863 r.language
::languages
1869 Common.profile_code
"post_engine" (fun () -> post_engine2 a
)
1871 (*****************************************************************************)
1872 (* check duplicate from result of full_engine *)
1873 (*****************************************************************************)
1875 let check_duplicate_modif2 xs =
1876 (* opti: let groups = Common.groupBy (fun (a,resa) (b,resb) -> a =$= b) xs *)
1877 if !Flag_cocci.verbose_cocci
1878 then pr2
("Check duplication for " ^ i_to_s
(List.length
xs) ^
" files");
1880 let groups = Common.group_assoc_bykey_eff
xs in
1881 groups +> Common.map_filter
(fun (file, xs) ->
1883 | [] -> raise Impossible
1884 | [res] -> Some
(file, res)
1888 if not
(List.for_all
(fun res2
-> res2
=*= None
) xs)
1890 pr2
("different modification result for " ^
file);
1893 else Some
(file, None
)
1895 if not
(List.for_all
(fun res2
->
1899 let diff = Common.cmd_to_list
("diff -u -b -B "^
res^
" "^res2
)
1903 pr2
("different modification result for " ^
file);
1906 else Some
(file, Some
res)
1908 let check_duplicate_modif a
=
1909 Common.profile_code
"check_duplicate" (fun () -> check_duplicate_modif2 a
)