Release coccinelle-0.1.8
[bpt/coccinelle.git] / main.ml
CommitLineData
34e49164 1(*
faf9a90c 2* Copyright 2005-2009, Ecole des Mines de Nantes, University of Copenhagen
34e49164
C
3* Yoann Padioleau, Julia Lawall, Rene Rydhof Hansen, Henrik Stuart, Gilles Muller
4* This file is part of Coccinelle.
5*
6* Coccinelle is free software: you can redistribute it and/or modify
7* it under the terms of the GNU General Public License as published by
8* the Free Software Foundation, according to version 2 of the License.
9*
10* Coccinelle is distributed in the hope that it will be useful,
11* but WITHOUT ANY WARRANTY; without even the implied warranty of
12* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13* GNU General Public License for more details.
14*
15* You should have received a copy of the GNU General Public License
16* along with Coccinelle. If not, see <http://www.gnu.org/licenses/>.
17*
18* The authors reserve the right to distribute this or future versions of
19* Coccinelle under other licenses.
20*)
21
22
23open Common
faf9a90c 24module FC = Flag_cocci
34e49164
C
25
26(*****************************************************************************)
27(* Flags *)
28(*****************************************************************************)
29
30(* In addition to flags that can be tweaked via -xxx options (cf the
31 * full list of options in "the spatch options" section below), the
32 * spatch program also depends on external files, described in
33 * globals/config.ml, mainly a standard.h and standard.iso file *)
34
35let cocci_file = ref ""
36
37let output_file = ref ""
38let inplace_modif = ref false (* but keeps a .cocci_orig *)
39let outplace_modif = ref false (* generates a .cocci_res *)
40
708f4980 41(* somehow obsolete now *)
34e49164
C
42let dir = ref false
43
44let include_headers = ref false
45let kbuild_info = ref ""
46
708f4980
C
47let macro_file = ref ""
48
34e49164
C
49(* test mode *)
50let test_mode = ref false
51let test_all = ref false
52let test_okfailed = ref false
53let test_regression_okfailed = ref false
708f4980 54let expected_score_file = ref ""
34e49164
C
55
56
57(* action mode *)
58let action = ref ""
59
60(* works with -test but also in "normal" spatch mode *)
61let compare_with_expected = ref false
62
34e49164
C
63let distrib_index = ref (None : int option)
64let distrib_max = ref (None : int option)
65let mod_distrib = ref false
66
67
68(*****************************************************************************)
69(* Profiles *)
70(*****************************************************************************)
71
72(* pair of (list of flags to set true, list of flags to set false *)
73let quiet_profile = (
74 [
75 ],
76 [
faf9a90c 77 (* FC.show_diff; just leave this as it is *)
34e49164
C
78
79 Flag.show_misc;
80 Flag.show_trying;
faf9a90c 81 Flag.show_transinfo;
34e49164 82
faf9a90c
C
83 FC.show_c;
84 FC.show_cocci;
85 FC.show_flow;
86 FC.show_before_fixed_flow;
87 FC.show_ctl_tex;
88 FC.show_ctl_text;
89 FC.show_binding_in_out;
34e49164 90
708f4980
C
91 FC.verbose_cocci;
92
93 Flag_parsing_c.show_parsing_error;
94
95 Flag_parsing_c.verbose_lexing;
96 Flag_parsing_c.verbose_parsing;
97 Flag_parsing_c.verbose_type;
98 Flag_parsing_c.verbose_cfg;
99 Flag_parsing_c.verbose_unparsing;
100 Flag_parsing_c.verbose_visit;
101
102 Flag_matcher.verbose_matcher;
103 Flag_matcher.debug_engine;
104
105 Flag_parsing_c.debug_unparsing;
106
34e49164
C
107 Flag_parsing_cocci.show_SP;
108 Flag_parsing_cocci.show_iso_failures;
708f4980 109
34e49164
C
110 Flag_ctl.verbose_ctl_engine;
111 Flag_ctl.verbose_match;
708f4980
C
112
113
34e49164
C
114 ])
115
faf9a90c
C
116(* some information that is useful in seeing why a semantic patch doesn't
117work properly *)
118let debug_profile = (
119 [
120 Flag.show_misc;
708f4980
C
121 Flag.show_transinfo;
122
faf9a90c
C
123 FC.show_diff;
124 FC.show_cocci;
125 FC.show_binding_in_out;
126 FC.show_dependencies;
708f4980 127
faf9a90c 128 Flag_parsing_cocci.show_iso_failures;
708f4980
C
129
130 FC.verbose_cocci;
131
132 Flag_parsing_c.verbose_cfg;
133 Flag_parsing_c.verbose_unparsing;
134 Flag_parsing_c.verbose_visit;
135
136 Flag_matcher.verbose_matcher;
137
138 Flag_parsing_c.show_parsing_error;
faf9a90c
C
139 ],
140 [
141
142 Flag.show_misc;
143
144 FC.show_c;
145 FC.show_flow;
146 FC.show_before_fixed_flow;
147 FC.show_ctl_tex;
148 FC.show_ctl_text;
149
150 Flag_parsing_cocci.show_SP;
151 Flag_ctl.verbose_ctl_engine;
152 Flag_ctl.verbose_match;
153 Flag_matcher.debug_engine;
154 Flag_parsing_c.debug_unparsing;
155 Flag_parsing_c.verbose_type;
156 Flag_parsing_c.verbose_parsing;
157 ])
158
34e49164
C
159let pad_profile = (
160 [
faf9a90c 161 FC.show_diff;
34e49164
C
162 ],
163 [
164
165 Flag.show_misc;
faf9a90c 166 Flag.show_transinfo;
34e49164 167
faf9a90c
C
168 FC.show_c;
169 FC.show_cocci;
170 FC.show_flow;
171 FC.show_before_fixed_flow;
172 FC.show_ctl_tex;
173 FC.show_ctl_text;
174 FC.show_binding_in_out;
34e49164
C
175
176 Flag_parsing_cocci.show_SP;
177 Flag_parsing_cocci.show_iso_failures;
178 Flag_ctl.verbose_ctl_engine;
179 Flag_ctl.verbose_match;
485bce71 180 Flag_matcher.debug_engine;
34e49164
C
181 Flag_parsing_c.debug_unparsing;
182 Flag_parsing_c.verbose_type;
183 Flag_parsing_c.verbose_parsing;
184 ])
185
faf9a90c
C
186let run_profile p =
187 let (set_to_true, set_to_false) = p in
188 List.iter (fun x -> x := false) set_to_false;
189 List.iter (fun x -> x := true) set_to_true
190
34e49164
C
191(*****************************************************************************)
192(* The spatch options *)
193(*****************************************************************************)
194
195let usage_msg =
196 "Usage: " ^ basename Sys.argv.(0) ^
197 " -sp_file <SP> <infile> [-o <outfile>] [-iso_file <iso>] [options]" ^
198 "\n" ^ "Options are:"
199
200(* forward reference trick *)
201let short_usage_func = ref (fun () -> ())
202let long_usage_func = ref (fun () -> ())
203
204
205(* The short_options are user-oriented. The other options are for
206 * the developers of coccinelle or advanced-users that know
207 * quite well the underlying semantics of coccinelle.
208 *)
209
210
211(* will be printed when use only ./spatch. For the rest you have to
212 * use -longhelp to see them.
213 *)
214let short_options = [
215 "-sp_file", Arg.Set_string cocci_file,
216 " <file> the semantic patch file";
217
218 "-o", Arg.Set_string output_file,
219 " <file> the output file";
220 "-inplace", Arg.Set inplace_modif,
221 " do the modification on the file directly";
222 "-outplace", Arg.Set outplace_modif,
223 " store modifications in a .cocci_res file";
224
225 "-U", Arg.Int (fun n -> Flag_parsing_c.diff_lines := Some (i_to_s n)),
226 " set number of diff context lines";
227 "-partial_match", Arg.Set Flag_ctl.partial_match,
228 " report partial matches of the SP on the C file";
229
230 "-iso_file", Arg.Set_string Config.std_iso,
231 " <file> (default=" ^ !Config.std_iso ^")";
708f4980
C
232 "-macro_file", Arg.Set_string macro_file,
233 " <file>";
234 "-macro_file_builtins", Arg.Set_string Config.std_h,
34e49164
C
235 " <file> (default=" ^ !Config.std_h ^ ")";
236
faf9a90c
C
237 "-all_includes",
238 Arg.Unit (function _ -> FC.include_options := FC.I_ALL_INCLUDES),
34e49164 239 " causes all available include files to be used";
faf9a90c
C
240 "-no_includes",
241 Arg.Unit (function _ -> FC.include_options := FC.I_NO_INCLUDES),
34e49164 242 " causes not even local include files to be used";
faf9a90c
C
243 "-local_includes",
244 Arg.Unit (function _ -> FC.include_options := FC.I_NORMAL_INCLUDES),
245 " causes local include files to be used";
246 "-include_headers", Arg.Set include_headers,
247 " process header files independently";
b1b2de81
C
248 "-I", Arg.String (function x -> FC.include_path := Some x),
249 " <dir> containing the header files (optional)";
34e49164
C
250
251
252 "-dir", Arg.Set dir,
253 " <dir> process all files in directory recursively";
254
34e49164
C
255 "-use_glimpse", Arg.Set Flag.use_glimpse,
256 " works with -dir, use info generated by glimpseindex";
257 "-patch", Arg.String (function s -> Flag.patch := Some s),
258 (" <dir> path name with respect to which a patch should be created\n"^
259 " \"\" for a file in the current directory");
260 "-kbuild_info", Arg.Set_string kbuild_info,
261 " <file> improve -dir by grouping related c files";
262 "-pyoutput", Arg.Set_string Flag.pyoutput,
263 " Sets output routine: Standard values: <coccilib.output.Gtk|coccilib.output.Console>";
264
265
266 "-version", Arg.Unit (fun () ->
267 pr2 (spf "spatch version: %s" Config.version);
268 exit 0;
269 ),
270 " guess what";
271
272 "-date", Arg.Unit (fun () ->
708f4980 273 pr2 "version: $Date: 2009/05/08 16:15:31 $";
34e49164
C
274 raise (Common.UnixExit 0)
275 ),
276 " guess what";
277
278 "-shorthelp", Arg.Unit (fun () ->
279 !short_usage_func();
280 raise (Common.UnixExit 0)
281 ),
282 " see short list of options";
283 "-longhelp", Arg.Unit (fun () ->
284 !long_usage_func();
285 raise (Common.UnixExit 0)
286 ),
287 " see all the available options in different categories";
288 "-help", Arg.Unit (fun () ->
289 !long_usage_func();
290 raise (Common.UnixExit 0)
291 ),
292 " ";
293 "--help", Arg.Unit (fun () ->
294 !long_usage_func();
295 raise (Common.UnixExit 0)
296 ),
297 " ";
298
299]
300
301(* the format is a list of triples:
302 * (title of section * (optional) explanation of sections * option list)
303 *)
304let other_options = [
305 "aliases and obsolete options",
306 "",
307 [
708f4980
C
308 "-sp", Arg.Set_string cocci_file, " short option of -sp_file";
309 "-iso", Arg.Set_string Config.std_iso, " short option of -iso_file";
310
34e49164
C
311 "-cocci_file", Arg.Set_string cocci_file,
312 " <file> the semantic patch file";
708f4980 313 "-c", Arg.Set_string cocci_file, " short option of -sp_file";
34e49164
C
314 ];
315
316 "most useful show options",
317 "",
318 [
faf9a90c
C
319 "-show_diff" , Arg.Set FC.show_diff, " ";
320 "-no_show_diff" , Arg.Clear FC.show_diff, " ";
321 "-show_flow" , Arg.Set FC.show_flow, " ";
322 (* works in conjunction with -show_ctl_text *)
323 "-ctl_inline_let",
324 Arg.Unit
325 (function _ -> FC.show_ctl_text := true; FC.inline_let_ctl := true), " ";
326 "-ctl_show_mcodekind",
327 Arg.Unit
328 (function _ -> FC.show_ctl_text := true; FC.show_mcodekind_in_ctl := true),
329 " ";
330 "-show_bindings", Arg.Set FC.show_binding_in_out, " ";
331 "-show_transinfo", Arg.Set Flag.show_transinfo, " ";
332 "-show_misc", Arg.Set Flag.show_misc, " ";
34e49164
C
333 "-show_trying", Arg.Set Flag.show_trying,
334 " show the name of each function being processed";
1be43e12 335 "-show_dependencies",
faf9a90c
C
336 Arg.Unit (function _ -> FC.show_dependencies := true;
337 FC.show_binding_in_out := true),
1be43e12 338 " show the dependencies related to each rule";
34e49164
C
339 ];
340
341 "verbose subsystems options",
342 "",
343 [
faf9a90c
C
344 "-verbose_ctl_engine",
345 Arg.Unit (function _ ->
346 Flag_ctl.verbose_ctl_engine := true; FC.show_ctl_text := true) , " ";
485bce71
C
347 "-verbose_match", Arg.Set Flag_ctl.verbose_match, " ";
348 "-verbose_engine", Arg.Set Flag_matcher.debug_engine, " ";
349 "-graphical_trace", Arg.Set Flag_ctl.graphical_trace, " generate a pdf file representing the matching process";
faf9a90c
C
350 "-gt_without_label",
351 Arg.Unit (function _ ->
352 Flag_ctl.graphical_trace := true; Flag_ctl.gt_without_label := true),
353 " remove graph label (requires option -graphical_trace)";
34e49164 354
faf9a90c
C
355 "-parse_error_msg", Arg.Set Flag_parsing_c.verbose_parsing, " ";
356 "-type_error_msg", Arg.Set Flag_parsing_c.verbose_type, " ";
34e49164
C
357 (* could also use Flag_parsing_c.options_verbose *)
358 ];
359
360 "other show options",
361 "",
362 [
faf9a90c
C
363 "-show_c" , Arg.Set FC.show_c, " ";
364 "-show_cocci" , Arg.Set FC.show_cocci, " ";
365 "-show_before_fixed_flow" , Arg.Set FC.show_before_fixed_flow, " ";
366 "-show_ctl_tex" , Arg.Set FC.show_ctl_tex, " ";
367 "-show_ctl_text" , Arg.Set FC.show_ctl_text, " ";
368 "-show_SP" , Arg.Set Flag_parsing_cocci.show_SP, " ";
34e49164
C
369 ];
370
371
372 "debug C parsing/unparsing",
373 "",
374 [
375 "-debug_cpp", Arg.Set Flag_parsing_c.debug_cpp, " ";
376 "-debug_lexer", Arg.Set Flag_parsing_c.debug_lexer , " ";
377 "-debug_etdt", Arg.Set Flag_parsing_c.debug_etdt , " ";
378 "-debug_typedef", Arg.Set Flag_parsing_c.debug_typedef, " ";
379
380 "-filter_msg", Arg.Set Flag_parsing_c.filter_msg ,
381 " filter some cpp message when the macro is a \"known\" cpp construct";
382 "-filter_define_error",Arg.Set Flag_parsing_c.filter_define_error," ";
708f4980
C
383 "-filter_msg_define_error",Arg.Set Flag_parsing_c.filter_msg_define_error,
384 " filter the error msg";
485bce71 385 "-filter_passed_level", Arg.Set_int Flag_parsing_c.filter_passed_level," ";
faf9a90c
C
386(* debug cfg doesn't seem to have any effect, so drop it as an option *)
387(* "-debug_cfg", Arg.Set Flag_parsing_c.debug_cfg , " "; *)
34e49164
C
388 "-debug_unparsing", Arg.Set Flag_parsing_c.debug_unparsing, " ";
389
390 ];
391 (* could use Flag_parsing_c.options_debug_with_title instead *)
392
393
394 "shortcut for enabling/disabling a set of debugging options at once",
395 "",
396 [
397 (* todo: other profile ? *)
faf9a90c
C
398 "-quiet", Arg.Unit (fun () -> run_profile quiet_profile), " ";
399 "-debug", Arg.Unit (fun () -> run_profile debug_profile), " ";
400 "-pad", Arg.Unit (fun () -> run_profile pad_profile), " ";
34e49164
C
401
402 ];
403
404 "bench options",
405 "",
406 [
407 "-profile", Arg.Unit (function () -> Common.profile := Common.PALL) ,
408 " gather timing information about the main coccinelle functions";
409 "-bench", Arg.Int (function x -> Flag_ctl.bench := x),
410 " <level> for profiling the CTL engine";
faf9a90c 411 "-timeout", Arg.Int (fun x -> FC.timeout := Some x),
34e49164
C
412 " <sec> timeout in seconds";
413 "-steps", Arg.Int (fun x -> Flag_ctl.steps := Some x),
414 " max number of model checking steps per code unit";
b1b2de81
C
415 "-iso_limit", Arg.Int (fun x -> Flag_parsing_cocci.iso_limit := Some x),
416 " max depth of iso application";
417 "-no_iso_limit", Arg.Unit (fun _ -> Flag_parsing_cocci.iso_limit := None),
418 " disable limit on max depth of iso application";
34e49164
C
419 "-track_iso", Arg.Set Flag.track_iso_usage,
420 " gather information about isomorphism usage";
421 "-profile_iso",
422 Arg.Unit
423 (function () ->
b1b2de81
C
424 Common.profile :=
425 (*post_engine not included, because it doesn't use isos*)
426 PSOME ["parse cocci";"mysat";"asttoctl2";"pre_engine";"full_engine"]),
34e49164
C
427 " gather information about the cost of isomorphism usage"
428 ];
429
430
431
432 "change of algorithm options",
433 "",
434 [
b1b2de81 435(* no popl in official version
faf9a90c 436 "-popl", Arg.Set FC.popl,
34e49164
C
437 " simplified SmPL, for the popl paper";
438
439 "-popl_mark_all",
440 Arg.Unit
faf9a90c 441 (function _ -> FC.popl := true; Flag_popl.mark_all := true),
34e49164
C
442 " simplified SmPL, for the popl paper";
443
444 "-popl_keep_all_wits",
445 Arg.Unit
faf9a90c 446 (function _ -> FC.popl := true; Flag_popl.keep_all_wits := true),
34e49164 447 " simplified SmPL, for the popl paper";
b1b2de81 448*)
34e49164 449
faf9a90c
C
450 "-hrule", Arg.String
451 (function s ->
452 Flag.make_hrule := Some s; FC.include_options := FC.I_NO_INCLUDES),
34e49164
C
453 " semantic patch generation";
454
455 "-loop", Arg.Set Flag_ctl.loop_in_src_code, " ";
456
457 "-l1", Arg.Clear Flag_parsing_c.label_strategy_2, " ";
faf9a90c 458 "-ifdef_to_if", Arg.Set FC.ifdef_to_if,
485bce71 459 " convert ifdef to if (experimental)";
708f4980
C
460 "-no_ifdef_to_if", Arg.Clear FC.ifdef_to_if,
461 " convert ifdef to if (experimental)";
462
463 "-disable_multi_pass", Arg.Set Flag_parsing_c.disable_multi_pass, " ";
485bce71 464
34e49164
C
465 "-noif0_passing", Arg.Clear Flag_parsing_c.if0_passing,
466 " ";
467 "-noadd_typedef_root", Arg.Clear Flag_parsing_c.add_typedef_root, " ";
468 (* could use Flag_parsing_c.options_algo instead *)
469
470
485bce71 471 "-disallow_nested_exps", Arg.Set Flag_matcher.disallow_nested_exps,
34e49164 472 "disallow an expresion pattern from matching a term and its subterm";
faf9a90c 473 "-disable_worth_trying_opt", Arg.Clear FC.worth_trying_opt,
34e49164
C
474 " ";
475 "-only_return_is_error_exit",
485bce71 476 Arg.Set Flag_matcher.only_return_is_error_exit,
34e49164
C
477 "if this flag is not set, then break and continue are also error exits";
478 (* the following is a hack to make it easier to add code in sgrep-like
479 code, essentially to compensate for the fact that we don't have
480 any way of printing things out *)
481 "-allow_inconsistent_paths",
485bce71 482 Arg.Set Flag_matcher.allow_inconsistent_paths,
708f4980
C
483 " if this flag is set don't check for inconsistent paths; dangerous";
484 "-int_bits", Arg.Int Flag_parsing_c.set_int_bits,
485 " the number of bits in an unsigned int";
486 "-long_bits", Arg.Int Flag_parsing_c.set_long_bits,
487 " the number of bits in an unsigned long";
488 "-linux_spacing", Arg.Unit Flag_parsing_c.set_linux_spacing,
489 " spacing of + code follows the conventions of Linux";
490 "-smpl_spacing", Arg.Unit Flag_parsing_c.set_smpl_spacing,
491 " spacing of + code follows the semantic patch";
34e49164
C
492 ];
493
494 "misc options",
495 "",
496 [
497 "-debugger", Arg.Set Common.debugger ,
498 " option to set if launch spatch in ocamldebug";
499 "-disable_once", Arg.Set Common.disable_pr2_once,
500 " to print more messages";
708f4980
C
501 "-show_trace_profile", Arg.Set Common.show_trace_profile,
502 " show trace";
34e49164
C
503 "-save_tmp_files", Arg.Set Common.save_tmp_files, " ";
504 ];
505
506 "concurrency",
507 "",
508 [
509 "-index", Arg.Int (function x -> distrib_index := Some x) ,
510 " the processor to use for this run of spatch";
511 "-max", Arg.Int (function x -> distrib_max := Some x) ,
512 " the number of processors available";
513 "-mod_distrib", Arg.Set mod_distrib,
514 " use mod to distribute files among the processors";
515 ];
516
517 "pad options",
518 "",
519 [
520 "-use_cache", Arg.Set Flag_parsing_c.use_cache,
521 " use .ast_raw pre-parsed cached C file";
522 (* could use Flag_parsing_c.options_pad instead *)
523 ];
524
525
526
527 "test mode and test options (works with tests/ or .ok files)",
528 "The test options don't work with the -sp_file and so on.",
529 [
530 "-test", Arg.Set test_mode,
531 " <file> launch spatch on tests/file.[c,cocci]";
532 "-testall", Arg.Set test_all,
533 " launch spatch on all files in tests/ having a .res";
534 "-test_okfailed", Arg.Set test_okfailed,
535 " generates .{ok,failed,spatch_ok} files using .res files";
536 "-test_regression_okfailed", Arg.Set test_regression_okfailed,
537 " process the .{ok,failed,spatch_ok} files in current dir";
538
539 "-compare_with_expected", Arg.Set compare_with_expected,
540 " use also file.res";
708f4980
C
541 "-expected_score_file", Arg.Set_string expected_score_file,
542 " which score file to compare with in -testall";
faf9a90c 543 "-relax_include_path", Arg.Set FC.relax_include_path,
34e49164
C
544 " ";
545
546 ];
547
548 "action mode",
549 ("The action options don't work with the -sp_file and so on." ^ "\n" ^
550 "It's for the other (internal) uses of the spatch program."
551 ),
552
553 (* -token_c, -parse_c, etc *)
554 ((Common.options_of_actions action (Test_parsing_c.actions())) ++
555 [
556 (let s = "-parse_cocci" in s, Arg.Unit (fun () -> action := s),
557 " <file>");
558 (let s = "-compare_c" in s, Arg.Unit (fun () -> action := s),
559 " <file1> <file2>");
560 ]);
561]
562
563
564let all_options =
565 short_options ++ List.concat (List.map Common.thd3 other_options)
566
34e49164
C
567
568(* I don't want the -help and --help that are appended by Arg.align *)
569let arg_align2 xs =
570 Arg.align xs +> List.rev +> Common.drop 2 +> List.rev
571
572(* copy paste of Arg.parse. Don't want the default -help msg *)
573let arg_parse2 l f msg =
574 (try
575 Arg.parse_argv Sys.argv l f msg;
576 with
577 | Arg.Bad msg -> (* eprintf "%s" msg; exit 2; *)
578 let xs = Common.lines msg in
579 (* take only head, it's where the error msg is *)
580 pr2 (List.hd xs);
581 !short_usage_func();
582 raise (Common.UnixExit (2))
583 | Arg.Help msg -> (* printf "%s" msg; exit 0; *)
584 raise Impossible (* -help is specified in speclist *)
585 )
586
587
588let short_usage () =
589 begin
590 Common.short_usage usage_msg short_options;
591 pr2 "";
592 pr2 "Example of use:";
593 pr2 " ./spatch -sp_file foo.cocci foo.c -o /tmp/newfoo.c";
594 pr2 "";
595 end
596
597
598let long_usage () =
599 Common.long_usage usage_msg short_options other_options
600
601let _ = short_usage_func := short_usage
602let _ = long_usage_func := long_usage
603
604(*****************************************************************************)
605(* Helpers *)
606(*****************************************************************************)
607
608let adjust_stdin cfile k =
609 if !dir
610 then k()
611 else
612 let newin =
485bce71
C
613 try
614 let (dir, base, ext) = Common.dbe_of_filename cfile in
615 let varfile = Common.filename_of_dbe (dir, base, "var") in
b1b2de81 616 if ext =$= "c" && Common.lfile_exists varfile
485bce71
C
617 then Some varfile
618 else None
619 with Invalid_argument("Filename.chop_extension") -> None
620 in
34e49164
C
621 Common.redirect_stdin_opt newin k
622
623let glimpse_filter (coccifile, isofile) dir =
faf9a90c 624 let (_metavars,astcocci,_free_var_lists,_negated_positions,
34e49164
C
625 _used_after_lists,_positions_lists,_,query) =
626 Cocci.sp_of_file coccifile (Some isofile) in
627 match query with
faf9a90c 628 None -> pr2 "no glimpse keyword inferred from snippet"; None
34e49164
C
629 | Some query ->
630 let suffixes = if !include_headers then ["c";"h"] else ["c"] in
631 pr2 ("glimpse request = " ^ query);
632 let command = spf "glimpse -y -H %s -N -W -w '%s'" dir query in
633 let (glimpse_res,stat) = Common.cmd_to_list_and_status command in
634 match stat with
635 Unix.WEXITED(0) | Unix.WEXITED(1) ->
636 Some
637 (glimpse_res +>
638 List.filter
639 (fun file -> List.mem (Common.filesuffix file) suffixes))
640 | _ -> None (* error, eg due to pattern too big *)
641
642
643
34e49164 644(*****************************************************************************)
b1b2de81 645(* Main action *)
34e49164 646(*****************************************************************************)
34e49164 647
b1b2de81
C
648let main_action xs =
649 match xs with
650 | x::xs ->
708f4980
C
651
652 (* a more general solution would be to use
653 * Common.files_of_dir_or_files (x::xs)
654 * as some elements in xs may also be directories, or individual
655 * files.
656 *)
657 if Common.is_directory x
658 then dir := true;
659
660 adjust_stdin x (fun () ->
661 if !cocci_file =$= ""
662 then failwith "I need a cocci file, use -sp_file <file>";
663
664 if !dir && !Flag.patch =*= None
665 then
666 (match xs with
667 | [] -> Flag.patch := Some x
668 | _ ->
669 pr2
670 ("warning: patch output can only be created when only one\n"^
671 "directory is specified or when the -patch flag is used")
672 );
673
674 let infiles =
675 Common.profile_code "Main.infiles computation" (fun () ->
676 match !dir, !kbuild_info, !Flag.use_glimpse with
677 (* glimpse *)
678 | false, _, true ->
679 failwith "-use_glimpse works only with -dir"
680 | true, s, true when s <> "" ->
681 failwith "-use_glimpse does not work with -kbuild"
682 | true, "", true ->
683 if not (null xs)
684 then failwith "-use_glimpse can accept only one dir";
685
686 Flag.dir := x;
687 let files =
688 match glimpse_filter (!cocci_file, !Config.std_iso) x with
689 None ->
690 Common.cmd_to_list (* same as "true, "", _" case *)
691 (if !include_headers
692 (* FIXME : Could we remove xs ?
693 -use_glimpse requires a singleton.
694 This is checked some lines before.
695 then ("find "^(join " " (x::xs))^" -name \"*.[ch]\"")
696 else ("find "^(join " " (x::xs))^" -name \"*.c\""))
697 *)
698 then ("find "^ x ^" -name \"*.[ch]\"")
699 else ("find "^ x ^" -name \"*.c\""))
700 | Some files -> files in
701 files +> List.map (fun x -> [x])
702 (* normal *)
703 | false, _, _ -> [x::xs]
704 | true, "", _ ->
705 Common.cmd_to_list
706 (if !include_headers
707 then ("find "^(join " " (x::xs))^" -name \"*.[ch]\"")
34e49164 708 else ("find "^(join " " (x::xs))^" -name \"*.c\""))
708f4980
C
709 +> List.map (fun x -> [x])
710
711 (* kbuild *)
712 | true, kbuild_info_file,_ ->
713 let dirs =
714 Common.cmd_to_list ("find "^(join " " (x::xs))^" -type d")
715 in
716 let info = Kbuild.parse_kbuild_info kbuild_info_file in
717 let groups = Kbuild.files_in_dirs dirs info in
718
719 groups +> List.map (function Kbuild.Group xs -> xs)
720 )
721 in
722
723 let infiles =
724 match (!distrib_index,!distrib_max) with
725 (None,None) -> infiles
726 | (Some index,Some max) ->
727 (if index >= max
728 then
729 failwith "index starts at 0, and so must be less than max");
730 if !mod_distrib
731 then
732 let rec loop ct = function
733 [] -> []
734 | x::xs ->
735 if (ct mod max) =|= index
736 then x::(loop (ct+1) xs)
737 else loop (ct+1) xs in
738 loop 0 infiles
739 else
740 begin
741 let all_files = List.length infiles in
742 let regions = (all_files + (max - 1)) / max in
743 let this_min = index * regions in
744 let this_max = (index+1) * regions in
34e49164 745 let rec loop ct = function
708f4980 746 [] -> []
34e49164 747 | x::xs ->
708f4980 748 if this_min <= ct && ct < this_max
34e49164
C
749 then x::(loop (ct+1) xs)
750 else loop (ct+1) xs in
751 loop 0 infiles
708f4980
C
752 end
753 | _ -> failwith "inconsistent distribution information" in
754
755 let outfiles =
756 Common.profile_code "Main.outfiles computation" (fun () ->
757 let cocci_infos =
758 Cocci.pre_engine (!cocci_file, !Config.std_iso) in
759 let res =
760 infiles +> List.map (fun cfiles ->
761 pr2 ("HANDLING: " ^ (join " " cfiles));
762 Common.timeout_function_opt !FC.timeout (fun () ->
763 Common.report_if_take_time 10 (join " " cfiles) (fun () ->
34e49164 764 (* Unix.sleep 1; *)
708f4980
C
765 try
766 (* this is the main call *)
767 Cocci.full_engine cocci_infos cfiles
768 with
769 | Common.UnixExit x -> raise (Common.UnixExit x)
770 | e ->
771 if !dir
772 then begin
773 pr2 ("EXN:" ^ Printexc.to_string e);
774 [] (* *)
775 end
776 else raise e))) in
777 Cocci.post_engine cocci_infos;
778 res
779 ) +> List.concat
780 in
781
782 Common.profile_code "Main.result analysis" (fun () ->
783
784 Ctlcocci_integration.print_bench();
785
786 let outfiles = Cocci.check_duplicate_modif outfiles in
787
788 outfiles +> List.iter (fun (infile, outopt) ->
789 outopt +> Common.do_option (fun outfile ->
790 if !inplace_modif
791 then begin
792 Common.command2 ("cp "^infile^" "^infile^".cocci_orig");
793 Common.command2 ("cp "^outfile^" "^infile);
794 end;
795
796 if !outplace_modif
797 then Common.command2 ("cp "^outfile^" "^infile^".cocci_res");
34e49164 798
708f4980
C
799 if !output_file =$= ""
800 then begin
801 let tmpfile = "/tmp/"^Common.basename infile in
802 pr2 (spf "One file modified. Result is here: %s" tmpfile);
803 Common.command2 ("cp "^outfile^" "^tmpfile);
804 end
805 ));
806 if !output_file <> "" then
807 (match outfiles with
808 | [infile, Some outfile] when infile =$= x && null xs ->
809 Common.command2 ("cp " ^outfile^ " " ^ !output_file);
810 | [infile, None] when infile =$= x && null xs ->
811 Common.command2 ("cp " ^infile^ " " ^ !output_file);
812 | _ ->
813 failwith
814 ("-o can not be applied because there is multiple " ^
815 "modified files");
816 );
817
818 if !compare_with_expected
819 then Testing.compare_with_expected outfiles))
b1b2de81
C
820
821 | [] -> raise Impossible
822
823
824(*****************************************************************************)
825(* The coccinelle main entry point *)
826(*****************************************************************************)
827let main () =
828 begin
829 let arglist = Array.to_list Sys.argv in
830
831 if not (null (Common.inter_set arglist
832 ["-cocci_file";"-sp_file";"-test";"-testall";
833 "-test_okfailed";"-test_regression_okfailed"]))
834 then run_profile quiet_profile;
835
836 let args = ref [] in
837
708f4980
C
838 (* Gc.set {(Gc.get ()) with Gc.stack_limit = 1024 * 1024};*)
839
b1b2de81
C
840 (* this call can set up many global flag variables via the cmd line *)
841 arg_parse2 (Arg.align all_options) (fun x -> args := x::!args) usage_msg;
842
708f4980
C
843 (* julia hack so that one can override directories specified on
844 * the command line. *)
b1b2de81
C
845 (if !dir
846 then
847 let chosen_dir =
848 if List.length !args > 1
849 then
850 begin
851 let chosen = List.hd !args in
852 pr2 ("ignoring all but the last specified directory: "^chosen);
853 args := [chosen];
854 chosen
855 end
856 else List.hd !args in
857 if !FC.include_path =*= None
858 then FC.include_path := Some (Filename.concat chosen_dir "include"));
708f4980 859
b1b2de81
C
860 args := List.rev !args;
861
862 if !cocci_file <> "" && (not (!cocci_file =~ ".*\\.\\(sgrep\\|spatch\\)$"))
863 then cocci_file := Common.adjust_ext_if_needed !cocci_file ".cocci";
864
865 if !Config.std_iso <> ""
866 then Config.std_iso := Common.adjust_ext_if_needed !Config.std_iso ".iso";
867 if !Config.std_h <> ""
868 then Config.std_h := Common.adjust_ext_if_needed !Config.std_h ".h";
869
870 if !Config.std_h <> ""
708f4980
C
871 then Parse_c.init_defs_builtins !Config.std_h;
872
873 if !macro_file <> ""
874 then Parse_c.init_defs_macros !macro_file;
b1b2de81
C
875
876
877 (* must be done after Arg.parse, because Common.profile is set by it *)
878 Common.profile_code "Main total" (fun () ->
879
880
881 let all_actions = Test_parsing_c.actions() in
882
883 (match (!args) with
884
885 (* --------------------------------------------------------- *)
886 (* The test framework. Works with tests/ or .ok and .failed *)
887 (* --------------------------------------------------------- *)
888 | [x] when !test_mode ->
889 FC.include_path := Some "tests/include";
890 Testing.testone x !compare_with_expected
891
892 | [] when !test_all ->
893 FC.include_path := Some "tests/include";
708f4980
C
894 if !expected_score_file <> ""
895 then Testing.testall ~expected_score_file:!expected_score_file ()
896 else Testing.testall ()
b1b2de81
C
897
898 | [] when !test_regression_okfailed ->
899 Testing.test_regression_okfailed ()
900
901 | x::xs when !test_okfailed ->
902 (* do its own timeout on FC.timeout internally *)
903 FC.relax_include_path := true;
904 adjust_stdin x (fun () ->
905 Testing.test_okfailed !cocci_file (x::xs)
906 )
907
908 (* --------------------------------------------------------- *)
909 (* Actions, useful to debug subpart of coccinelle *)
910 (* --------------------------------------------------------- *)
911
912 | xs when List.mem !action (Common.action_list all_actions) ->
913 Common.do_action !action xs all_actions
914
915 | [file] when !action =$= "-parse_cocci" ->
916 Testing.test_parse_cocci file
917
918 (* I think this is used by some scripts in some Makefile for our
919 * big-tests. So dont remove.
920 *)
921 | [file1;file2] when !action =$= "-compare_c" ->
922 Test_parsing_c.test_compare_c file1 file2 (* result = unix code *)
923
924 (* could add the Test_parsing_c.test_actions such as -parse_c & co *)
925
926
927 (* --------------------------------------------------------- *)
928 (* This is the main entry *)
929 (* --------------------------------------------------------- *)
930 | x::xs ->
931 main_action (x::xs)
932
34e49164
C
933 (* --------------------------------------------------------- *)
934 (* empty entry *)
935 (* --------------------------------------------------------- *)
936 | [] -> short_usage()
937
938 ));
939 if !Pycocci.initialised && (Pycocci.py_isinitialized ()) != 0 then begin
940 ignore(Pycocci.pyrun_simplestring "cocci.finalise()");
941 if !Flag.show_misc
942 then Common.pr2 "Finalizing python\n";
943 Pycocci.py_finalize ();
944 end
945 end
946
708f4980
C
947
948let main_with_better_error_report () =
949 if !Common.debugger then main ()
950 else
951 try
952 main ()
953 with
954 | Unix.Unix_error (_, "stat", filename) ->
955 pr2 (spf "ERROR: File %s does not exist" filename);
956 raise (UnixExit (-1))
957
958
34e49164 959(*****************************************************************************)
708f4980 960let start =
34e49164 961 Common.main_boilerplate (fun () ->
708f4980 962 main_with_better_error_report ();
34e49164
C
963 Ctlcocci_integration.print_bench();
964 )