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