b736b7f7a59d92f34a633bd55aefc9bd284a3666
[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 "-all_includes",
296 Arg.Unit (function _ -> FC.include_options := FC.I_ALL_INCLUDES),
297 " causes all available include files to be used";
298 "-no_includes",
299 Arg.Unit (function _ -> FC.include_options := FC.I_NO_INCLUDES),
300 " causes not even local include files to be used";
301 "-local_includes",
302 Arg.Unit (function _ -> FC.include_options := FC.I_NORMAL_INCLUDES),
303 " causes local include files to be used";
304 "-ignore_unknown_options", Arg.Set ignore_unknown_opt,
305 " For integration in a toolchain (must be set before the first unknown option)";
306 "-include_headers", Arg.Set include_headers,
307 " process header files independently";
308 "-I", Arg.String (fun x ->
309 FC.include_path:= x::!FC.include_path
310 ),
311 " <dir> containing the header files (optional)";
312
313 "-preprocess", Arg.Set preprocess,
314 " run the C preprocessor before applying the semantic match";
315
316 "-c", Arg.Set compat_mode, " gcc/cpp compatibility mode";
317
318 "-dir", Arg.Set dir,
319 " <dir> process all files in directory recursively";
320
321 "-use_glimpse", Arg.Unit (function _ -> Flag.scanner := Flag.Glimpse),
322 " works with -dir, use info generated by glimpseindex";
323 "-use_google", Arg.String (function s -> Flag.scanner := Flag.Google s),
324 " find relevant files using google code search";
325 "-patch",
326 Arg.String (function s -> Flag.patch := Some (Cocci.normalize_path s)),
327 (" <dir> path name with respect to which a patch should be created\n"^
328 " \"\" for a file in the current directory");
329 "-kbuild_info", Arg.Set_string kbuild_info,
330 " <file> improve -dir by grouping related c files";
331 "-pyoutput", Arg.Set_string Flag.pyoutput,
332 " Sets output routine: Standard values: <coccilib.output.Gtk|coccilib.output.Console>";
333
334
335 "-version", Arg.Unit (fun () ->
336 let withpython = if Pycocci.python_support then "with" else "without" in
337 pr2 (spf "spatch version %s %s Python support" Config.version withpython);
338 exit 0;
339 ),
340 " guess what";
341
342 "-date", Arg.Unit (fun () ->
343 pr2 "version: $Date: 2010/09/04 10:20:49 $";
344 raise (Common.UnixExit 0)
345 ),
346 " guess what";
347
348 "-shorthelp", Arg.Unit (fun () ->
349 !short_usage_func();
350 raise (Common.UnixExit 0)
351 ),
352 " see short list of options";
353 "-longhelp", Arg.Unit (fun () ->
354 !long_usage_func();
355 raise (Common.UnixExit 0)
356 ),
357 " see all the available options in different categories";
358 "-help", Arg.Unit (fun () ->
359 !long_usage_func();
360 raise (Common.UnixExit 0)
361 ),
362 " ";
363 "--help", Arg.Unit (fun () ->
364 !long_usage_func();
365 raise (Common.UnixExit 0)
366 ),
367 " ";
368 ]
369
370 (* the format is a list of triples:
371 * (title of section * (optional) explanation of sections * option list)
372 *)
373 let other_options = [
374 "aliases and obsolete options",
375 "",
376 [
377 "-sp", Arg.Set_string cocci_file, " short option of -sp_file";
378 "-iso", Arg.Set_string Config.std_iso, " short option of -iso_file";
379
380 "-cocci_file", Arg.Set_string cocci_file,
381 " <file> the semantic patch file";
382 (* "-c", Arg.Set_string cocci_file, " short option of -sp_file"; *)
383 ];
384
385 "most useful show options",
386 "",
387 [
388 "-show_diff" , Arg.Set FC.show_diff, " ";
389 "-no_show_diff" , Arg.Clear FC.show_diff, " ";
390 "-show_flow" , Arg.Set FC.show_flow, " ";
391 (* works in conjunction with -show_ctl_text *)
392 "-ctl_inline_let",
393 Arg.Unit
394 (function _ -> FC.show_ctl_text := true; FC.inline_let_ctl := true), " ";
395 "-ctl_show_mcodekind",
396 Arg.Unit
397 (function _ -> FC.show_ctl_text := true; FC.show_mcodekind_in_ctl := true),
398 " ";
399 "-show_bindings", Arg.Set FC.show_binding_in_out, " ";
400 "-show_transinfo", Arg.Set Flag.show_transinfo, " ";
401 "-show_misc", Arg.Set Flag.show_misc, " ";
402 "-show_trying", Arg.Set Flag.show_trying,
403 " show the name of each function being processed";
404 "-show_dependencies",
405 Arg.Unit (function _ -> FC.show_dependencies := true;
406 FC.show_binding_in_out := true),
407 " show the dependencies related to each rule";
408 ];
409
410 "verbose subsystems options",
411 "",
412 [
413 "-verbose_ctl_engine",
414 Arg.Unit (function _ ->
415 Flag_ctl.verbose_ctl_engine := true; FC.show_ctl_text := true) , " ";
416 "-verbose_match", Arg.Set Flag_ctl.verbose_match, " ";
417 "-verbose_engine", Arg.Set Flag_matcher.debug_engine, " ";
418 "-graphical_trace", Arg.Set Flag_ctl.graphical_trace, " generate a pdf file representing the matching process";
419 "-gt_without_label",
420 Arg.Unit (function _ ->
421 Flag_ctl.graphical_trace := true; Flag_ctl.gt_without_label := true),
422 " remove graph label (requires option -graphical_trace)";
423
424 "-parse_error_msg", Arg.Set Flag_parsing_c.show_parsing_error, " ";
425 "-verbose_parsing",
426 Arg.Unit (fun _ -> Flag_parsing_c.verbose_parsing := true;
427 Flag_parsing_c.show_parsing_error := true), " ";
428 "-type_error_msg", Arg.Set Flag_parsing_c.verbose_type, " ";
429 (* could also use Flag_parsing_c.options_verbose *)
430 ];
431
432 "other show options",
433 "",
434 [
435 "-show_c" , Arg.Set FC.show_c, " ";
436 "-show_cocci" , Arg.Set FC.show_cocci, " ";
437 "-show_before_fixed_flow" , Arg.Set FC.show_before_fixed_flow, " ";
438 "-show_ctl_tex" , Arg.Set FC.show_ctl_tex, " ";
439 "-show_ctl_text" , Arg.Set FC.show_ctl_text, " ";
440 "-show_SP" , Arg.Set Flag_parsing_cocci.show_SP, " ";
441 ];
442
443
444 "debug C parsing/unparsing",
445 "",
446 [
447 "-debug_cpp", Arg.Set Flag_parsing_c.debug_cpp, " ";
448 "-debug_lexer", Arg.Set Flag_parsing_c.debug_lexer , " ";
449 "-debug_etdt", Arg.Set Flag_parsing_c.debug_etdt , " ";
450 "-debug_typedef", Arg.Set Flag_parsing_c.debug_typedef, " ";
451
452 "-filter_msg", Arg.Set Flag_parsing_c.filter_msg ,
453 " filter some cpp message when the macro is a \"known\" cpp construct";
454 "-filter_define_error", Arg.Set Flag_parsing_c.filter_define_error," ";
455 "-filter_msg_define_error", Arg.Set Flag_parsing_c.filter_msg_define_error,
456 " filter the error msg";
457 "-filter_passed_level", Arg.Set_int Flag_parsing_c.filter_passed_level," ";
458 (* debug cfg doesn't seem to have any effect, so drop it as an option *)
459 (* "-debug_cfg", Arg.Set Flag_parsing_c.debug_cfg , " "; *)
460 "-debug_unparsing", Arg.Set Flag_parsing_c.debug_unparsing, " ";
461
462 ];
463 (* could use Flag_parsing_c.options_debug_with_title instead *)
464
465
466 "shortcut for enabling/disabling a set of debugging options at once",
467 "",
468 [
469 (* todo: other profile ? *)
470 "-quiet", Arg.Unit (fun () -> run_profile quiet_profile), " ";
471 "-very_quiet", Arg.Unit (fun () -> run_profile very_quiet_profile), " ";
472 "-debug", Arg.Unit (fun () -> run_profile debug_profile), " ";
473 "-pad", Arg.Unit (fun () -> run_profile pad_profile), " ";
474
475 ];
476
477 "bench options",
478 "",
479 [
480 "-profile", Arg.Unit (function () -> Common.profile := Common.PALL) ,
481 " gather timing information about the main coccinelle functions";
482 "-bench", Arg.Int (function x -> Flag_ctl.bench := x),
483 " <level> for profiling the CTL engine";
484 "-timeout", Arg.Int (fun x -> FC.timeout := Some x),
485 " <sec> timeout in seconds";
486 "-steps", Arg.Int (fun x -> Flag_ctl.steps := Some x),
487 " max number of model checking steps per code unit";
488 "-iso_limit", Arg.Int (fun x -> Flag_parsing_cocci.iso_limit := Some x),
489 " max depth of iso application";
490 "-no_iso_limit", Arg.Unit (fun _ -> Flag_parsing_cocci.iso_limit := None),
491 " disable limit on max depth of iso application";
492 "-track_iso", Arg.Set Flag.track_iso_usage,
493 " gather information about isomorphism usage";
494 "-disable_iso",
495 Arg.String
496 (fun s -> Flag_parsing_cocci.disabled_isos :=
497 s :: !Flag_parsing_cocci.disabled_isos),
498 " disable a specific isomorphism";
499 "-profile_iso",
500 Arg.Unit
501 (function () ->
502 Common.profile :=
503 (*post_engine not included, because it doesn't use isos*)
504 PSOME ["parse cocci";"mysat";"asttoctl2";"pre_engine";"full_engine"]),
505 " gather information about the cost of isomorphism usage"
506 ];
507
508
509
510 "change of algorithm options",
511 "",
512 [
513 "-popl", Arg.Set FC.popl,
514 " simplified SmPL, for the popl paper";
515
516 "-popl_mark_all",
517 Arg.Unit
518 (function _ -> FC.popl := true; Flag_popl.mark_all := true),
519 " simplified SmPL, for the popl paper";
520
521 "-popl_keep_all_wits",
522 Arg.Unit
523 (function _ -> FC.popl := true; Flag_popl.keep_all_wits := true),
524 " simplified SmPL, for the popl paper";
525
526 "-hrule", Arg.String
527 (function s ->
528 Flag.make_hrule := Some s; FC.include_options := FC.I_NO_INCLUDES),
529 " semantic patch generation";
530
531 "-keep_comments", Arg.Set Flag_parsing_c.keep_comments,
532 " keep comments around removed code";
533
534 "-loop", Arg.Set Flag_ctl.loop_in_src_code, " ";
535 "-no_loops", Arg.Set Flag_parsing_c.no_loops,
536 " drop all back edges derived from looping constructs - unsafe";
537 "-no_gotos", Arg.Set Flag_parsing_c.no_gotos,
538 " drop all jumps derived from gotos - unsafe";
539
540 "-l1", Arg.Clear Flag_parsing_c.label_strategy_2, " ";
541 "-ifdef_to_if", Arg.Set FC.ifdef_to_if,
542 " convert ifdef to if (experimental)";
543 "-no_ifdef_to_if", Arg.Clear FC.ifdef_to_if,
544 " convert ifdef to if (experimental)";
545
546 "-disable_multi_pass", Arg.Set Flag_parsing_c.disable_multi_pass, " ";
547
548 "-noif0_passing", Arg.Clear Flag_parsing_c.if0_passing,
549 " ";
550 "-noadd_typedef_root", Arg.Clear Flag_parsing_c.add_typedef_root, " ";
551 (* could use Flag_parsing_c.options_algo instead *)
552
553
554 "-disallow_nested_exps", Arg.Set Flag_matcher.disallow_nested_exps,
555 " disallow an expresion pattern from matching a term and its subterm";
556 "-disable_worth_trying_opt", Arg.Clear FC.worth_trying_opt,
557 " ";
558 "-only_return_is_error_exit",
559 Arg.Set Flag_matcher.only_return_is_error_exit,
560 "if this flag is not set, then break and continue are also error exits";
561 (* the following is a hack to make it easier to add code in sgrep-like
562 code, essentially to compensate for the fact that we don't have
563 any way of printing things out *)
564 "-allow_inconsistent_paths",
565 Arg.Set Flag_matcher.allow_inconsistent_paths,
566 " if this flag is set don't check for inconsistent paths; dangerous";
567 "-no_safe_expressions",
568 Arg.Set Flag_matcher.no_safe_expressions,
569 " make an expression disjunction not prioritise the topmost disjunct";
570 "-int_bits", Arg.Int Flag_parsing_c.set_int_bits,
571 " the number of bits in an unsigned int";
572 "-long_bits", Arg.Int Flag_parsing_c.set_long_bits,
573 " the number of bits in an unsigned long";
574 "-linux_spacing", Arg.Unit Flag_parsing_c.set_linux_spacing,
575 " spacing of + code follows the conventions of Linux";
576 "-smpl_spacing", Arg.Unit Flag_parsing_c.set_smpl_spacing,
577 " spacing of + code follows the semantic patch";
578 "-D", Arg.String Flag.set_defined_virtual_rules,
579 " indicate that a virtual rule should be considered to be matched";
580 ];
581
582 "misc options",
583 "",
584 [
585 "-debugger", Arg.Set Common.debugger,
586 " option to set if launch spatch in ocamldebug";
587 "-disable_once", Arg.Set Common.disable_pr2_once,
588 " to print more messages";
589 "-show_trace_profile", Arg.Set Common.show_trace_profile,
590 " show trace";
591 "-save_tmp_files", Arg.Set Common.save_tmp_files, " ";
592 ];
593
594 "concurrency",
595 "",
596 [
597 "-index", Arg.Int (function x -> distrib_index := Some x) ,
598 " the processor to use for this run of spatch";
599 "-max", Arg.Int (function x -> distrib_max := Some x) ,
600 " the number of processors available";
601 "-mod_distrib", Arg.Set mod_distrib,
602 " use mod to distribute files among the processors";
603 ];
604
605 "pad options",
606 "",
607 [
608 "-use_cache", Arg.Set Flag_parsing_c.use_cache,
609 " use .ast_raw pre-parsed cached C file";
610 (* could use Flag_parsing_c.options_pad instead *)
611 ];
612
613
614
615 "test mode and test options (works with tests/ or .ok files)",
616 "The test options don't work with the -sp_file and so on.",
617 [
618 "-test", Arg.Set test_mode,
619 " <file> launch spatch on tests/file.[c,cocci]";
620 "-testall", Arg.Set test_all,
621 " launch spatch on all files in tests/ having a .res";
622 "-test_okfailed", Arg.Set test_okfailed,
623 " generates .{ok,failed,spatch_ok} files using .res files";
624 "-test_regression_okfailed", Arg.Set test_regression_okfailed,
625 " process the .{ok,failed,spatch_ok} files in current dir";
626
627 "-compare_with_expected", Arg.Set compare_with_expected,
628 " use also file.res";
629 "-expected_score_file", Arg.Set_string expected_score_file,
630 " which score file to compare with in -testall";
631 "-relax_include_path", Arg.Set FC.relax_include_path,
632 " ";
633 ];
634
635 "action mode",
636 ("The action options don't work with the -sp_file and so on." ^ "\n" ^
637 "It's for the other (internal) uses of the spatch program."
638 ),
639
640 (* -token_c, -parse_c, etc *)
641 ((Common.options_of_actions action (Test_parsing_c.actions())) ++
642 [
643 (let s = "-parse_cocci" in s, Arg.Unit (fun () -> action := s),
644 " <file>");
645 (let s = "-compare_c" in s, Arg.Unit (fun () -> action := s),
646 " <file1> <file2>");
647 ]);
648 ]
649
650
651 let all_options =
652 short_options ++ List.concat (List.map Common.thd3 other_options)
653
654 (* I don't want the -help and --help that are appended by Arg.align *)
655 let arg_align2 xs =
656 Arg.align xs +> List.rev +> Common.drop 2 +> List.rev
657
658 (*
659 Ignore unknown option
660
661 This simplifies the integration of Coccinelle in toolchain. For
662 instance, spatch can then be used as a checker in the Linux build
663 system.
664
665 *)
666 let check_include_path () =
667 let opt = Array.get Sys.argv !Arg.current in
668 let is_include_re = Str.regexp "-I\\(.*\\)" in
669 if Str.string_match is_include_re opt 0 then
670 let path = Str.matched_group 1 opt in
671 FC.include_path:= path::!FC.include_path
672 else ()
673
674 let rec arg_parse_no_fail l f msg =
675 try
676 check_include_path ();
677 Arg.parse_argv Sys.argv l f msg;
678 with
679 | Arg.Bad emsg ->
680 arg_parse_no_fail l f msg
681 | Arg.Help msg -> (* printf "%s" msg; exit 0; *)
682 raise Impossible (* -help is specified in speclist *)
683
684 (* copy paste of Arg.parse. Don't want the default -help msg *)
685 let arg_parse2 l f msg =
686 (try
687 Arg.parse_argv Sys.argv l f msg;
688 with
689 | Arg.Bad emsg -> (* eprintf "%s" msg; exit 2; *)
690 if not !ignore_unknown_opt then
691 begin
692 let xs = Common.lines emsg in
693 (* take only head, it's where the error msg is *)
694 pr2 (List.hd xs);
695 !short_usage_func();
696 raise (Common.UnixExit (2))
697 end
698 else
699 arg_parse_no_fail l f msg;
700 | Arg.Help msg -> (* printf "%s" msg; exit 0; *)
701 raise Impossible (* -help is specified in speclist *)
702 )
703
704
705 let short_usage () =
706 begin
707 Common.short_usage usage_msg short_options;
708 pr2 "";
709 pr2 "Example of use:";
710 pr2 " ./spatch -sp_file foo.cocci foo.c -o /tmp/newfoo.c";
711 pr2 "";
712 end
713
714
715 let long_usage () =
716 Common.long_usage usage_msg short_options other_options
717
718 let _ = short_usage_func := short_usage
719 let _ = long_usage_func := long_usage
720
721 (*****************************************************************************)
722 (* Helpers *)
723 (*****************************************************************************)
724
725 let adjust_stdin cfile k =
726 if !dir
727 then k()
728 else
729 let newin =
730 try
731 let (dir, base, ext) = Common.dbe_of_filename cfile in
732 let varfile = Common.filename_of_dbe (dir, base, "var") in
733 if ext =$= "c" && Common.lfile_exists varfile
734 then Some varfile
735 else None
736 with Invalid_argument("Filename.chop_extension") -> None
737 in
738 Common.redirect_stdin_opt newin k
739
740 let glimpse_filter (coccifile, isofile) dir =
741 let (_metavars,astcocci,_free_var_lists,_negated_positions,
742 _used_after_lists,_positions_lists,_,query) =
743 Cocci.sp_of_file coccifile (Some isofile) in
744 match query with
745 None -> pr2 "no glimpse keyword inferred from snippet"; None
746 | Some queries ->
747 let suffixes = if !include_headers then ["c";"h"] else ["c"] in
748 let rec loop = function
749 [] -> None (* error, eg due to pattern too big *)
750 | query::queries ->
751 Printf.fprintf stderr "%s\n" ("glimpse request = " ^ query);
752 let command = spf "glimpse -y -H %s -N -W -w '%s'" dir query in
753 let (glimpse_res,stat) = Common.cmd_to_list_and_status command in
754 match stat with
755 Unix.WEXITED(0) | Unix.WEXITED(1) ->
756 Some
757 (glimpse_res +>
758 List.filter
759 (fun file -> List.mem (Common.filesuffix file) suffixes))
760 | _ -> loop queries (* error, eg due to pattern too big *) in
761 loop queries
762
763 (*****************************************************************************)
764 (* Main action *)
765 (*****************************************************************************)
766
767 let main_action xs =
768 match xs with
769 | x::xs ->
770
771 (* a more general solution would be to use
772 * Common.files_of_dir_or_files (x::xs)
773 * as some elements in xs may also be directories, or individual
774 * files.
775 *)
776 if Common.is_directory x
777 then dir := true;
778
779 adjust_stdin x (fun () ->
780 if !cocci_file =$= ""
781 then failwith "I need a cocci file, use -sp_file <file>";
782
783 if !dir && !Flag.patch =*= None
784 then
785 (match xs with
786 | [] -> Flag.patch := Some (Cocci.normalize_path x)
787 | _ ->
788 pr2
789 ("warning: patch output can only be created when only one\n"^
790 "directory is specified or when the -patch flag is used")
791 );
792 Flag.dir := x;
793
794 let infiles =
795 Common.profile_code "Main.infiles computation" (fun () ->
796 match !dir, !kbuild_info, !Flag.scanner = Flag.Glimpse with
797 (* glimpse *)
798 | false, _, true ->
799 failwith "-use_glimpse works only with -dir"
800 | true, s, true when s <> "" ->
801 failwith "-use_glimpse does not work with -kbuild"
802 | true, "", true ->
803 if not (null xs)
804 then failwith "-use_glimpse can accept only one dir";
805
806 let files =
807 match glimpse_filter (!cocci_file, !Config.std_iso) x with
808 None ->
809 Common.cmd_to_list (* same as "true, "", _" case *)
810 (if !include_headers
811 (* FIXME : Could we remove xs ?
812 -use_glimpse requires a singleton.
813 This is checked some lines before.
814 then ("find "^(join " " (x::xs))^" -name \"*.[ch]\"")
815 else ("find "^(join " " (x::xs))^" -name \"*.c\""))
816 *)
817 then ("find "^ x ^" -name \"*.[ch]\"")
818 else ("find "^ x ^" -name \"*.c\""))
819 | Some files -> files in
820 files +> List.map (fun x -> [x])
821 (* normal *)
822 | false, _, _ -> [x::xs]
823 | true, "", _ ->
824 Common.cmd_to_list
825 (if !include_headers
826 then ("find "^(join " " (x::xs))^" -name \"*.[ch]\"")
827 else ("find "^(join " " (x::xs))^" -name \"*.c\""))
828 +> List.map (fun x -> [x])
829
830 (* kbuild *)
831 | true, kbuild_info_file,_ ->
832 let dirs =
833 Common.cmd_to_list ("find "^(join " " (x::xs))^" -type d")
834 in
835 let info = Kbuild.parse_kbuild_info kbuild_info_file in
836 let groups = Kbuild.files_in_dirs dirs info in
837
838 groups +> List.map (function Kbuild.Group xs -> xs)
839 )
840 in
841
842 let infiles =
843 match (!distrib_index,!distrib_max) with
844 (None,None) -> infiles
845 | (Some index,Some max) ->
846 (if index >= max
847 then
848 failwith "index starts at 0, and so must be less than max");
849 if !mod_distrib
850 then
851 let rec loop ct = function
852 [] -> []
853 | x::xs ->
854 if (ct mod max) =|= index
855 then x::(loop (ct+1) xs)
856 else loop (ct+1) xs in
857 loop 0 infiles
858 else
859 begin
860 let all_files = List.length infiles in
861 let regions = (all_files + (max - 1)) / max in
862 let this_min = index * regions in
863 let this_max = (index+1) * regions in
864 let rec loop ct = function
865 [] -> []
866 | x::xs ->
867 if this_min <= ct && ct < this_max
868 then x::(loop (ct+1) xs)
869 else loop (ct+1) xs in
870 loop 0 infiles
871 end
872 | _ -> failwith "inconsistent distribution information" in
873
874 let outfiles =
875 Common.profile_code "Main.outfiles computation" (fun () ->
876 let cocci_infos =
877 Cocci.pre_engine (!cocci_file, !Config.std_iso) in
878 let res =
879 infiles +> List.map (fun cfiles ->
880 pr2 ("HANDLING: " ^ (join " " cfiles));
881 Common.timeout_function_opt !FC.timeout (fun () ->
882 Common.report_if_take_time 10 (join " " cfiles) (fun () ->
883 (*let s = profile_diagnostic() in*)
884 (* Unix.sleep 1; *)
885 try
886 let optfile =
887 if !output_file <> "" && !compat_mode then
888 Some !output_file
889 else
890 None
891 in
892 Common.redirect_stdout_opt optfile (fun () ->
893 (* this is the main call *)
894 Cocci.full_engine cocci_infos cfiles
895 )
896 with
897 | Common.UnixExit x -> raise (Common.UnixExit x)
898 | Pycocci.Pycocciexception ->
899 raise Pycocci.Pycocciexception
900 | e ->
901 (*pr2 "previous";
902 pr2 s;
903 pr2 "new";
904 pr2(profile_diagnostic());*)
905 if !dir
906 then begin
907 pr2 ("EXN:" ^ Printexc.to_string e);
908 [] (* *)
909 end
910 else raise e))) in
911 Cocci.post_engine cocci_infos;
912 res
913 ) +> List.concat
914 in
915
916 Common.profile_code "Main.result analysis" (fun () ->
917 Ctlcocci_integration.print_bench();
918 let outfiles = Cocci.check_duplicate_modif outfiles in
919 outfiles +> List.iter (fun (infile, outopt) ->
920 outopt +> Common.do_option (fun outfile ->
921 if !inplace_modif
922 then begin
923 (match !backup_suffix with
924 Some backup_suffix ->
925 Common.command2 ("cp "^infile^" "^infile^backup_suffix)
926 | None -> ());
927 Common.command2 ("cp "^outfile^" "^infile);
928 end;
929
930 if !outplace_modif
931 then Common.command2 ("cp "^outfile^" "^infile^".cocci_res");
932
933 (* potential source of security pb if the /tmp/ file is
934 * a symlink, so simpler to not produce any regular file
935 * (files created by Common.new_temp_file are still ok)
936 * anymore in /tmp.
937 *)
938 (*
939 if !output_file =$= ""
940 then begin
941 let tmpfile = "/tmp/"^Common.basename infile in
942 pr2 (spf "One file modified. Result is here: %s" tmpfile);
943 Common.command2 ("cp "^outfile^" "^tmpfile);
944 end
945 *)
946 ));
947 if !output_file <> "" && not !compat_mode then
948 (match outfiles with
949 | [infile, Some outfile] when infile =$= x && null xs ->
950 Common.command2 ("cp " ^outfile^ " " ^ !output_file);
951 | [infile, None] when infile =$= x && null xs ->
952 Common.command2 ("cp " ^infile^ " " ^ !output_file);
953 | _ ->
954 failwith
955 ("-o can not be applied because there is multiple " ^
956 "modified files");
957 );
958 if !compare_with_expected
959 then Testing.compare_with_expected outfiles))
960
961 | [] -> raise Impossible
962
963
964 (*****************************************************************************)
965 (* The coccinelle main entry point *)
966 (*****************************************************************************)
967 let main () =
968 begin
969 let arglist = Array.to_list Sys.argv in
970
971 if not (null (Common.inter_set arglist
972 ["-cocci_file";"-sp_file";"-sp";"-test";"-testall";
973 "-test_okfailed";"-test_regression_okfailed"]))
974 then run_profile quiet_profile;
975
976 let args = ref [] in
977
978 (* Gc.set {(Gc.get ()) with Gc.stack_limit = 1024 * 1024};*)
979
980 (* this call can set up many global flag variables via the cmd line *)
981 arg_parse2 (Arg.align all_options) (fun x -> args := x::!args) usage_msg;
982
983 (* julia hack so that one can override directories specified on
984 * the command line. *)
985 (if !dir
986 then
987 let chosen_dir =
988 if List.length !args > 1
989 then
990 begin
991 let chosen = List.hd !args in
992 Flag.dir := chosen;
993 pr2 ("ignoring all but the last specified directory: "^chosen);
994 args := [chosen];
995 chosen
996 end
997 else List.hd !args in
998 if !FC.include_path =*= []
999 then FC.include_path := [Filename.concat chosen_dir "include"]);
1000
1001 args := List.rev !args;
1002
1003 if !cocci_file <> "" && (not (!cocci_file =~ ".*\\.\\(sgrep\\|spatch\\)$"))
1004 then cocci_file := Common.adjust_ext_if_needed !cocci_file ".cocci";
1005
1006 if !Config.std_iso <> ""
1007 then Config.std_iso := Common.adjust_ext_if_needed !Config.std_iso ".iso";
1008 if !Config.std_h <> ""
1009 then Config.std_h := Common.adjust_ext_if_needed !Config.std_h ".h";
1010
1011 if !Config.std_h <> ""
1012 then Parse_c.init_defs_builtins !Config.std_h;
1013
1014 if !macro_file <> ""
1015 then Parse_c.init_defs_macros !macro_file;
1016
1017
1018 (* must be done after Arg.parse, because Common.profile is set by it *)
1019 Common.profile_code "Main total" (fun () ->
1020
1021
1022 let all_actions = Test_parsing_c.actions() in
1023
1024 (match (!args) with
1025
1026 (* --------------------------------------------------------- *)
1027 (* The test framework. Works with tests/ or .ok and .failed *)
1028 (* --------------------------------------------------------- *)
1029 | [x] when !test_mode ->
1030 begin
1031 let prefix = "tests/" in
1032 let testfile = x ^ ".cocci" in
1033 if Sys.file_exists (prefix ^ testfile) then
1034 begin
1035 FC.include_path := [prefix^"include"];
1036 Testing.testone prefix x !compare_with_expected
1037 end
1038 else
1039 if Sys.file_exists testfile then
1040 begin
1041 FC.include_path := ["include"];
1042 Testing.testone "" x !compare_with_expected
1043 end
1044 else
1045 pr2 (spf "ERROR: File %s does not exist" testfile)
1046 end
1047
1048 | [] when !test_all ->
1049 FC.include_path := ["tests/include"];
1050 if !expected_score_file <> ""
1051 then Testing.testall ~expected_score_file:!expected_score_file ()
1052 else Testing.testall ()
1053
1054 | [] when !test_regression_okfailed ->
1055 Testing.test_regression_okfailed ()
1056
1057 | x::xs when !test_okfailed ->
1058 (* do its own timeout on FC.timeout internally *)
1059 FC.relax_include_path := true;
1060 adjust_stdin x (fun () ->
1061 Testing.test_okfailed !cocci_file (x::xs)
1062 )
1063
1064 (* --------------------------------------------------------- *)
1065 (* Actions, useful to debug subpart of coccinelle *)
1066 (* --------------------------------------------------------- *)
1067
1068 | xs when List.mem !action (Common.action_list all_actions) ->
1069 Common.do_action !action xs all_actions
1070
1071 | [file] when !action =$= "-parse_cocci" ->
1072 Testing.test_parse_cocci file
1073
1074 (* I think this is used by some scripts in some Makefile for our
1075 * big-tests. So dont remove.
1076 *)
1077 | [file1;file2] when !action =$= "-compare_c" ->
1078 Test_parsing_c.test_compare_c file1 file2 (* result = unix code *)
1079
1080 (* could add the Test_parsing_c.test_actions such as -parse_c & co *)
1081
1082
1083 (* --------------------------------------------------------- *)
1084 (* This is the main entry *)
1085 (* --------------------------------------------------------- *)
1086 | x::xs -> main_action (x::xs)
1087
1088 (* --------------------------------------------------------- *)
1089 (* empty entry *)
1090 (* --------------------------------------------------------- *)
1091 | [] -> short_usage()
1092 ));
1093 if !Pycocci.initialised && (Pycocci.py_isinitialized ()) != 0 then begin
1094 ignore(Pycocci.pyrun_simplestring "cocci.finalise()");
1095 if !Flag.show_misc
1096 then Common.pr2 "Finalizing python\n";
1097 Pycocci.py_finalize ();
1098 end
1099 end
1100
1101
1102 let main_with_better_error_report () =
1103 if !Common.debugger then main ()
1104 else
1105 try
1106 main ()
1107 with
1108 | Unix.Unix_error (e, "stat", filename) ->
1109 pr2
1110 (spf "ERROR: File %s does not exist: %s"
1111 filename (Unix.error_message e));
1112 raise (UnixExit (-1))
1113 | Parse_cocci.Bad_virt s ->
1114 Common.pr2 (Printf.sprintf "virtual rule %s not supported" s);
1115 raise (UnixExit (-1))
1116
1117 (*****************************************************************************)
1118 let start =
1119 Common.main_boilerplate (fun () ->
1120 main_with_better_error_report ();
1121 Ctlcocci_integration.print_bench();
1122 )