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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
(* SPDX-License-Identifier: AGPL-3.0-or-later *)
(* Copyright © 2021-2024 OCamlPro *)
(* Written by the Owi programmers *)
open Text
open Syntax
type env =
{ start : bool
; memory : bool
; imported_memory : bool
; funcs : bool
; tables : bool
; globals : bool
}
let empty_env () =
{ start = false
; memory = false
; imported_memory = false
; funcs = false
; tables = false
; globals = false
}
let modul m =
Log.debug0 "checking ...@\n";
let add_global =
let seen = Hashtbl.create 512 in
function
| None -> Ok ()
| Some id ->
if Hashtbl.mem seen id then Error (`Duplicate_global id)
else Ok (Hashtbl.replace seen id ())
in
let add_table =
let seen = Hashtbl.create 512 in
function
| None -> Ok ()
| Some id ->
if Hashtbl.mem seen id then Error (`Duplicate_table id)
else Ok (Hashtbl.replace seen id ())
in
let add_memory =
let seen = Hashtbl.create 512 in
function
| None -> Ok ()
| Some id ->
if Hashtbl.mem seen id then Error (`Duplicate_memory id)
else Ok (Hashtbl.add seen id ())
in
let+ (_env : env) =
List.fold_left
(fun env field ->
let* env in
match field with
| MExport _e -> Ok env
| MFunc _f -> Ok { env with funcs = true }
| MStart _start ->
if env.start then Error `Multiple_start_sections
else Ok { env with start = true }
| MImport i ->
if env.funcs then Error `Import_after_function
else if env.memory then Error `Import_after_memory
else if env.tables then Error `Import_after_table
else if env.globals then Error `Import_after_global
else begin
match i.desc with
| Import_mem (id, _) ->
let* () = add_memory id in
if env.imported_memory then Error `Multiple_memories
else Ok { env with imported_memory = true }
| Import_func _ -> Ok env
| Import_global (id, _) ->
let+ () = add_global id in
env
| Import_table (id, _) ->
let+ () = add_table id in
env
end
| MData _d -> Ok env
| MElem _e -> Ok env
| MMem (id, _) ->
let* () = add_memory id in
if env.memory || env.imported_memory then Error `Multiple_memories
else Ok { env with memory = true }
| MType _t -> Ok env
| MGlobal { id; _ } ->
let+ () = add_global id in
{ env with globals = true }
| MTable (id, _) ->
let+ () = add_table id in
{ env with tables = true } )
(Ok (empty_env ()))
m.fields
in
m