1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
let other_scripts_magic_strings =
List.map Str.regexp [
"#![ ]*/usr/bin/perl.*";
"#![ ]*/bin/bash.*"
]
let is_other_script filename =
let cin = open_in_bin filename in
try
let firstline = input_line cin in
close_in cin;
List.exists
(function r -> Str.string_match r firstline 0)
other_scripts_magic_strings
with End_of_file ->
(** An empty file is not considered as a script.*)
false
let elf_magic_number = Bytes.of_string "\x7FELF"
let is_elf filename =
let cin = open_in_bin filename
and buf = Bytes.create 4 in
let number_chars_read = input cin buf 0 4 in
begin
close_in cin;
if number_chars_read < 4
then false
else Bytes.compare buf elf_magic_number = 0
end
let parse_string filename contents =
let lexbuf = ExtPervasives.lexing_make filename contents in
let cst = Engine.parse false PrelexerState.initial_state lexbuf in
cst.CST.value
let parse_file filename =
let cin = open_in_bin filename in
let cst =
try
(** We assume that scripts are no longer than 16M. *)
ExtPervasives.string_of_channel cin |> parse_string filename
with e ->
close_in cin;
raise e
in
close_in cin;
cst