checker.py 9.83 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
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
#!/usr/bin/python
# -*- coding: utf-8 -*-

''' Property parser for SDL systems

Template for a simple model checker

(c) European Space Agency, 2015-2017

Author: Maxime Perrotin
'''
from stringtemplate3 import StringTemplateGroup, StringTemplate
import opengeode

asn1_module = '''with <module>;
use <module>;
'''

provided_interface = '''<interface>_pi'''

required_interface = '''<interface>_ri'''

event = '''when <interface>_pi =>
<if(param)>
    <interface>_Param: aliased asn1Scc<sort>;
<else>
    null;
<endif>'''

check_ppty = u'''errno := <num>;
res := <model>_stop_conditions.p\u00dcproperty_<num>;
if res then
    return res;
end if;'''

exhaust_procedure = '''procedure exhaust_<interface> is
    <if(param)><interface>_it    : <sort>_pkg.Instance;<endif>
38
    event             : Event_ty(<interface>_pi);
Maxime Perrotin's avatar
Maxime Perrotin committed
39
40
41
42
43
    S_Hash            : Hash_Type;
begin
    backup_ctxt := Process_Ctxt;
<if(param)>
    for each of <interface>_it loop
44
        <sort>_pkg.To_ASN1(each, event.<interface>_param);
Maxime Perrotin's avatar
Maxime Perrotin committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        <model>.<interface>(event.<interface>_param'access);
        count := count + 1;
        S_Hash := Add_to_graph(event => event);
        check_and_report(S_Hash);
        Process_Ctxt := backup_ctxt;
    end loop;
<else>
    <model>.<interface>;
    count := count + 1;
    S_Hash := Add_to_graph(event => event);
    check_and_report(S_Hash);
<endif>

end;'''

exhaust = '''if Process_Ctxt.State in <states;separator= " | "> then
    exhaust_<interface>;
end if;'''

checker_template = '''with <model>;
use <model>;
with <model>_stop_conditions;
67
68
with asn1_iterators.iterators;
use asn1_iterators.iterators;
Maxime Perrotin's avatar
Maxime Perrotin committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

<asn1_modules;separator="\n">

with Ada.Text_IO;
use Ada.Text_IO;

with GNAT.MD5;

with Ada.Streams;
use Ada.Streams;

with Ada.Unchecked_Conversion;
with System;
with Ada.Strings.Hash;

84
85
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Ordered_Sets;
Maxime Perrotin's avatar
Maxime Perrotin committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
with Ada.Containers.Vectors;
use Ada.Containers;

with Ada.Calendar;
use Ada.Calendar;

procedure model_checker is
    subtype Context_ty is <model>_ctxt_ty;
    Process_Ctxt : Context_ty renames <model>_Ctxt;

    -- To save/restore the context when calling a PI:
    backup_ctxt : Context_ty;

    -- Type representing an event (input or output)
    type Interfaces is (start, <interfaces;separator=", ">);
    type Event_ty (Option: Interfaces) is
        record
            case Option is
                when start =>
                    null;
                <events;separator="\n">
            end case;
    end record;

    -- Type representing an entry in the state graph
    type Global_State (I: Interfaces) is
        record
            event   : Event_ty(I);
            context : Context_ty;
    end record;

    -- We store only pointers to graph states in the map
    type State_Access is access Global_State;

    -- The state graph itself is stored in a dictionary type (map)
    package State_graph is new Ordered_Maps (Key_Type     => Hash_Type,
                                             Element_Type => State_Access);
    Grafset : State_graph.Map;

    -- State graph index: Use md5 first to get a string representing
    -- the context object, then strings.hash to get a number that can be used
    -- as a map key. This can surely be improved!
    Ctxt_Size: constant stream_element_offset :=
           Context_ty'object_size / stream_element'size;
    type SEA_Pointer is
         access all Stream_Element_Array (1 .. Ctxt_Size);

    function As_SEA_Ptr is
       new Ada.Unchecked_Conversion (System.Address, SEA_Pointer);

    function State_Hash(state: State_Access) return Hash_Type is
        (Ada.Strings.Hash(gnat.md5.digest(as_sea_ptr(state.context'address).all)));

    -- Add a state to the graph: compute the hash (key) and store if not already there
    function Add_to_graph(event : Event_ty) return Hash_Type is
        New_State: constant State_Access := new Global_State(event.Option);
        New_Hash : Hash_Type;
    begin
        New_State.event   := event;
        New_State.context := Process_Ctxt;
        New_Hash := State_Hash(New_State);
        if not Grafset.Contains(Key => New_Hash) then
            Grafset.Insert(Key => New_Hash, New_Item => New_State);
        end if;
        return New_Hash;
    end;

    -- To count the number of calls to the function's provided interfaces
    count : natural := 0;

    -- Vector of hashes (integers) used for the model checking
    subtype Vect_Count is Positive range 1 .. 1000;
    package Lists is new Vectors (Element_Type => Hash_Type,
                                  Index_type   => Vect_Count);
    use Lists;

162
163
    package Sets is new Ordered_Sets(Element_Type => Hash_Type);

Maxime Perrotin's avatar
Maxime Perrotin committed
164
    queue   : Lists.Vector;
165
    visited : Sets.Set;
Maxime Perrotin's avatar
Maxime Perrotin committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

    -- Check all properties in one go, and if one fails, set errno
    function check_properties(errno: out natural) return boolean is
        res : Boolean := false;
    begin
        <check_properties;separator="\n">
        return res;
    end;

    -- Report the result of the property check to the user
    procedure check_and_report (S_Hash: Hash_Type) is
        errno: Natural := 0;
        stop_condition: boolean := false;
    begin
        if check_properties(errno) then
            put_line("Property " & errno'img & " is verified, at step " & count'img);
            stop_condition := true;
        end if;
184
185
        if not visited.contains(s_hash) then
            visited.insert(s_hash);
Maxime Perrotin's avatar
Maxime Perrotin committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
            if stop_condition = false then
                queue.append(S_Hash);
            end if;
        end if;
    end;


    -- One function per PI to exhaust the interface parameters
    <exhaust_procedures;separator="\n\n">

    procedure exhaustive_simulation is
    begin
        <exhausts;separator="\n">
    end;

    event      : Event_ty(start);
    S_Hash     : Hash_Type;
    Start_Time : Time := Clock;
begin
    put_line("Exhaustive simulation. Hit Ctrl-C to stop if it is too long...");
    orchestrator.startup;
    S_Hash := Add_to_graph(event => event);
    check_and_report(S_Hash);
    queue.append(S_Hash);
210
    visited.include(S_Hash);
Maxime Perrotin's avatar
Maxime Perrotin committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    while queue.Length > 0 loop
        Process_Ctxt := Grafset.Element(Key => queue.Last_Element).Context;
        exhaustive_simulation;
        queue.delete_last;
    end loop;
    put_line("Executed" & count'img & " functions");
    put_line("Visited" & Grafset.Length'img & " states");
    Put_Line("Execution time:" & Duration'Image(Clock - Start_Time) & "s.");
end;
'''

