Coccinelle release-1.0.0-rc11
[bpt/coccinelle.git] / main.ml
1 (*
2 * Copyright 2012, INRIA
3 * Julia Lawall, Gilles Muller
4 * Copyright 2010-2011, INRIA, University of Copenhagen
5 * Julia Lawall, Rene Rydhof Hansen, Gilles Muller, Nicolas Palix
6 * Copyright 2005-2009, Ecole des Mines de Nantes, University of Copenhagen
7 * Yoann Padioleau, Julia Lawall, Rene Rydhof Hansen, Henrik Stuart, Gilles Muller, Nicolas Palix
8 * This file is part of Coccinelle.
9 *
10 * Coccinelle is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, according to version 2 of the License.
13 *
14 * Coccinelle is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with Coccinelle. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * The authors reserve the right to distribute this or future versions of
23 * Coccinelle under other licenses.
24 *)
25
26
27 open Common
28 module FC = Flag_cocci
29
30 (*****************************************************************************)
31 (* Flags *)
32 (*****************************************************************************)
33
34 (* In addition to flags that can be tweaked via -xxx options (cf the
35 * full list of options in "the spatch options" section below), the
36 * spatch program also depends on external files, described in
37 * globals/config.ml, mainly a standard.h and standard.iso file *)
38
39 let cocci_file = ref ""
40
41 let output_file = ref ""
42 let inplace_modif = ref false (* but keeps nothing *)
43 let backup_suffix =
44 ref (None : string option) (* suffix for backup if one is desired *)
45 let outplace_modif = ref false (* generates a .cocci_res *)
46 let preprocess = ref false (* run the C preprocessor before cocci *)
47 let compat_mode = ref false
48 let ignore_unknown_opt = ref false
49
50 (* somehow obsolete now *)
51 let dir = ref false
52
53 let include_headers = ref false
54 let kbuild_info = ref ""
55
56 let macro_file = ref ""
57
58 (* test mode *)
59 let test_mode = ref false
60 let test_all = ref false
61 let test_okfailed = ref false
62 let test_regression_okfailed = ref false
63 let expected_score_file = ref ""
64
65
66 (* action mode *)
67 let action = ref ""
68
69 (* works with -test but also in "normal" spatch mode *)
70 let compare_with_expected = ref false
71
72 let distrib_index = ref (None : int option)
73 let distrib_max = ref (None : int option)
74 let mod_distrib = ref false
75
76 (*****************************************************************************)
77 (* Profiles *)
78 (*****************************************************************************)
79
80 (* pair of (list of flags to set true, list of flags to set false *)
81 let very_quiet_profile = (
82 [
83 ],
84 [
85 (* FC.show_diff; just leave this as it is *)
86
87 Common.print_to_stderr;
88 Flag.show_misc;
89 Flag.show_trying;
90 Flag.show_transinfo;
91
92 FC.show_c;
93 FC.show_cocci;
94 FC.show_flow;
95 FC.show_before_fixed_flow;
96 FC.show_ctl_tex;
97 FC.show_ctl_text;
98 FC.show_binding_in_out;
99
100 FC.verbose_cocci;
101
102 Flag_parsing_c.show_parsing_error;
103
104 Flag_parsing_c.verbose_lexing;
105 Flag_parsing_c.verbose_parsing;
106 Flag_parsing_c.verbose_type;
107 Flag_parsing_c.verbose_cfg;
108 Flag_parsing_c.verbose_unparsing;
109 Flag_parsing_c.verbose_visit;
110 Flag_parsing_c.verbose_cpp_ast;
111
112 Flag_matcher.verbose_matcher;
113 Flag_matcher.debug_engine;
114
115 Flag_parsing_c.debug_unparsing;
116
117 Flag_parsing_cocci.show_SP;
118 Flag_parsing_cocci.show_iso_failures;
119
120 Flag_ctl.verbose_ctl_engine;
121 Flag_ctl.verbose_match;
122
123
124 ])
125
126 let quiet_profile = (
127 [
128 Common.print_to_stderr
129 ],
130 [
131 (* FC.show_diff; just leave this as it is *)
132
133 Flag.show_misc;
134 Flag.show_trying;
135 Flag.show_transinfo;
136
137 FC.show_c;
138 FC.show_cocci;
139 FC.show_flow;
140 FC.show_before_fixed_flow;
141 FC.show_ctl_tex;
142 FC.show_ctl_text;
143 FC.show_binding_in_out;
144
145 FC.verbose_cocci;
146
147 Flag_parsing_c.show_parsing_error;
148
149 Flag_parsing_c.verbose_lexing;
150 Flag_parsing_c.verbose_parsing;
151 Flag_parsing_c.verbose_type;
152 Flag_parsing_c.verbose_cfg;
153 Flag_parsing_c.verbose_unparsing;
154 Flag_parsing_c.verbose_visit;
155 Flag_parsing_c.verbose_cpp_ast;
156
157 Flag_matcher.verbose_matcher;
158 Flag_matcher.debug_engine;
159
160 Flag_parsing_c.debug_unparsing;
161
162 Flag_parsing_cocci.show_SP;
163 Flag_parsing_cocci.show_iso_failures;
164
165 Flag_ctl.verbose_ctl_engine;
166 Flag_ctl.verbose_match;
167
168
169 ])
170
171 (* some information that is useful in seeing why a semantic patch doesn't
172 work properly *)
173 let debug_profile = (
174 [
175 Common.print_to_stderr;
176 Flag.show_misc;
177 Flag.show_transinfo;
178
179 FC.show_diff;
180 FC.show_cocci;
181 FC.show_binding_in_out;
182 FC.show_dependencies;
183
184 Flag_parsing_cocci.keep_ml_script;
185 Flag_parsing_cocci.show_iso_failures;
186
187 FC.verbose_cocci;
188
189 Flag_parsing_c.verbose_cfg;
190 Flag_parsing_c.verbose_unparsing;
191 Flag_parsing_c.verbose_visit;
192
193 Flag_matcher.verbose_matcher;
194
195 Flag_parsing_c.show_parsing_error;
196 ],
197 [
198
199 Flag.show_misc;
200
201 FC.show_c;
202 FC.show_flow;
203 FC.show_before_fixed_flow;
204 FC.show_ctl_tex;
205 FC.show_ctl_text;
206
207 Flag_parsing_cocci.show_SP;
208 Flag_ctl.verbose_ctl_engine;
209 Flag_ctl.verbose_match;
210 Flag_matcher.debug_engine;
211 Flag_parsing_c.debug_unparsing;
212 Flag_parsing_c.verbose_type;
213 Flag_parsing_c.verbose_parsing;
214 ])
215
216 let pad_profile = (
217 [
218 FC.show_diff;
219 Common.print_to_stderr;
220 ],
221 [
222
223 Flag.show_misc;
224 Flag.show_transinfo;
225
226 FC.show_c;
227 FC.show_cocci;
228 FC.show_flow;
229 FC.show_before_fixed_flow;
230 FC.show_ctl_tex;
231 FC.show_ctl_text;
232 FC.show_binding_in_out;
233
234 Flag_parsing_cocci.show_SP;
235 Flag_parsing_cocci.show_iso_failures;
236 Flag_ctl.verbose_ctl_engine;
237 Flag_ctl.verbose_match;
238 Flag_matcher.debug_engine;
239 Flag_parsing_c.debug_unparsing;
240 Flag_parsing_c.verbose_type;
241 Flag_parsing_c.verbose_parsing;
242 ])
243
244 let run_profile p =
245 let (set_to_true, set_to_false) = p in
246 List.iter (fun x -> x := false) set_to_false;
247 List.iter (fun x -> x := true) set_to_true
248
249 (*****************************************************************************)
250 (* The spatch options *)
251 (*****************************************************************************)
252
253 let usage_msg =
254 "Usage: " ^ basename Sys.argv.(0) ^
255 " --sp-file <SP> <infile> [-o <outfile>] [--iso-file <iso>] [options]" ^
256 "\n" ^ "Options are:"
257
258 (* forward reference trick *)
259 let short_usage_func = ref (fun () -> ())
260 let long_usage_func = ref (fun () -> ())
261
262
263 (* The short_options are user-oriented. The other options are for
264 * the developers of coccinelle or advanced-users that know
265 * quite well the underlying semantics of coccinelle.
266 *)
267
268
269 (* will be printed when use only ./spatch. For the rest you have to
270 * use -longhelp to see them.
271 *)
272 let short_options = [
273 "--sp-file", Arg.Set_string cocci_file,
274 " <file> the semantic patch file";
275
276 "-o", Arg.Set_string output_file,
277 " <file> the output file";
278 "--in-place", Arg.Set inplace_modif,
279 " do the modification on the file directly";
280 "--backup-suffix", Arg.String (function s -> backup_suffix := Some s),
281 " suffix to use when making a backup for inplace";
282 "--out-place", Arg.Set outplace_modif,
283 " store modifications in a .cocci_res file";
284
285 "-U", Arg.Int (fun n -> Flag_parsing_c.diff_lines := Some (i_to_s n)),
286 " set number of diff context lines";
287 "--partial-match", Arg.Set Flag_ctl.partial_match,
288 " report partial matches of the SP on the C file";
289
290 "--iso-file", Arg.Set_string Config.std_iso,
291 " <file> (default=" ^ !Config.std_iso ^")";
292 "--macro-file", Arg.Set_string macro_file,
293 " <file>";
294 "--macro-file-builtins", Arg.Set_string Config.std_h,
295 " <file> (default=" ^ !Config.std_h ^ ")";
296
297 "--recursive-includes",
298 Arg.Unit (function _ -> FC.include_options := FC.I_REALLY_ALL_INCLUDES),
299 " causes all available include files, both those included in the C file(s) and those included in header files, to be used";
300 "--all-includes",
301 Arg.Unit (function _ -> FC.include_options := FC.I_ALL_INCLUDES),
302 " causes all available include files included in the C file(s) to be used";
303 "--no-includes",
304 Arg.Unit (function _ -> FC.include_options := FC.I_NO_INCLUDES),
305 " causes not even local include files to be used";
306 "--local-includes",
307 Arg.Unit (function _ -> FC.include_options := FC.I_NORMAL_INCLUDES),
308 " causes local include files to be used";
309 "--ignore-unknown-options", Arg.Set ignore_unknown_opt,
310 " For integration in a toolchain (must be set before the first unknown option)";
311 "--include-headers", Arg.Set include_headers,
312 " process header files independently";
313 "-I", Arg.String (fun x ->
314 FC.include_path:= x::!FC.include_path
315 ),
316 " <dir> containing the header files (optional)";
317
318 "--preprocess", Arg.Set preprocess,
319 " run the C preprocessor before applying the semantic match";
320
321 "-c", Arg.Set compat_mode, " gcc/cpp compatibility mode";
322
323 "--dir", Arg.Set dir,
324 " <dir> process all files in directory recursively";
325
326 "--use-glimpse", Arg.Unit (function _ -> Flag.scanner := Flag.Glimpse),
327 " works with -dir, use info generated by glimpseindex";
328 "--use-google", Arg.String (function s -> Flag.scanner := Flag.Google s),
329 " find relevant files using google code search";
330 "--use-idutils", Arg.Unit (function s -> Flag.scanner := Flag.IdUtils),
331 " find relevant files using id-utils";
332 "--patch",
333 Arg.String (function s -> Flag.patch := Some (Cocci.normalize_path s)),
334 (" <dir> path name with respect to which a patch should be created\n"^
335 " \"\" for a file in the current directory");
336 "--kbuild-info", Arg.Set_string kbuild_info,
337 " <file> improve -dir by grouping related c files";
338 "--pyoutput", Arg.Set_string Flag.pyoutput,
339 " Sets output routine: Standard values: <coccilib.output.Gtk|coccilib.output.Console>";
340
341
342 "--version", Arg.Unit (fun () ->
343 let withpython = if Pycocci.python_support then "with" else "without" in
344 let whichregexp =
345 if !Regexp.pcre_support then "with PCRE support"
346 else "with Str regexp support "
347 in
348 pr2 (spf "spatch version %s %s Python support and %s" Config.version withpython whichregexp);
349 exit 0;
350 ),
351 " guess what";
352
353 "--date", Arg.Unit (fun () ->
354 pr2 "version: $Date$";
355 raise (Common.UnixExit 0)
356 ),
357 " guess what";
358
359 "--shorthelp", Arg.Unit (fun () ->
360 !short_usage_func();
361 raise (Common.UnixExit 0)
362 ),
363 " see short list of options";
364 "--longhelp", Arg.Unit (fun () ->
365 !long_usage_func();
366 raise (Common.UnixExit 0)
367 ),
368 " see all the available options in different categories";
369 "-help", Arg.Unit (fun () ->
370 !long_usage_func();
371 raise (Common.UnixExit 0)
372 ),
373 " ";
374 "--help", Arg.Unit (fun () ->
375 !long_usage_func();
376 raise (Common.UnixExit 0)
377 ),
378 " ";
379 ]
380
381 (* the format is a list of triples:
382 * (title of section * (optional) explanation of sections * option list)
383 *)
384 let other_options = [
385 "aliases and obsolete options",
386 "",
387 [
388 "--sp", Arg.Unit (function _ -> failwith "impossible"),
389 " command line semantic patch";
390 "--iso", Arg.Set_string Config.std_iso, " short option of --iso-file";
391
392 "--cocci-file", Arg.Set_string cocci_file,
393 " <file> the semantic patch file";
394 (* "-c", Arg.Set_string cocci_file, " short option of -sp_file"; *)
395 ];
396
397 "most useful show options",
398 "",
399 [
400 "--show-diff" , Arg.Set FC.show_diff, " ";
401 "--no-show-diff" , Arg.Clear FC.show_diff, " ";
402 "--force-diff" , Arg.Set FC.force_diff,
403 "show diff even if only spacing changes";
404 "--show-flow" , Arg.Set FC.show_flow, " ";
405 (* works in conjunction with -show_ctl_text *)
406 "--ctl-inline-let",
407 Arg.Unit
408 (function _ -> FC.show_ctl_text := true; FC.inline_let_ctl := true), " ";
409 "--ctl-show-mcodekind",
410 Arg.Unit
411 (function _ -> FC.show_ctl_text := true; FC.show_mcodekind_in_ctl := true),
412 " ";
413 "--show-bindings", Arg.Set FC.show_binding_in_out, " ";
414 "--show-transinfo", Arg.Set Flag.show_transinfo, " ";
415 "--show-misc", Arg.Set Flag.show_misc, " ";
416 "--show-trying", Arg.Set Flag.show_trying,
417 " show the name of each function being processed";
418 "--show-dependencies",
419 Arg.Unit (function _ -> FC.show_dependencies := true;
420 FC.show_binding_in_out := true),
421 " show the dependencies related to each rule";
422 ];
423
424 "verbose subsystems options",
425 "",
426 [
427 "--verbose-ctl-engine",
428 Arg.Unit (function _ ->
429 Flag_ctl.verbose_ctl_engine := true; FC.show_ctl_text := true) , " ";
430 "--verbose-match", Arg.Set Flag_ctl.verbose_match, " ";
431 "--verbose-engine", Arg.Set Flag_matcher.debug_engine, " ";
432 "--graphical-trace", Arg.Set Flag_ctl.graphical_trace, " generate a pdf file representing the matching process";
433 "--gt-without-label",
434 Arg.Unit (function _ ->
435 Flag_ctl.graphical_trace := true; Flag_ctl.gt_without_label := true),
436 " remove graph label (requires option -graphical-trace)";
437
438 "--parse-error-msg", Arg.Set Flag_parsing_c.show_parsing_error, " ";
439 "--verbose-parsing",
440 Arg.Unit (fun _ -> Flag_parsing_c.verbose_parsing := true;
441 Flag_parsing_c.show_parsing_error := true), " ";
442 "--type-error-msg", Arg.Set Flag_parsing_c.verbose_type, " ";
443 (* could also use Flag_parsing_c.options_verbose *)
444 ];
445
446 "other show options",
447 "",
448 [
449 "--show-c" , Arg.Set FC.show_c, " ";
450 "--show-cocci" , Arg.Set FC.show_cocci, " ";
451 "--show-before-fixed-flow" , Arg.Set FC.show_before_fixed_flow, " ";
452 "--show-ctl-tex" , Arg.Set FC.show_ctl_tex, " ";
453 "--show-ctl-text" , Arg.Set FC.show_ctl_text, " ";
454 "--show-SP" , Arg.Set Flag_parsing_cocci.show_SP, " ";
455 ];
456
457
458 "debug C parsing/unparsing",
459 "",
460 [
461 "--debug-cpp", Arg.Set Flag_parsing_c.debug_cpp, " ";
462 "--debug-lexer", Arg.Set Flag_parsing_c.debug_lexer , " ";
463 "--debug-etdt", Arg.Set Flag_parsing_c.debug_etdt , " ";
464 "--debug-typedef", Arg.Set Flag_parsing_c.debug_typedef, " ";
465
466 "--filter-msg", Arg.Set Flag_parsing_c.filter_msg ,
467 " filter some cpp message when the macro is a \"known\" cpp construct";
468 "--filter-define-error", Arg.Set Flag_parsing_c.filter_define_error," ";
469 "--filter-msg-define-error", Arg.Set Flag_parsing_c.filter_msg_define_error,
470 " filter the error msg";
471 "--filter-passed-level", Arg.Set_int Flag_parsing_c.filter_passed_level," ";
472 (* debug cfg doesn't seem to have any effect, so drop it as an option *)
473 (* "--debug_cfg", Arg.Set Flag_parsing_c.debug_cfg , " "; *)
474 "--debug-unparsing", Arg.Set Flag_parsing_c.debug_unparsing, " ";
475
476 ];
477 (* could use Flag_parsing_c.options_debug_with_title instead *)
478
479
480 "shortcut for enabling/disabling a set of debugging options at once",
481 "",
482 [
483 (* todo: other profile ? *)
484 "--quiet", Arg.Unit (fun () -> run_profile quiet_profile), " ";
485 "--very-quiet", Arg.Unit (fun () -> run_profile very_quiet_profile), " ";
486 "--debug", Arg.Unit (fun () -> run_profile debug_profile), " ";
487 "--pad", Arg.Unit (fun () -> run_profile pad_profile), " ";
488
489 ];
490
491 "bench options",
492 "",
493 [
494 "--profile", Arg.Unit (function () -> Common.profile := Common.PALL) ,
495 " gather timing information about the main coccinelle functions";
496 "--bench", Arg.Int (function x -> Flag_ctl.bench := x),
497 " <level> for profiling the CTL engine";
498 "--timeout", Arg.Int (fun x -> FC.timeout := Some x),
499 " <sec> timeout in seconds";
500 "--steps", Arg.Int (fun x -> Flag_ctl.steps := Some x),
501 " max number of model checking steps per code unit";
502 "--iso-limit", Arg.Int (fun x -> Flag_parsing_cocci.iso_limit := Some x),
503 " max depth of iso application";
504 "--no-iso-limit", Arg.Unit (fun _ -> Flag_parsing_cocci.iso_limit := None),
505 " disable limit on max depth of iso application";
506 "--track-iso", Arg.Set Flag.track_iso_usage,
507 " gather information about isomorphism usage";
508 "--disable-iso",
509 Arg.String
510 (fun s -> Flag_parsing_cocci.disabled_isos :=
511 s :: !Flag_parsing_cocci.disabled_isos),
512 " disable a specific isomorphism";
513 "--profile-iso",
514 Arg.Unit
515 (function () ->
516 Common.profile :=
517 (*post_engine not included, because it doesn't use isos*)
518 PSOME ["parse cocci";"mysat";"asttoctl2";"pre_engine";"full_engine"]),
519 " gather information about the cost of isomorphism usage"
520 ];
521
522
523
524 "change of algorithm options",
525 "",
526 [
527 (* "--popl", Arg.Set FC.popl,
528 " simplified SmPL, for the popl paper";
529
530 "--popl_mark_all",
531 Arg.Unit
532 (function _ -> FC.popl := true; Flag_popl.mark_all := true),
533 " simplified SmPL, for the popl paper";
534
535 "--popl_keep_all_wits",
536 Arg.Unit
537 (function _ -> FC.popl := true; Flag_popl.keep_all_wits := true),
538 " simplified SmPL, for the popl paper";
539
540 "--hrule", Arg.String
541 (function s ->
542 Flag.make_hrule := Some s; FC.include_options := FC.I_NO_INCLUDES),
543 " semantic patch generation";
544 *)
545 "--keep-comments", Arg.Set Flag_parsing_c.keep_comments,
546 " keep comments around removed code";
547
548 "--loop", Arg.Set Flag_ctl.loop_in_src_code, " ";
549 "--no-loops", Arg.Set Flag_parsing_c.no_loops,
550 " drop all back edges derived from looping constructs - unsafe";
551 "--no-gotos", Arg.Set Flag_parsing_c.no_gotos,
552 " drop all jumps derived from gotos - unsafe";
553 "--no-saved-typedefs", Arg.Clear Flag_cocci.use_saved_typedefs,
554 " drop all inferred typedefs from one parse of some code to the next";
555
556 "--ocaml-regexps", Arg.Clear Regexp.pcre_support,
557 " use OCaml Str regular expressions for constraints";
558
559 "--l1", Arg.Clear Flag_parsing_c.label_strategy_2, " ";
560 "--ifdef-to-if", Arg.Set FC.ifdef_to_if,
561 " convert ifdef to if (experimental)";
562 "--no-ifdef-to-if", Arg.Clear FC.ifdef_to_if,
563 " convert ifdef to if (experimental)";
564
565 "--disable-multi-pass", Arg.Set Flag_parsing_c.disable_multi_pass, " ";
566
567 "--noif0-passing", Arg.Clear Flag_parsing_c.if0_passing,
568 " ";
569 "--noadd-typedef-root", Arg.Clear Flag_parsing_c.add_typedef_root, " ";
570 (* could use Flag_parsing_c.options_algo instead *)
571
572
573 "--disallow-nested-exps", Arg.Set Flag_matcher.disallow_nested_exps,
574 " disallow an expresion pattern from matching a term and its subterm";
575 "--disable-worth-trying-opt", Arg.Clear FC.worth_trying_opt,
576 " ";
577 "--only-return-is-error-exit",
578 Arg.Set Flag_matcher.only_return_is_error_exit,
579 "if this flag is not set, then break and continue are also error exits";
580 (* the following is a hack to make it easier to add code in sgrep-like
581 code, essentially to compensate for the fact that we don't have
582 any way of printing things out *)
583 "--allow-inconsistent-paths",
584 Arg.Set Flag_matcher.allow_inconsistent_paths,
585 " if this flag is set don't check for inconsistent paths; dangerous";
586 "--no-safe-expressions",
587 Arg.Set Flag_matcher.no_safe_expressions,
588 " make an expression disjunction not prioritise the topmost disjunct";
589 "--int-bits", Arg.Int Flag_parsing_c.set_int_bits,
590 " the number of bits in an unsigned int";
591 "--long-bits", Arg.Int Flag_parsing_c.set_long_bits,
592 " the number of bits in an unsigned long";
593 "--linux-spacing", Arg.Unit Flag_parsing_c.set_linux_spacing,
594 " spacing of + code follows the conventions of Linux";
595 "--smpl-spacing", Arg.Unit Flag_parsing_c.set_smpl_spacing,
596 " spacing of + code follows the semantic patch";
597 "-D", Arg.String Flag.set_defined_virtual_rules,
598 " indicate that a virtual rule should be considered to be matched";
599 "--c++", Arg.Set Flag.c_plus_plus,
600 " make a small attempt to parse C++ files"
601 ];
602
603 "misc options",
604 "",
605 [
606 "--debugger", Arg.Set Common.debugger,
607 " option to set if launch spatch in ocamldebug";
608 "--disable-once", Arg.Set Common.disable_pr2_once,
609 " to print more messages";
610 "--show-trace-profile", Arg.Set Common.show_trace_profile,
611 " show trace";
612 "--save-tmp-files", Arg.Set Common.save_tmp_files, " ";
613 ];
614
615 "concurrency",
616 "",
617 [
618 "--index", Arg.Int (function x -> distrib_index := Some x) ,
619 " the processor to use for this run of spatch";
620 "--max", Arg.Int (function x -> distrib_max := Some x) ,
621 " the number of processors available";
622 "--mod-distrib", Arg.Set mod_distrib,
623 " use mod to distribute files among the processors";
624 ];
625
626 "pad options",
627 "",
628 [
629 "--use-cache", Arg.Set Flag_parsing_c.use_cache,
630 " use .ast_raw pre-parsed cached C file";
631 "--cache_prefix",
632 Arg.String (function s ->
633 Flag_parsing_c.cache_prefix := Some s;
634 Flag_parsing_c.use_cache := true),
635 " directory of cached ASTs, sets -use-cache";
636 (* could use Flag_parsing_c.options_pad instead *)
637 "--cache-limit",
638 Arg.Int (function n ->
639 Flag_parsing_c.cache_limit := Some n),
640 " maximum number of cached ASTs, sets -use-cache";
641 ];
642
643
644
645 "test mode and test options (works with tests/ or .ok files)",
646 "The test options don't work with the --sp-file and so on.",
647 [
648 "--test", Arg.Set test_mode,
649 " <file> launch spatch on tests/file.[c,cocci]";
650 "--testall", Arg.Set test_all,
651 " launch spatch on all files in tests/ having a .res";
652 "--test-okfailed", Arg.Set test_okfailed,
653 " generates .{ok,failed,spatch_ok} files using .res files";
654 "--test-regression-okfailed", Arg.Set test_regression_okfailed,
655 " process the .{ok,failed,spatch_ok} files in current dir";
656
657 "--compare-with-expected", Arg.Set compare_with_expected,
658 " use also file.res";
659 "--expected-score-file", Arg.Set_string expected_score_file,
660 " which score file to compare with in -testall";
661 "--relax-include-path", Arg.Set FC.relax_include_path,
662 " ";
663 ];
664
665 "action mode",
666 ("The action options don't work with the --sp-file and so on." ^ "\n" ^
667 "It's for the other (internal) uses of the spatch program."
668 ),
669
670 (* -token_c, -parse_c, etc *)
671 ((Common.options_of_actions action (Test_parsing_c.actions())) ++
672 [
673 (let s = "--parse-cocci" in s, Arg.Unit (fun () -> action := s),
674 " <file>");
675 (let s = "--compare-c" in s, Arg.Unit (fun () -> action := s),
676 " <file1> <file2>");
677 ]);
678 ]
679
680
681 let all_options =
682 short_options ++ List.concat (List.map Common.thd3 other_options)
683
684 (* I don't want the -help and --help that are appended by Arg.align *)
685 let arg_align2 xs =
686 Arg.align xs +> List.rev +> Common.drop 2 +> List.rev
687
688 (*
689 Ignore unknown option
690
691 This simplifies the integration of Coccinelle in toolchain. For
692 instance, spatch can then be used as a checker in the Linux build
693 system.
694
695 *)
696 let check_include_path () =
697 let opt = Array.get Sys.argv !Arg.current in
698 let is_include_re = Str.regexp "-I\\(.*\\)" in
699 if Str.string_match is_include_re opt 0 then
700 let path = Str.matched_group 1 opt in
701 FC.include_path:= path::!FC.include_path
702 else ()
703
704 let rec arg_parse_no_fail l f msg =
705 try
706 check_include_path ();
707 Arg.parse_argv Sys.argv l f msg;
708 with
709 | Arg.Bad emsg ->
710 arg_parse_no_fail l f msg
711 | Arg.Help msg -> (* printf "%s" msg; exit 0; *)
712 raise Impossible (* -help is specified in speclist *)
713
714 (* copy paste of Arg.parse. Don't want the default -help msg *)
715 let arg_parse2 l f msg argv =
716 (try
717 Arg.parse_argv argv l f msg;
718 with
719 | Arg.Bad emsg -> (* eprintf "%s" msg; exit 2; *)
720 if not !ignore_unknown_opt then
721 begin
722 let xs = Common.lines emsg in
723 (* take only head, it's where the error msg is *)
724 pr2 (List.hd xs);
725 !short_usage_func();
726 raise (Common.UnixExit (2))
727 end
728 else
729 arg_parse_no_fail l f msg;
730 | Arg.Help msg -> (* printf "%s" msg; exit 0; *)
731 raise Impossible (* -help is specified in speclist *)
732 )
733
734
735 let short_usage () =
736 begin
737 Common.short_usage usage_msg short_options;
738 pr2 "";
739 pr2 "Example of use:";
740 pr2 " ./spatch --sp-file foo.cocci foo.c -o /tmp/newfoo.c";
741 pr2 "";
742 end
743
744
745 let long_usage () =
746 Common.long_usage usage_msg short_options other_options
747
748 let _ = short_usage_func := short_usage
749 let _ = long_usage_func := long_usage
750
751 (*****************************************************************************)
752 (* Helpers *)
753 (*****************************************************************************)
754
755 (* for fresh identifier information *)
756 let adjust_stdin cfiles k =
757 match cfiles with
758 [] -> failwith "not possible"
759 | cfile::_ ->
760 let newin =
761 try
762 let (dir, base, ext) = Common.dbe_of_filename cfile in
763 let varfile = Common.filename_of_dbe (dir, base, "var") in
764 if ext =$= "c" && Common.lfile_exists varfile
765 then Some varfile
766 else None
767 with Invalid_argument("Filename.chop_extension") -> None in
768 Common.redirect_stdin_opt newin k
769
770 let glimpse_filter (coccifile, isofile) dir =
771 let (_metavars,astcocci,_free_var_lists,_negated_positions,
772 _used_after_lists,_positions_lists,(_,query,_)) =
773 Cocci.sp_of_file coccifile (Some isofile) in
774 match query with
775 None -> pr2 "no inferred glimpse keywords"; None
776 | Some queries ->
777 let suffixes = if !include_headers then ["c";"h"] else ["c"] in
778 let rec loop = function
779 [] -> None (* error, eg due to pattern too big *)
780 | query::queries ->
781 Printf.fprintf stderr "%s\n" ("glimpse request = " ^ query);
782 let command = spf "glimpse -y -H %s -N -W -w '%s'" dir query in
783 let (glimpse_res,stat) = Common.cmd_to_list_and_status command in
784 match stat with
785 Unix.WEXITED(0) | Unix.WEXITED(1) ->
786 Printf.fprintf stderr "got files\n"; flush stderr;
787 Some
788 (glimpse_res +>
789 List.filter
790 (fun file -> List.mem (Common.filesuffix file) suffixes))
791 | _ -> loop queries (* error, eg due to pattern too big *) in
792 loop queries
793
794 let idutils_filter (coccifile, isofile) dir =
795 let (_metavars,astcocci,_free_var_lists,_negated_positions,
796 _used_after_lists,_positions_lists,(_,_,query)) =
797 Cocci.sp_of_file coccifile (Some isofile) in
798 match query with
799 None -> pr2 "no inferred idutils keywords"; None
800 | Some query ->
801 let suffixes = if !include_headers then ["c";"h"] else ["c"] in
802 let files = Id_utils.interpret dir query in
803 Printf.fprintf stderr "got files\n"; flush stderr;
804 Some
805 (files +>
806 List.filter (fun file -> List.mem (Common.filesuffix file) suffixes))
807
808 (*****************************************************************************)
809 (* Main action *)
810 (*****************************************************************************)
811
812 let get_files path =
813 let ch =
814 Common.cmd_to_list (* same as "true, "", _" case *)
815 (if !include_headers
816 (* FIXME : Could we remove xs ?
817 -use_glimpse requires a singleton.
818 This is checked some lines before.
819 then ("find "^(join " " (x::xs))^" -name \"*.[ch]\"")
820 else ("find "^(join " " (x::xs))^" -name \"*.c\"")
821 *)
822 then ("find "^ path ^" -name \"*.[ch]\"")
823 else ("find "^ path ^" -name \"*.c\"")) in
824 let cpp =
825 if !Flag.c_plus_plus
826 then Common.cmd_to_list ("find "^ path ^" -name \"*.cpp\"")
827 else [] in
828 cpp @ ch
829
830 let rec main_action xs =
831 let (cocci_files,xs) =
832 List.partition (function nm -> Filename.check_suffix nm ".cocci") xs in
833 (match (!cocci_file,cocci_files) with
834 "",[fl] -> cocci_file := fl
835 | _,[] -> ()
836 | _ -> failwith "only one .cocci file allowed");
837 Iteration.base_file_list := xs;
838 let rec toploop = function
839 [] -> failwith "no C files provided"
840 | x::xs ->
841 (* a more general solution would be to use
842 * Common.files_of_dir_or_files (x::xs)
843 * as some elements in xs may also be directories, or individual
844 * files.
845 *)
846 dir := (Common.is_directory x);
847
848 if !cocci_file =$= ""
849 then failwith "I need a cocci file, use --sp-file <file>";
850
851 if !dir && !Flag.patch =*= None
852 then
853 (match xs with
854 | [] -> Flag.patch := Some (Cocci.normalize_path x)
855 | _ ->
856 pr2
857 ("warning: patch output can only be created when only one\n"^
858 "directory is specified or when the -patch flag is used")
859 );
860 Flag.dir := x;
861
862 let infiles =
863 Common.profile_code "Main.infiles computation" (fun () ->
864 match !dir, !kbuild_info, !Flag.scanner with
865 (* glimpse *)
866 | false, _, (Flag.Glimpse|Flag.IdUtils) -> [x::xs]
867 | true, s, (Flag.Glimpse|Flag.IdUtils) when s <> "" ->
868 failwith
869 "-use_glimpse or -id_utils does not work with -kbuild"
870 | true, "", Flag.Glimpse ->
871 (if not (null xs)
872 then failwith "-use_glimpse can accept only one dir");
873
874 let files =
875 match glimpse_filter (!cocci_file, !Config.std_iso) x with
876 None -> get_files x
877 | Some files -> files in
878 files +> List.map (fun x -> [x])
879 | true, "", Flag.IdUtils ->
880 (if not (null xs)
881 then failwith "-id_utils can accept only one dir");
882
883 let files =
884 match idutils_filter (!cocci_file, !Config.std_iso) x with
885 None -> get_files x
886 | Some files -> files in
887 files +> List.map (fun x -> [x])
888 (* normal *)
889 | false, _, _ -> [x::xs]
890 | true, "", _ ->
891 get_files (join " " (x::xs)) +> List.map (fun x -> [x])
892
893 (* kbuild *)
894 | true, kbuild_info_file,_ ->
895 let dirs =
896 Common.cmd_to_list ("find "^(join " " (x::xs))^" -type d")
897 in
898 let info = Kbuild.parse_kbuild_info kbuild_info_file in
899 let groups = Kbuild.files_in_dirs dirs info in
900
901 groups +> List.map (function Kbuild.Group xs -> xs)
902 )
903 in
904
905 (* make cache unique in parallel case *)
906 (match (!distrib_index,!Flag_parsing_c.cache_prefix) with
907 (Some index,Some str) ->
908 Flag_parsing_c.cache_prefix :=
909 Some (Printf.sprintf "%s/d%d" str index)
910 | _ -> ());
911
912 let infiles =
913 match (!distrib_index,!distrib_max) with
914 (None,None) -> infiles
915 | (Some index,Some max) ->
916 (if index >= max
917 then
918 failwith "index starts at 0, and so must be less than max");
919 if !mod_distrib
920 then
921 let rec loop ct = function
922 [] -> []
923 | x::xs ->
924 if (ct mod max) =|= index
925 then x::(loop (ct+1) xs)
926 else loop (ct+1) xs in
927 loop 0 infiles
928 else
929 begin
930 let all_files = List.length infiles in
931 let regions = (all_files + (max - 1)) / max in
932 let this_min = index * regions in
933 let this_max = (index+1) * regions in
934 let rec loop ct = function
935 [] -> []
936 | x::xs ->
937 if this_min <= ct && ct < this_max
938 then x::(loop (ct+1) xs)
939 else loop (ct+1) xs in
940 loop 0 infiles
941 end
942 | _ -> failwith "inconsistent distribution information" in
943
944 let (cocci_infos,outfiles) =
945 Common.profile_code "Main.outfiles computation" (fun () ->
946 let cocci_infos =
947 Cocci.pre_engine (!cocci_file, !Config.std_iso) in
948 let res =
949 infiles +> List.map (fun cfiles ->
950 pr2 ("HANDLING: " ^ (join " " cfiles));
951 (*pr2 (List.hd(Common.cmd_to_list "free -m | grep Mem"));*)
952 flush stderr;
953
954 Common.timeout_function_opt !FC.timeout (fun () ->
955 Common.report_if_take_time 10 (join " " cfiles) (fun () ->
956 try
957 let optfile =
958 if !output_file <> "" && !compat_mode then
959 Some !output_file
960 else
961 None
962 in
963 adjust_stdin cfiles (fun () ->
964 Common.redirect_stdout_opt optfile (fun () ->
965 (* this is the main call *)
966 Cocci.full_engine cocci_infos cfiles
967 ))
968 with
969 | Common.UnixExit x -> raise (Common.UnixExit x)
970 | Pycocci.Pycocciexception ->
971 raise Pycocci.Pycocciexception
972 | e ->
973 if !dir
974 then begin
975 pr2 ("EXN:" ^ Printexc.to_string e);
976 [] (* *)
977 end
978 else raise e))) in
979 (cocci_infos,res)) in
980 let outfiles = List.concat outfiles in
981 (match Iteration.get_pending_instance() with
982 None ->
983 (x,xs,cocci_infos,outfiles)
984 | Some (files,virt_rules,virt_ids) ->
985 if outfiles = [] or outfiles = [] or not !FC.show_diff
986 or !inplace_modif
987 then
988 begin
989 (if !inplace_modif then generate_outfiles outfiles x xs);
990 Flag.defined_virtual_rules := virt_rules;
991 Flag.defined_virtual_env := virt_ids;
992 Common.erase_temp_files();
993 Common.clear_pr2_once();
994 distrib_index := None;
995 distrib_max := None;
996 toploop files
997 end
998 else
999 begin
1000 Common.pr2
1001 "Out of place transformation not compatible with iteration. Aborting.\n consider using -no_show_diff or -in_place";
1002 (x,xs,cocci_infos,outfiles)
1003 end) in
1004 let (x,xs,cocci_infos,outfiles) = toploop xs in
1005
1006 Cocci.post_engine cocci_infos;
1007 Common.profile_code "Main.result analysis" (fun () ->
1008 Ctlcocci_integration.print_bench();
1009 generate_outfiles outfiles x xs;
1010 if !compare_with_expected
1011 then Testing.compare_with_expected outfiles)
1012
1013 and generate_outfiles outfiles x (* front file *) xs (* other files *) =
1014 let outfiles = Cocci.check_duplicate_modif outfiles in
1015 outfiles +> List.iter (fun (infile, outopt) ->
1016 outopt +> Common.do_option (fun outfile ->
1017 if !inplace_modif
1018 then begin
1019 (match !backup_suffix with
1020 Some backup_suffix ->
1021 Common.command2 ("cp "^infile^" "^infile^backup_suffix)
1022 | None -> ());
1023 Common.command2 ("cp "^outfile^" "^infile);
1024 end;
1025
1026 if !outplace_modif
1027 then Common.command2 ("cp "^outfile^" "^infile^".cocci_res")
1028
1029 (* potential source of security pb if the /tmp/ file is
1030 * a symlink, so simpler to not produce any regular file
1031 * (files created by Common.new_temp_file are still ok)
1032 * anymore in /tmp.
1033 *)
1034 (*
1035 if !output_file =$= ""
1036 then begin
1037 let tmpfile = "/tmp/"^Common.basename infile in
1038 pr2 (spf "One file modified. Result is here: %s" tmpfile);
1039 Common.command2 ("cp "^outfile^" "^tmpfile);
1040 end
1041 *)
1042 ));
1043 if !output_file <> "" && not !compat_mode then
1044 (match outfiles with
1045 | [infile, Some outfile] when infile =$= x && null xs ->
1046 Common.command2 ("cp " ^outfile^ " " ^ !output_file)
1047 | [infile, None] when infile =$= x && null xs ->
1048 Common.command2 ("cp " ^infile^ " " ^ !output_file)
1049 | _ ->
1050 failwith
1051 ("-o can not be applied because there are multiple " ^
1052 "modified files"))
1053
1054 let fix_chars s =
1055 if (String.length s) > 2 && String.get s 0 = '-'
1056 && not (String.get s 1 = '-')
1057 then "-"^(String.concat "-" (Str.split (Str.regexp_string "_") s))
1058 else s
1059
1060 (*****************************************************************************)
1061 (* The coccinelle main entry point *)
1062 (*****************************************************************************)
1063 let main () =
1064 begin
1065 let arglist = Array.to_list Sys.argv in
1066 let arglist = Command_line.command_line arglist in
1067 let arglist = List.map fix_chars arglist in
1068
1069 let contains_cocci =
1070 (* rather a hack... don't want to think about all possible options *)
1071 List.exists
1072 (function x -> Filename.check_suffix x ".cocci")
1073 arglist &&
1074 not (List.mem "--parse-cocci" arglist) in
1075 if not (null (Common.inter_set arglist
1076 ["--cocci-file";"--sp-file";"--sp";"--test";"--testall";
1077 "--test-okfailed";"--test-regression-okfailed"]))
1078 or contains_cocci
1079 then run_profile quiet_profile;
1080
1081 let args = ref [] in
1082
1083 (* Gc.set {(Gc.get ()) with Gc.stack_limit = 1024 * 1024};*)
1084
1085 (* this call can set up many global flag variables via the cmd line *)
1086 arg_parse2 (Arg.align all_options) (fun x -> args := x::!args) usage_msg
1087 (Array.of_list arglist);
1088 args :=
1089 List.filter
1090 (function arg ->
1091 if Filename.check_suffix arg ".cocci"
1092 then
1093 begin
1094 (if !cocci_file = ""
1095 then cocci_file := arg
1096 else failwith "only one .cocci file allowed");
1097 false
1098 end
1099 else true)
1100 !args;
1101
1102 (* julia hack so that one can override directories specified on
1103 * the command line. *)
1104 (if !dir
1105 then
1106 let chosen_dir =
1107 if List.length !args > 1
1108 then
1109 begin
1110 let chosen = List.hd !args in
1111 Flag.dir := chosen;
1112 pr2 ("ignoring all but the last specified directory: "^chosen);
1113 args := [chosen];
1114 chosen
1115 end
1116 else List.hd !args in
1117 if !FC.include_path =*= []
1118 then FC.include_path := [Filename.concat chosen_dir "include"]);
1119
1120 args := List.rev !args;
1121
1122 if !cocci_file <> "" && (not (!cocci_file =~ ".*\\.\\(sgrep\\|spatch\\)$"))
1123 then cocci_file := Common.adjust_ext_if_needed !cocci_file ".cocci";
1124
1125 if !Config.std_iso <> ""
1126 then Config.std_iso := Common.adjust_ext_if_needed !Config.std_iso ".iso";
1127 if !Config.std_h <> ""
1128 then Config.std_h := Common.adjust_ext_if_needed !Config.std_h ".h";
1129
1130 if !Config.std_h <> ""
1131 then Parse_c.init_defs_builtins !Config.std_h;
1132
1133 if !macro_file <> ""
1134 then Parse_c.init_defs_macros !macro_file;
1135
1136
1137 (* must be done after Arg.parse, because Common.profile is set by it *)
1138 Common.profile_code "Main total" (fun () ->
1139
1140
1141 let all_actions = Test_parsing_c.actions() in
1142
1143 (match (!args) with
1144
1145 (* --------------------------------------------------------- *)
1146 (* The test framework. Works with tests/ or .ok and .failed *)
1147 (* --------------------------------------------------------- *)
1148 | [x] when !test_mode ->
1149 begin
1150 let prefix = "tests/" in
1151 let testfile = x ^ ".cocci" in
1152 if Sys.file_exists (prefix ^ testfile) then
1153 begin
1154 (if !FC.include_path = []
1155 then FC.include_path := [prefix^"include"]);
1156 Testing.testone prefix x !compare_with_expected
1157 end
1158 else
1159 if Sys.file_exists testfile then
1160 begin
1161 (if !FC.include_path = []
1162 then FC.include_path := ["include"]);
1163 Testing.testone "" x !compare_with_expected
1164 end
1165 else
1166 pr2 (spf "ERROR: File %s does not exist" testfile)
1167 end
1168
1169 | [] when !test_all ->
1170 (if !FC.include_path = []
1171 then FC.include_path := ["tests/include"]);
1172 if !expected_score_file <> ""
1173 then Testing.testall ~expected_score_file:!expected_score_file ()
1174 else Testing.testall ()
1175
1176 | [] when !test_regression_okfailed ->
1177 Testing.test_regression_okfailed ()
1178
1179 | ((x::xs) as cfiles) when !test_okfailed ->
1180 (* do its own timeout on FC.timeout internally *)
1181 FC.relax_include_path := true;
1182 adjust_stdin cfiles (fun () ->
1183 Testing.test_okfailed !cocci_file cfiles
1184 )
1185
1186 (* --------------------------------------------------------- *)
1187 (* Actions, useful to debug subpart of coccinelle *)
1188 (* --------------------------------------------------------- *)
1189
1190 | xs when List.mem !action (Common.action_list all_actions) ->
1191 Common.do_action !action xs all_actions
1192
1193 | [] when !action =$= "--parse-cocci" ->
1194 Testing.test_parse_cocci !cocci_file
1195
1196 (* I think this is used by some scripts in some Makefile for our
1197 * big-tests. So dont remove.
1198 *)
1199 | [file1;file2] when !action =$= "--compare-c" ->
1200 Test_parsing_c.test_compare_c file1 file2 (* result = unix code *)
1201
1202 (* could add the Test_parsing_c.test_actions such as -parse_c & co *)
1203
1204
1205 (* --------------------------------------------------------- *)
1206 (* This is the main entry *)
1207 (* --------------------------------------------------------- *)
1208 | x::xs -> main_action (x::xs)
1209
1210 (* --------------------------------------------------------- *)
1211 (* empty entry *)
1212 (* --------------------------------------------------------- *)
1213 | [] -> short_usage()
1214 ));
1215 if !Pycocci.initialised && (Pycocci.py_isinitialized ()) != 0 then begin
1216 ignore(Pycocci.pyrun_simplestring "cocci.finalise()");
1217 if !Flag.show_misc
1218 then Common.pr2 "Finalizing python\n";
1219 Pycocci.py_finalize ();
1220 end
1221 end
1222
1223
1224 let main_with_better_error_report () =
1225 if !Common.debugger then main ()
1226 else
1227 try
1228 main ()
1229 with
1230 | Unix.Unix_error (e, "stat", filename) ->
1231 pr2
1232 (spf "ERROR: File %s does not exist: %s"
1233 filename (Unix.error_message e));
1234 raise (UnixExit (-1))
1235 | Parse_cocci.Bad_virt s ->
1236 Common.pr2 (Printf.sprintf "virtual rule %s not supported" s);
1237 raise (UnixExit (-1))
1238
1239 (*****************************************************************************)
1240 let start =
1241 Common.main_boilerplate (fun () ->
1242 main_with_better_error_report ();
1243 Ctlcocci_integration.print_bench();
1244 )