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.
26 module FC
= Flag_cocci
28 (*****************************************************************************)
30 (*****************************************************************************)
32 (* In addition to flags that can be tweaked via -xxx options (cf the
33 * full list of options in "the spatch options" section below), the
34 * spatch program also depends on external files, described in
35 * globals/config.ml, mainly a standard.h and standard.iso file *)
37 let cocci_file = ref ""
39 let output_file = ref ""
40 let inplace_modif = ref false (* but keeps nothing *)
42 ref (None
: string option) (* suffix for backup if one is desired *)
43 let outplace_modif = ref false (* generates a .cocci_res *)
44 let preprocess = ref false (* run the C preprocessor before cocci *)
45 let compat_mode = ref false
46 let ignore_unknown_opt = ref false
48 (* somehow obsolete now *)
51 let include_headers = ref false
52 let kbuild_info = ref ""
54 let macro_file = ref ""
57 let test_mode = ref false
58 let test_all = ref false
59 let test_okfailed = ref false
60 let test_regression_okfailed = ref false
61 let expected_score_file = ref ""
67 (* works with -test but also in "normal" spatch mode *)
68 let compare_with_expected = ref false
70 let distrib_index = ref (None
: int option)
71 let distrib_max = ref (None
: int option)
72 let mod_distrib = ref false
74 (*****************************************************************************)
76 (*****************************************************************************)
78 (* pair of (list of flags to set true, list of flags to set false *)
79 let very_quiet_profile = (
83 (* FC.show_diff; just leave this as it is *)
85 Common.print_to_stderr
;
93 FC.show_before_fixed_flow
;
96 FC.show_binding_in_out
;
100 Flag_parsing_c.show_parsing_error
;
102 Flag_parsing_c.verbose_lexing
;
103 Flag_parsing_c.verbose_parsing
;
104 Flag_parsing_c.verbose_type
;
105 Flag_parsing_c.verbose_cfg
;
106 Flag_parsing_c.verbose_unparsing
;
107 Flag_parsing_c.verbose_visit
;
108 Flag_parsing_c.verbose_cpp_ast
;
110 Flag_matcher.verbose_matcher
;
111 Flag_matcher.debug_engine
;
113 Flag_parsing_c.debug_unparsing
;
115 Flag_parsing_cocci.show_SP
;
116 Flag_parsing_cocci.show_iso_failures
;
118 Flag_ctl.verbose_ctl_engine
;
119 Flag_ctl.verbose_match
;
124 let quiet_profile = (
126 Common.print_to_stderr
129 (* FC.show_diff; just leave this as it is *)
138 FC.show_before_fixed_flow
;
141 FC.show_binding_in_out
;
145 Flag_parsing_c.show_parsing_error
;
147 Flag_parsing_c.verbose_lexing
;
148 Flag_parsing_c.verbose_parsing
;
149 Flag_parsing_c.verbose_type
;
150 Flag_parsing_c.verbose_cfg
;
151 Flag_parsing_c.verbose_unparsing
;
152 Flag_parsing_c.verbose_visit
;
153 Flag_parsing_c.verbose_cpp_ast
;
155 Flag_matcher.verbose_matcher
;
156 Flag_matcher.debug_engine
;
158 Flag_parsing_c.debug_unparsing
;
160 Flag_parsing_cocci.show_SP
;
161 Flag_parsing_cocci.show_iso_failures
;
163 Flag_ctl.verbose_ctl_engine
;
164 Flag_ctl.verbose_match
;
169 (* some information that is useful in seeing why a semantic patch doesn't
171 let debug_profile = (
173 Common.print_to_stderr
;
179 FC.show_binding_in_out
;
180 FC.show_dependencies
;
182 Flag_parsing_cocci.keep_ml_script
;
183 Flag_parsing_cocci.show_iso_failures
;
187 Flag_parsing_c.verbose_cfg
;
188 Flag_parsing_c.verbose_unparsing
;
189 Flag_parsing_c.verbose_visit
;
191 Flag_matcher.verbose_matcher
;
193 Flag_parsing_c.show_parsing_error
;
201 FC.show_before_fixed_flow
;
205 Flag_parsing_cocci.show_SP
;
206 Flag_ctl.verbose_ctl_engine
;
207 Flag_ctl.verbose_match
;
208 Flag_matcher.debug_engine
;
209 Flag_parsing_c.debug_unparsing
;
210 Flag_parsing_c.verbose_type
;
211 Flag_parsing_c.verbose_parsing
;
217 Common.print_to_stderr
;
227 FC.show_before_fixed_flow
;
230 FC.show_binding_in_out
;
232 Flag_parsing_cocci.show_SP
;
233 Flag_parsing_cocci.show_iso_failures
;
234 Flag_ctl.verbose_ctl_engine
;
235 Flag_ctl.verbose_match
;
236 Flag_matcher.debug_engine
;
237 Flag_parsing_c.debug_unparsing
;
238 Flag_parsing_c.verbose_type
;
239 Flag_parsing_c.verbose_parsing
;
243 let (set_to_true
, set_to_false
) = p
in
244 List.iter
(fun x
-> x
:= false) set_to_false
;
245 List.iter
(fun x
-> x
:= true) set_to_true
247 (*****************************************************************************)
248 (* The spatch options *)
249 (*****************************************************************************)
252 "Usage: " ^ basename
Sys.argv
.(0) ^
253 " -sp_file <SP> <infile> [-o <outfile>] [-iso_file <iso>] [options]" ^
254 "\n" ^
"Options are:"
256 (* forward reference trick *)
257 let short_usage_func = ref (fun () -> ())
258 let long_usage_func = ref (fun () -> ())
261 (* The short_options are user-oriented. The other options are for
262 * the developers of coccinelle or advanced-users that know
263 * quite well the underlying semantics of coccinelle.
267 (* will be printed when use only ./spatch. For the rest you have to
268 * use -longhelp to see them.
270 let short_options = [
271 "-sp_file", Arg.Set_string
cocci_file,
272 " <file> the semantic patch file";
274 "-o", Arg.Set_string
output_file,
275 " <file> the output file";
276 "-in_place", Arg.Set
inplace_modif,
277 " do the modification on the file directly";
278 "-backup_suffix", Arg.String
(function s
-> backup_suffix := Some s
),
279 " suffix to use when making a backup for inplace";
280 "-out_place", Arg.Set
outplace_modif,
281 " store modifications in a .cocci_res file";
283 "-U", Arg.Int
(fun n
-> Flag_parsing_c.diff_lines
:= Some
(i_to_s n
)),
284 " set number of diff context lines";
285 "-partial_match", Arg.Set
Flag_ctl.partial_match
,
286 " report partial matches of the SP on the C file";
288 "-iso_file", Arg.Set_string
Config.std_iso
,
289 " <file> (default=" ^
!Config.std_iso ^
")";
290 "-macro_file", Arg.Set_string
macro_file,
292 "-macro_file_builtins", Arg.Set_string
Config.std_h
,
293 " <file> (default=" ^
!Config.std_h ^
")";
295 "-recursive_includes",
296 Arg.Unit
(function _
-> FC.include_options
:= FC.I_REALLY_ALL_INCLUDES
),
297 " causes all available include files, both those included in the C file(s) and those included in header files, to be used";
299 Arg.Unit
(function _
-> FC.include_options
:= FC.I_ALL_INCLUDES
),
300 " causes all available include files included in the C file(s) to be used";
302 Arg.Unit
(function _
-> FC.include_options
:= FC.I_NO_INCLUDES
),
303 " causes not even local include files to be used";
305 Arg.Unit
(function _
-> FC.include_options
:= FC.I_NORMAL_INCLUDES
),
306 " causes local include files to be used";
307 "-ignore_unknown_options", Arg.Set
ignore_unknown_opt,
308 " For integration in a toolchain (must be set before the first unknown option)";
309 "-include_headers", Arg.Set
include_headers,
310 " process header files independently";
311 "-I", Arg.String
(fun x
->
312 FC.include_path
:= x
::!FC.include_path
314 " <dir> containing the header files (optional)";
316 "-preprocess", Arg.Set
preprocess,
317 " run the C preprocessor before applying the semantic match";
319 "-c", Arg.Set
compat_mode, " gcc/cpp compatibility mode";
322 " <dir> process all files in directory recursively";
324 "-use_glimpse", Arg.Unit
(function _
-> Flag.scanner
:= Flag.Glimpse
),
325 " works with -dir, use info generated by glimpseindex";
326 "-use_google", Arg.String
(function s
-> Flag.scanner
:= Flag.Google s
),
327 " find relevant files using google code search";
328 "-use_idutils", Arg.Unit
(function s
-> Flag.scanner
:= Flag.IdUtils
),
329 " find relevant files using id-utils";
331 Arg.String
(function s
-> Flag.patch
:= Some
(Cocci.normalize_path s
)),
332 (" <dir> path name with respect to which a patch should be created\n"^
333 " \"\" for a file in the current directory");
334 "-kbuild_info", Arg.Set_string
kbuild_info,
335 " <file> improve -dir by grouping related c files";
336 "-pyoutput", Arg.Set_string
Flag.pyoutput
,
337 " Sets output routine: Standard values: <coccilib.output.Gtk|coccilib.output.Console>";
340 "-version", Arg.Unit
(fun () ->
341 let withpython = if Pycocci.python_support
then "with" else "without" in
343 if !Regexp.pcre_support
then "with PCRE support"
344 else "with Str regexp support "
346 pr2
(spf
"spatch version %s %s Python support and %s" Config.version
withpython whichregexp);
351 "-date", Arg.Unit
(fun () ->
352 pr2
"version: $Date$";
353 raise
(Common.UnixExit
0)
357 "-shorthelp", Arg.Unit
(fun () ->
359 raise
(Common.UnixExit
0)
361 " see short list of options";
362 "-longhelp", Arg.Unit
(fun () ->
364 raise
(Common.UnixExit
0)
366 " see all the available options in different categories";
367 "-help", Arg.Unit
(fun () ->
369 raise
(Common.UnixExit
0)
372 "--help", Arg.Unit
(fun () ->
374 raise
(Common.UnixExit
0)
379 (* the format is a list of triples:
380 * (title of section * (optional) explanation of sections * option list)
382 let other_options = [
383 "aliases and obsolete options",
386 "-sp", Arg.Set_string
cocci_file, " short option of -sp_file";
387 "-iso", Arg.Set_string
Config.std_iso
, " short option of -iso_file";
389 "-cocci_file", Arg.Set_string
cocci_file,
390 " <file> the semantic patch file";
391 (* "-c", Arg.Set_string cocci_file, " short option of -sp_file"; *)
394 "most useful show options",
397 "-show_diff" , Arg.Set
FC.show_diff
, " ";
398 "-no_show_diff" , Arg.Clear
FC.show_diff
, " ";
399 "-force_diff" , Arg.Set
FC.force_diff
,
400 "show diff even if only spacing changes";
401 "-show_flow" , Arg.Set
FC.show_flow
, " ";
402 (* works in conjunction with -show_ctl_text *)
405 (function _
-> FC.show_ctl_text
:= true; FC.inline_let_ctl
:= true), " ";
406 "-ctl_show_mcodekind",
408 (function _
-> FC.show_ctl_text
:= true; FC.show_mcodekind_in_ctl
:= true),
410 "-show_bindings", Arg.Set
FC.show_binding_in_out
, " ";
411 "-show_transinfo", Arg.Set
Flag.show_transinfo
, " ";
412 "-show_misc", Arg.Set
Flag.show_misc
, " ";
413 "-show_trying", Arg.Set
Flag.show_trying
,
414 " show the name of each function being processed";
415 "-show_dependencies",
416 Arg.Unit
(function _
-> FC.show_dependencies
:= true;
417 FC.show_binding_in_out
:= true),
418 " show the dependencies related to each rule";
421 "verbose subsystems options",
424 "-verbose_ctl_engine",
425 Arg.Unit
(function _
->
426 Flag_ctl.verbose_ctl_engine
:= true; FC.show_ctl_text
:= true) , " ";
427 "-verbose_match", Arg.Set
Flag_ctl.verbose_match
, " ";
428 "-verbose_engine", Arg.Set
Flag_matcher.debug_engine
, " ";
429 "-graphical_trace", Arg.Set
Flag_ctl.graphical_trace
, " generate a pdf file representing the matching process";
431 Arg.Unit
(function _
->
432 Flag_ctl.graphical_trace
:= true; Flag_ctl.gt_without_label
:= true),
433 " remove graph label (requires option -graphical_trace)";
435 "-parse_error_msg", Arg.Set
Flag_parsing_c.show_parsing_error
, " ";
437 Arg.Unit
(fun _
-> Flag_parsing_c.verbose_parsing
:= true;
438 Flag_parsing_c.show_parsing_error
:= true), " ";
439 "-type_error_msg", Arg.Set
Flag_parsing_c.verbose_type
, " ";
440 (* could also use Flag_parsing_c.options_verbose *)
443 "other show options",
446 "-show_c" , Arg.Set
FC.show_c
, " ";
447 "-show_cocci" , Arg.Set
FC.show_cocci
, " ";
448 "-show_before_fixed_flow" , Arg.Set
FC.show_before_fixed_flow
, " ";
449 "-show_ctl_tex" , Arg.Set
FC.show_ctl_tex
, " ";
450 "-show_ctl_text" , Arg.Set
FC.show_ctl_text
, " ";
451 "-show_SP" , Arg.Set
Flag_parsing_cocci.show_SP
, " ";
455 "debug C parsing/unparsing",
458 "-debug_cpp", Arg.Set
Flag_parsing_c.debug_cpp
, " ";
459 "-debug_lexer", Arg.Set
Flag_parsing_c.debug_lexer
, " ";
460 "-debug_etdt", Arg.Set
Flag_parsing_c.debug_etdt
, " ";
461 "-debug_typedef", Arg.Set
Flag_parsing_c.debug_typedef
, " ";
463 "-filter_msg", Arg.Set
Flag_parsing_c.filter_msg
,
464 " filter some cpp message when the macro is a \"known\" cpp construct";
465 "-filter_define_error", Arg.Set
Flag_parsing_c.filter_define_error
," ";
466 "-filter_msg_define_error", Arg.Set
Flag_parsing_c.filter_msg_define_error
,
467 " filter the error msg";
468 "-filter_passed_level", Arg.Set_int
Flag_parsing_c.filter_passed_level
," ";
469 (* debug cfg doesn't seem to have any effect, so drop it as an option *)
470 (* "-debug_cfg", Arg.Set Flag_parsing_c.debug_cfg , " "; *)
471 "-debug_unparsing", Arg.Set
Flag_parsing_c.debug_unparsing
, " ";
474 (* could use Flag_parsing_c.options_debug_with_title instead *)
477 "shortcut for enabling/disabling a set of debugging options at once",
480 (* todo: other profile ? *)
481 "-quiet", Arg.Unit
(fun () -> run_profile quiet_profile), " ";
482 "-very_quiet", Arg.Unit
(fun () -> run_profile very_quiet_profile), " ";
483 "-debug", Arg.Unit
(fun () -> run_profile debug_profile), " ";
484 "-pad", Arg.Unit
(fun () -> run_profile pad_profile), " ";
491 "-profile", Arg.Unit
(function () -> Common.profile
:= Common.PALL
) ,
492 " gather timing information about the main coccinelle functions";
493 "-bench", Arg.Int
(function x
-> Flag_ctl.bench
:= x
),
494 " <level> for profiling the CTL engine";
495 "-timeout", Arg.Int
(fun x
-> FC.timeout
:= Some x
),
496 " <sec> timeout in seconds";
497 "-steps", Arg.Int
(fun x
-> Flag_ctl.steps
:= Some x
),
498 " max number of model checking steps per code unit";
499 "-iso_limit", Arg.Int
(fun x
-> Flag_parsing_cocci.iso_limit
:= Some x
),
500 " max depth of iso application";
501 "-no_iso_limit", Arg.Unit
(fun _
-> Flag_parsing_cocci.iso_limit
:= None
),
502 " disable limit on max depth of iso application";
503 "-track_iso", Arg.Set
Flag.track_iso_usage
,
504 " gather information about isomorphism usage";
507 (fun s
-> Flag_parsing_cocci.disabled_isos
:=
508 s
:: !Flag_parsing_cocci.disabled_isos
),
509 " disable a specific isomorphism";
514 (*post_engine not included, because it doesn't use isos*)
515 PSOME
["parse cocci";"mysat";"asttoctl2";"pre_engine";"full_engine"]),
516 " gather information about the cost of isomorphism usage"
521 "change of algorithm options",
524 "-popl", Arg.Set
FC.popl
,
525 " simplified SmPL, for the popl paper";
529 (function _
-> FC.popl
:= true; Flag_popl.mark_all
:= true),
530 " simplified SmPL, for the popl paper";
532 "-popl_keep_all_wits",
534 (function _
-> FC.popl
:= true; Flag_popl.keep_all_wits
:= true),
535 " simplified SmPL, for the popl paper";
539 Flag.make_hrule
:= Some s
; FC.include_options
:= FC.I_NO_INCLUDES
),
540 " semantic patch generation";
542 "-keep_comments", Arg.Set
Flag_parsing_c.keep_comments
,
543 " keep comments around removed code";
545 "-loop", Arg.Set
Flag_ctl.loop_in_src_code
, " ";
546 "-no_loops", Arg.Set
Flag_parsing_c.no_loops
,
547 " drop all back edges derived from looping constructs - unsafe";
548 "-no_gotos", Arg.Set
Flag_parsing_c.no_gotos
,
549 " drop all jumps derived from gotos - unsafe";
550 "-no_saved_typedefs", Arg.Clear
Flag_cocci.use_saved_typedefs
,
551 " drop all inferred typedefs from one parse of some code to the next";
553 "-ocaml_regexps", Arg.Clear
Regexp.pcre_support
,
554 " use OCaml Str regular expressions for constraints";
556 "-l1", Arg.Clear
Flag_parsing_c.label_strategy_2
, " ";
557 "-ifdef_to_if", Arg.Set
FC.ifdef_to_if
,
558 " convert ifdef to if (experimental)";
559 "-no_ifdef_to_if", Arg.Clear
FC.ifdef_to_if
,
560 " convert ifdef to if (experimental)";
562 "-disable_multi_pass", Arg.Set
Flag_parsing_c.disable_multi_pass
, " ";
564 "-noif0_passing", Arg.Clear
Flag_parsing_c.if0_passing
,
566 "-noadd_typedef_root", Arg.Clear
Flag_parsing_c.add_typedef_root
, " ";
567 (* could use Flag_parsing_c.options_algo instead *)
570 "-disallow_nested_exps", Arg.Set
Flag_matcher.disallow_nested_exps
,
571 " disallow an expresion pattern from matching a term and its subterm";
572 "-disable_worth_trying_opt", Arg.Clear
FC.worth_trying_opt
,
574 "-only_return_is_error_exit",
575 Arg.Set
Flag_matcher.only_return_is_error_exit
,
576 "if this flag is not set, then break and continue are also error exits";
577 (* the following is a hack to make it easier to add code in sgrep-like
578 code, essentially to compensate for the fact that we don't have
579 any way of printing things out *)
580 "-allow_inconsistent_paths",
581 Arg.Set
Flag_matcher.allow_inconsistent_paths
,
582 " if this flag is set don't check for inconsistent paths; dangerous";
583 "-no_safe_expressions",
584 Arg.Set
Flag_matcher.no_safe_expressions
,
585 " make an expression disjunction not prioritise the topmost disjunct";
586 "-int_bits", Arg.Int
Flag_parsing_c.set_int_bits
,
587 " the number of bits in an unsigned int";
588 "-long_bits", Arg.Int
Flag_parsing_c.set_long_bits
,
589 " the number of bits in an unsigned long";
590 "-linux_spacing", Arg.Unit
Flag_parsing_c.set_linux_spacing
,
591 " spacing of + code follows the conventions of Linux";
592 "-smpl_spacing", Arg.Unit
Flag_parsing_c.set_smpl_spacing
,
593 " spacing of + code follows the semantic patch";
594 "-D", Arg.String
Flag.set_defined_virtual_rules
,
595 " indicate that a virtual rule should be considered to be matched";
596 "-c++", Arg.Set
Flag.c_plus_plus
,
597 " make a small attempt to parse C++ files"
603 "-debugger", Arg.Set
Common.debugger
,
604 " option to set if launch spatch in ocamldebug";
605 "-disable_once", Arg.Set
Common.disable_pr2_once
,
606 " to print more messages";
607 "-show_trace_profile", Arg.Set
Common.show_trace_profile
,
609 "-save_tmp_files", Arg.Set
Common.save_tmp_files
, " ";
615 "-index", Arg.Int
(function x
-> distrib_index := Some x
) ,
616 " the processor to use for this run of spatch";
617 "-max", Arg.Int
(function x
-> distrib_max := Some x
) ,
618 " the number of processors available";
619 "-mod_distrib", Arg.Set
mod_distrib,
620 " use mod to distribute files among the processors";
626 "-use_cache", Arg.Set
Flag_parsing_c.use_cache
,
627 " use .ast_raw pre-parsed cached C file";
629 Arg.String
(function s
->
630 Flag_parsing_c.cache_prefix
:= Some s
;
631 Flag_parsing_c.use_cache
:= true),
632 " directory of cached ASTs, sets -use_cache";
633 (* could use Flag_parsing_c.options_pad instead *)
635 Arg.Int
(function n
->
636 Flag_parsing_c.cache_limit
:= Some n
),
637 " maximum number of cached ASTs, sets -use_cache";
642 "test mode and test options (works with tests/ or .ok files)",
643 "The test options don't work with the -sp_file and so on.",
645 "-test", Arg.Set
test_mode,
646 " <file> launch spatch on tests/file.[c,cocci]";
647 "-testall", Arg.Set
test_all,
648 " launch spatch on all files in tests/ having a .res";
649 "-test_okfailed", Arg.Set
test_okfailed,
650 " generates .{ok,failed,spatch_ok} files using .res files";
651 "-test_regression_okfailed", Arg.Set
test_regression_okfailed,
652 " process the .{ok,failed,spatch_ok} files in current dir";
654 "-compare_with_expected", Arg.Set
compare_with_expected,
655 " use also file.res";
656 "-expected_score_file", Arg.Set_string
expected_score_file,
657 " which score file to compare with in -testall";
658 "-relax_include_path", Arg.Set
FC.relax_include_path
,
663 ("The action options don't work with the -sp_file and so on." ^
"\n" ^
664 "It's for the other (internal) uses of the spatch program."
667 (* -token_c, -parse_c, etc *)
668 ((Common.options_of_actions
action (Test_parsing_c.actions
())) ++
670 (let s = "-parse_cocci" in s, Arg.Unit
(fun () -> action := s),
672 (let s = "-compare_c" in s, Arg.Unit
(fun () -> action := s),
679 short_options ++ List.concat
(List.map
Common.thd3
other_options)
681 (* I don't want the -help and --help that are appended by Arg.align *)
683 Arg.align xs
+> List.rev
+> Common.drop
2 +> List.rev
686 Ignore unknown option
688 This simplifies the integration of Coccinelle in toolchain. For
689 instance, spatch can then be used as a checker in the Linux build
693 let check_include_path () =
694 let opt = Array.get
Sys.argv
!Arg.current
in
695 let is_include_re = Str.regexp
"-I\\(.*\\)" in
696 if Str.string_match
is_include_re opt 0 then
697 let path = Str.matched_group
1 opt in
698 FC.include_path
:= path::!FC.include_path
701 let rec arg_parse_no_fail l f msg
=
703 check_include_path ();
704 Arg.parse_argv
Sys.argv l f msg
;
707 arg_parse_no_fail l f msg
708 | Arg.Help msg
-> (* printf "%s" msg; exit 0; *)
709 raise Impossible
(* -help is specified in speclist *)
711 (* copy paste of Arg.parse. Don't want the default -help msg *)
712 let arg_parse2 l f msg argv
=
714 Arg.parse_argv argv l f msg
;
716 | Arg.Bad emsg
-> (* eprintf "%s" msg; exit 2; *)
717 if not
!ignore_unknown_opt then
719 let xs = Common.lines emsg
in
720 (* take only head, it's where the error msg is *)
723 raise
(Common.UnixExit
(2))
726 arg_parse_no_fail l f msg
;
727 | Arg.Help msg
-> (* printf "%s" msg; exit 0; *)
728 raise Impossible
(* -help is specified in speclist *)
734 Common.short_usage usage_msg short_options;
736 pr2
"Example of use:";
737 pr2
" ./spatch -sp_file foo.cocci foo.c -o /tmp/newfoo.c";
743 Common.long_usage usage_msg short_options other_options
745 let _ = short_usage_func := short_usage
746 let _ = long_usage_func := long_usage
748 (*****************************************************************************)
750 (*****************************************************************************)
752 (* for fresh identifier information *)
753 let adjust_stdin cfiles k
=
755 [] -> failwith
"not possible"
759 let (dir, base
, ext
) = Common.dbe_of_filename cfile
in
760 let varfile = Common.filename_of_dbe
(dir, base
, "var") in
761 if ext
=$
= "c" && Common.lfile_exists
varfile
764 with Invalid_argument
("Filename.chop_extension") -> None
in
765 Common.redirect_stdin_opt
newin k
767 let glimpse_filter (coccifile
, isofile
) dir =
768 let (_metavars
,astcocci
,_free_var_lists
,_negated_positions
,
769 _used_after_lists
,_positions_lists
,(_,query
,_)) =
770 Cocci.sp_of_file coccifile
(Some isofile
) in
772 None
-> pr2
"no inferred glimpse keywords"; None
774 let suffixes = if !include_headers then ["c";"h"] else ["c"] in
775 let rec loop = function
776 [] -> None
(* error, eg due to pattern too big *)
778 Printf.fprintf stderr
"%s\n" ("glimpse request = " ^ query
);
779 let command = spf
"glimpse -y -H %s -N -W -w '%s'" dir query
in
780 let (glimpse_res
,stat
) = Common.cmd_to_list_and_status
command in
782 Unix.WEXITED
(0) | Unix.WEXITED
(1) ->
783 Printf.fprintf stderr
"got files\n"; flush stderr
;
787 (fun file
-> List.mem
(Common.filesuffix file
) suffixes))
788 | _ -> loop queries
(* error, eg due to pattern too big *) in
791 let idutils_filter (coccifile
, isofile
) dir =
792 let (_metavars
,astcocci
,_free_var_lists
,_negated_positions
,
793 _used_after_lists
,_positions_lists
,(_,_,query
)) =
794 Cocci.sp_of_file coccifile
(Some isofile
) in
796 None
-> pr2
"no inferred idutils keywords"; None
798 let suffixes = if !include_headers then ["c";"h"] else ["c"] in
799 let files = Id_utils.interpret
dir query
in
800 Printf.fprintf stderr
"got files\n"; flush stderr
;
803 List.filter
(fun file
-> List.mem
(Common.filesuffix file
) suffixes))
805 (*****************************************************************************)
807 (*****************************************************************************)
811 Common.cmd_to_list
(* same as "true, "", _" case *)
813 (* FIXME : Could we remove xs ?
814 -use_glimpse requires a singleton.
815 This is checked some lines before.
816 then ("find "^(join " " (x::xs))^" -name \"*.[ch]\"")
817 else ("find "^(join " " (x::xs))^" -name \"*.c\"")
819 then ("find "^
path ^
" -name \"*.[ch]\"")
820 else ("find "^
path ^
" -name \"*.c\"")) in
823 then Common.cmd_to_list
("find "^
path ^
" -name \"*.cpp\"")
827 let rec main_action xs =
828 let (cocci_files
,xs) =
829 List.partition
(function nm
-> Filename.check_suffix nm
".cocci") xs in
830 (match (!cocci_file,cocci_files
) with
831 "",[fl
] -> cocci_file := fl
833 | _ -> failwith
"only one .cocci file allowed");
834 Iteration.base_file_list
:= xs;
835 let rec toploop = function
836 [] -> raise Impossible
838 (* a more general solution would be to use
839 * Common.files_of_dir_or_files (x::xs)
840 * as some elements in xs may also be directories, or individual
843 dir := (Common.is_directory x
);
845 if !cocci_file =$
= ""
846 then failwith
"I need a cocci file, use -sp_file <file>";
848 if !dir && !Flag.patch
=*= None
851 | [] -> Flag.patch
:= Some
(Cocci.normalize_path x
)
854 ("warning: patch output can only be created when only one\n"^
855 "directory is specified or when the -patch flag is used")
860 Common.profile_code
"Main.infiles computation" (fun () ->
861 match !dir, !kbuild_info, !Flag.scanner
with
863 | false, _, (Flag.Glimpse
|Flag.IdUtils
) -> [x
::xs]
864 | true, s, (Flag.Glimpse
|Flag.IdUtils
) when s <> "" ->
866 "-use_glimpse or -id_utils does not work with -kbuild"
867 | true, "", Flag.Glimpse
->
869 then failwith
"-use_glimpse can accept only one dir");
872 match glimpse_filter (!cocci_file, !Config.std_iso
) x
with
874 | Some
files -> files in
875 files +> List.map
(fun x
-> [x
])
876 | true, "", Flag.IdUtils
->
878 then failwith
"-id_utils can accept only one dir");
881 match idutils_filter (!cocci_file, !Config.std_iso
) x
with
883 | Some
files -> files in
884 files +> List.map
(fun x
-> [x
])
886 | false, _, _ -> [x
::xs]
888 get_files (join
" " (x
::xs)) +> List.map
(fun x
-> [x
])
891 | true, kbuild_info_file
,_ ->
893 Common.cmd_to_list
("find "^
(join
" " (x
::xs))^
" -type d")
895 let info = Kbuild.parse_kbuild_info kbuild_info_file
in
896 let groups = Kbuild.files_in_dirs
dirs info in
898 groups +> List.map
(function Kbuild.Group
xs -> xs)
902 (* make cache unique in parallel case *)
903 (match (!distrib_index,!Flag_parsing_c.cache_prefix
) with
904 (Some index
,Some str
) ->
905 Flag_parsing_c.cache_prefix
:=
906 Some
(Printf.sprintf
"%s/d%d" str index
)
910 match (!distrib_index,!distrib_max) with
911 (None
,None
) -> infiles
912 | (Some index
,Some max
) ->
915 failwith
"index starts at 0, and so must be less than max");
918 let rec loop ct
= function
921 if (ct
mod max
) =|= index
922 then x
::(loop (ct
+1) xs)
923 else loop (ct
+1) xs in
927 let all_files = List.length
infiles in
928 let regions = (all_files + (max
- 1)) / max
in
929 let this_min = index
* regions in
930 let this_max = (index
+1) * regions in
931 let rec loop ct
= function
934 if this_min <= ct
&& ct
< this_max
935 then x
::(loop (ct
+1) xs)
936 else loop (ct
+1) xs in
939 | _ -> failwith
"inconsistent distribution information" in
941 let (cocci_infos
,outfiles
) =
942 Common.profile_code
"Main.outfiles computation" (fun () ->
944 Cocci.pre_engine
(!cocci_file, !Config.std_iso
) in
946 infiles +> List.map
(fun cfiles
->
947 pr2
("HANDLING: " ^
(join
" " cfiles
));
948 Common.timeout_function_opt
!FC.timeout
(fun () ->
949 Common.report_if_take_time
10 (join
" " cfiles
) (fun () ->
952 if !output_file <> "" && !compat_mode then
957 adjust_stdin cfiles
(fun () ->
958 Common.redirect_stdout_opt
optfile (fun () ->
959 (* this is the main call *)
960 Cocci.full_engine
cocci_infos cfiles
963 | Common.UnixExit x
-> raise
(Common.UnixExit x
)
964 | Pycocci.Pycocciexception
->
965 raise
Pycocci.Pycocciexception
969 pr2
("EXN:" ^
Printexc.to_string e
);
973 (cocci_infos,res)) in
974 let outfiles = List.concat
outfiles in
975 (match Iteration.get_pending_instance
() with
977 (x
,xs,cocci_infos,outfiles)
978 | Some
(files,virt_rules
,virt_ids
) ->
979 if outfiles = [] or outfiles = [] or not
!FC.show_diff
983 (if !inplace_modif then generate_outfiles
outfiles x
xs);
984 Flag.defined_virtual_rules
:= virt_rules
;
985 Flag.defined_virtual_env
:= virt_ids
;
986 Common.erase_temp_files
();
987 Common.clear_pr2_once
();
988 distrib_index := None
;
995 "Out of place transformation not compatible with iteration. Aborting.\n consider using -no_show_diff or -in_place";
996 (x
,xs,cocci_infos,outfiles)
998 let (x
,xs,cocci_infos,outfiles) = toploop xs in
1000 Cocci.post_engine
cocci_infos;
1001 Common.profile_code
"Main.result analysis" (fun () ->
1002 Ctlcocci_integration.print_bench
();
1003 generate_outfiles
outfiles x
xs;
1004 if !compare_with_expected
1005 then Testing.compare_with_expected outfiles)
1007 and generate_outfiles
outfiles x
(* front file *) xs (* other files *) =
1008 let outfiles = Cocci.check_duplicate_modif
outfiles in
1009 outfiles +> List.iter
(fun (infile
, outopt
) ->
1010 outopt
+> Common.do_option
(fun outfile
->
1013 (match !backup_suffix with
1014 Some
backup_suffix ->
1015 Common.command2
("cp "^infile^
" "^infile^
backup_suffix)
1017 Common.command2
("cp "^outfile^
" "^infile
);
1021 then Common.command2
("cp "^outfile^
" "^infile^
".cocci_res")
1023 (* potential source of security pb if the /tmp/ file is
1024 * a symlink, so simpler to not produce any regular file
1025 * (files created by Common.new_temp_file are still ok)
1029 if !output_file =$= ""
1031 let tmpfile = "/tmp/"^Common.basename infile in
1032 pr2 (spf "One file modified. Result is here: %s" tmpfile);
1033 Common.command2 ("cp "^outfile^" "^tmpfile);
1037 if !output_file <> "" && not
!compat_mode then
1038 (match outfiles with
1039 | [infile
, Some outfile
] when infile
=$
= x
&& null
xs ->
1040 Common.command2
("cp " ^outfile^
" " ^
!output_file)
1041 | [infile
, None
] when infile
=$
= x
&& null
xs ->
1042 Common.command2
("cp " ^infile^
" " ^
!output_file)
1045 ("-o can not be applied because there are multiple " ^
1048 (*****************************************************************************)
1049 (* The coccinelle main entry point *)
1050 (*****************************************************************************)
1053 let arglist = Array.to_list
Sys.argv
in
1054 let arglist = Command_line.command_line
arglist in
1056 if not
(null
(Common.inter_set
arglist
1057 ["-cocci_file";"-sp_file";"-sp";"-test";"-testall";
1058 "-test_okfailed";"-test_regression_okfailed"]))
1059 then run_profile quiet_profile;
1061 let args = ref [] in
1063 (* Gc.set {(Gc.get ()) with Gc.stack_limit = 1024 * 1024};*)
1065 (* this call can set up many global flag variables via the cmd line *)
1066 arg_parse2 (Arg.align
all_options) (fun x
-> args := x
::!args) usage_msg
1067 (Array.of_list
arglist);
1069 (* julia hack so that one can override directories specified on
1070 * the command line. *)
1074 if List.length
!args > 1
1077 let chosen = List.hd
!args in
1079 pr2
("ignoring all but the last specified directory: "^
chosen);
1083 else List.hd
!args in
1084 if !FC.include_path
=*= []
1085 then FC.include_path
:= [Filename.concat
chosen_dir "include"]);
1087 args := List.rev
!args;
1089 if !cocci_file <> "" && (not
(!cocci_file =~
".*\\.\\(sgrep\\|spatch\\)$"))
1090 then cocci_file := Common.adjust_ext_if_needed
!cocci_file ".cocci";
1092 if !Config.std_iso
<> ""
1093 then Config.std_iso
:= Common.adjust_ext_if_needed
!Config.std_iso
".iso";
1094 if !Config.std_h
<> ""
1095 then Config.std_h
:= Common.adjust_ext_if_needed
!Config.std_h
".h";
1097 if !Config.std_h
<> ""
1098 then Parse_c.init_defs_builtins
!Config.std_h
;
1100 if !macro_file <> ""
1101 then Parse_c.init_defs_macros
!macro_file;
1104 (* must be done after Arg.parse, because Common.profile is set by it *)
1105 Common.profile_code
"Main total" (fun () ->
1108 let all_actions = Test_parsing_c.actions
() in
1112 (* --------------------------------------------------------- *)
1113 (* The test framework. Works with tests/ or .ok and .failed *)
1114 (* --------------------------------------------------------- *)
1115 | [x
] when !test_mode ->
1117 let prefix = "tests/" in
1118 let testfile = x ^
".cocci" in
1119 if Sys.file_exists
(prefix ^
testfile) then
1121 (if !FC.include_path
= []
1122 then FC.include_path
:= [prefix^
"include"]);
1123 Testing.testone
prefix x
!compare_with_expected
1126 if Sys.file_exists
testfile then
1128 (if !FC.include_path
= []
1129 then FC.include_path
:= ["include"]);
1130 Testing.testone
"" x
!compare_with_expected
1133 pr2
(spf
"ERROR: File %s does not exist" testfile)
1136 | [] when !test_all ->
1137 (if !FC.include_path
= []
1138 then FC.include_path
:= ["tests/include"]);
1139 if !expected_score_file <> ""
1140 then Testing.testall ~
expected_score_file:!expected_score_file ()
1141 else Testing.testall
()
1143 | [] when !test_regression_okfailed ->
1144 Testing.test_regression_okfailed ()
1146 | ((x
::xs) as cfiles
) when !test_okfailed ->
1147 (* do its own timeout on FC.timeout internally *)
1148 FC.relax_include_path
:= true;
1149 adjust_stdin cfiles
(fun () ->
1150 Testing.test_okfailed !cocci_file cfiles
1153 (* --------------------------------------------------------- *)
1154 (* Actions, useful to debug subpart of coccinelle *)
1155 (* --------------------------------------------------------- *)
1157 | xs when List.mem
!action (Common.action_list
all_actions) ->
1158 Common.do_action
!action xs all_actions
1160 | [file
] when !action =$
= "-parse_cocci" ->
1161 Testing.test_parse_cocci file
1163 (* I think this is used by some scripts in some Makefile for our
1164 * big-tests. So dont remove.
1166 | [file1
;file2
] when !action =$
= "-compare_c" ->
1167 Test_parsing_c.test_compare_c file1 file2
(* result = unix code *)
1169 (* could add the Test_parsing_c.test_actions such as -parse_c & co *)
1172 (* --------------------------------------------------------- *)
1173 (* This is the main entry *)
1174 (* --------------------------------------------------------- *)
1175 | x
::xs -> main_action (x
::xs)
1177 (* --------------------------------------------------------- *)
1179 (* --------------------------------------------------------- *)
1180 | [] -> short_usage()
1182 if !Pycocci.initialised
&& (Pycocci.py_isinitialized
()) != 0 then begin
1183 ignore
(Pycocci.pyrun_simplestring
"cocci.finalise()");
1185 then Common.pr2
"Finalizing python\n";
1186 Pycocci.py_finalize
();
1191 let main_with_better_error_report () =
1192 if !Common.debugger
then main ()
1197 | Unix.Unix_error
(e
, "stat", filename
) ->
1199 (spf
"ERROR: File %s does not exist: %s"
1200 filename
(Unix.error_message e
));
1201 raise
(UnixExit
(-1))
1202 | Parse_cocci.Bad_virt
s ->
1203 Common.pr2
(Printf.sprintf
"virtual rule %s not supported" s);
1204 raise
(UnixExit
(-1))
1206 (*****************************************************************************)
1208 Common.main_boilerplate
(fun () ->
1209 main_with_better_error_report ();
1210 Ctlcocci_integration.print_bench
();