def generate(ast, stop_conditions):
    ''' Generate the code for the model checker '''
    process = ast.processes[0]

    # Set up a StringTemplate group (needed to configure angle-bracket)
    group = StringTemplateGroup('checker', '/tmp', lexer='angle-bracket')

    # List of ASN.1 modules
    asn1 = [name.replace('-', '_') for name in ast.asn1Modules]

    # Provided interfaces (process.input_signals)
    pis = {pi['name']: pi.get('type', None) for pi in process.input_signals}

    # Required interfaces (process.output_signals)
    ris = {ri['name']: ri.get('type', None) for ri in process.output_signals}

    # Instiantate and fill in the templates with the model data

    asn1_modules = []
    for each in asn1:
        asn1_tpl = StringTemplate(asn1_module, group=group)
        asn1_tpl['module'] = each
        asn1_modules.append(str(asn1_tpl))

    provided_interfaces = []
    for each in pis.keys():
        pi_tpl = StringTemplate(provided_interface, group=group)
        pi_tpl['interface'] = each
        provided_interfaces.append(str(pi_tpl))

    required_interfaces = []
    for each in ris.keys():
        ri_tpl = StringTemplate(required_interface, group=group)
        ri_tpl['interface'] = each
        required_interfaces.append(str(ri_tpl))

    events = []
    for name, sort in pis.viewitems():
        event_tpl = StringTemplate(event, group=group)
        event_tpl['interface'] = name
        event_tpl['param'] = True if sort else False
        event_tpl['sort'] = (opengeode.AdaGenerator.type_name(sort,
                                                              use_prefix=False)
                            if sort else "")
        events.append(str(event_tpl))

    check_ppties = []
    for idx in range(len(stop_conditions)):
        check_ppty_tpl = StringTemplate(check_ppty, group=group)
        check_ppty_tpl['model'] = process.processName
        check_ppty_tpl['num'] = str(idx)
        check_ppties.append(unicode(check_ppty_tpl))

    exhaust_procedures = []
    for name, sort in pis.viewitems():
        exhaust_procedure_tpl = StringTemplate(exhaust_procedure, group=group)
        exhaust_procedure_tpl['interface'] = name
        exhaust_procedure_tpl['param'] = True if sort else False
        exhaust_procedure_tpl['sort'] = (opengeode.AdaGenerator.type_name(sort,
                                                              use_prefix=False)
                                                               if sort else '')
        exhaust_procedure_tpl['model'] = process.processName
        exhaust_procedures.append(str(exhaust_procedure_tpl))

    exhausts = []
    for name, sort in pis.viewitems():
        exhaust_tpl = StringTemplate(exhaust, group=group)
        exhaust_tpl['interface'] = name
        # get a mapping {input: {state : transition}}
        opengeode.Helper.flatten(process, sep=u'\u00dc')
        mapping = opengeode.Helper.map_input_state(process)
        states = [state for state in mapping[name].keys() if "START" not
                  in state]
        exhaust_tpl['states'] = states
        exhausts.append(str(exhaust_tpl))

    complete = StringTemplate(checker_template, group=group)
    complete['model'] = process.processName
    complete['asn1_modules'] = asn1_modules
    complete['interfaces'] = provided_interfaces
    complete['events'] = events
    complete['check_properties'] = check_ppties
    complete['exhaust_procedures'] = exhaust_procedures
    complete['exhausts'] = exhausts

    with open('model_checker.adb', 'w') as ada_file:
        ada_file.write(unicode(complete).encode('latin1'))