Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid into no_simix_global
[simgrid.git] / docs / source / Tutorial_Model-checking.rst
1 .. _usecase_modelchecking:
2
3 Formal Verification and Model-checking
4 ======================================
5
6 SimGrid can not only predict the performance of your application, but also assess its correctness through formal methods. Mc SimGrid is
7 a full-featured model-checker that is embedded in the SimGrid framework. It can be used to formally verify safety and liveness
8 properties on codes running on top of SimGrid, be it :ref:`simple algorithms <usecase_simalgo>` or :ref:`full MPI applications
9 <usecase_smpi>`.
10
11 Primer on formal methods
12 ------------------------
13
14 Formal methods are techniques leveraging mathematics to test and assess systems. They are routinely used to assess computer hardware,
15 transportation systems or any other complex engineering process. Among these methods, model-checking is a technique to automatically
16 prove that a given model verifies a given property by systematically checking all states of the model. The property and model are
17 written in a mathematical language and fed to an automated tool called model checker. When the model does not verify the property, the
18 model checker gives a counter-example that can be used to refine and improve the model. Conversely, if no counter-example can be found
19 after an exhaustive exploration of the model, we know that the property holds for the model. It may also happen that the model is too
20 large to be exhaustively explored, in which case the model-checker is not conclusive. Model checkers rely on so-called reduction
21 techniques (based on symmetries and equivalence) to efficiently explore the system state.
22
23 Dynamic verification applies similar ideas to programs, without requiring a mathematical model of the system. Instead, the program
24 itself is used as a model to verify against a property. Along these lines, Mc SimGrid is a stateful model checker: it does not leverage
25 static analysis nor symbolic execution. Instead, the program is simply executed through all possible outcomes. On indecision points, a
26 system checkpoint is taken, the first branch is executed exhaustively, and then the system is roll back to that point to explore the
27 other branch.
28
29 Mc SimGrid targets distributed applications that interact through message passing or through synchronization mechanisms (mutex,
30 barrier, etc). Since it does not explicitly observe memory accesses, Mc SimGrid cannot automatically detect race conditions in
31 multithreaded programs. It can however be used to detect misuses of the synchronization functions, such as the ones resulting in
32 deadlocks.
33
34 Mc SimGrid can be used to verify classical `safety and liveness properties <https://en.wikipedia.org/wiki/Linear_time_property>`_, but
35 also `communication determinism <https://hal.inria.fr/hal-01953167/document>`_, a property that allows more efficient solutions toward
36 fault-tolerance. It can alleviate the state space explosion problem through `Dynamic Partial Ordering Reduction (DPOR)
37 <https://en.wikipedia.org/wiki/Partial_order_reduction>`_ and `state equality <https://hal.inria.fr/hal-01900120/document>`_. Note that
38 Mc SimGrid is currently less mature than other parts of the framework, but it improves every month. Please report any question and
39 issue so that we can further improve it.
40
41 Getting Mc SimGrid
42 ------------------
43
44 It is included in the SimGrid source code, but it is not compiled in by default as it induces a small performance overhead to the
45 simulations. It is also not activated in the Debian package, nor in the Java or Python binary distributions. If you just plan to
46 experiment with Mc SimGrid, the easiest is to get the corresponding docker image. On the long term, you probably want to install it on
47 your machine: it works out of the box on Linux, Windows (with WSL2) and FreeBSD. Simply request it from cmake (``cmake
48 -Denable_model-checking .``) and then compile SimGrid :ref:`as usual <install_src>`. Unfortunately, Mc SimGrid does not work natively
49 on Mac OS X yet, so mac users should stick to the docker method for now.
50
51 .. code-block:: console
52
53    $ docker image pull simgrid/tuto-mc
54    $ mkdir ~/tuto-mcsimgrid # or chose another directory to share between your computer and the docker container 
55    $ docker run -it --rm --name mcsimgrid --volume ~/tuto-mcsimgrid:/source/tutorial simgrid/tuto-mc bash
56
57 In the container, you have access to the following directories of interest:
58
59 - ``/source/tutorial``: A view to the ``~/tuto-mcsimgrid`` directory on your disk, out of the container.
60   Edit the files you want from your computer and save them in ``~/tuto-mcsimgrid``;
61   Compile and use them immediately within the container in ``/source/tutorial``.
62 - ``/source/tuto-mc.git``: Files provided with this tutorial.
63 - ``/source/simgrid.git``: Source code of SimGrid, pre-configured in MC mode. The framework is also installed in ``/usr``
64   so the source code is only provided for your information.
65
66 Lab1: non-deterministic receive
67 -------------------------------
68
69 Motivational example
70 ^^^^^^^^^^^^^^^^^^^^
71
72 Let's go with a first example of a bugged program. Once in the container, copy all files from the tutorial into the directory shared
73 between your host computer and the container.
74
75 .. code-block:: console
76
77   # From within the container
78   $ cp -r /source/tuto-mc.git/* /source/tutorial/
79   $ cd /source/tutorial/
80
81 Several files should have appeared in the ``~/tuto-mcsimgrid`` directory of your computer.
82 This tutorial uses `ndet-receive-s4u.cpp <https://framagit.org/simgrid/tutorial-model-checking/-/blob/main/ndet-receive-s4u.cpp>`_,
83 that uses the :ref:`S4U interface <S4U_doc>` of SimGrid, but we provide a
84 `MPI version <https://framagit.org/simgrid/tutorial-model-checking/-/blob/main/ndet-receive-mpi.cpp>`_
85 if you prefer (see below for details on using the MPI version).
86
87 .. toggle-header::
88    :header: Code of ``ndet-receive-s4u.cpp``: click here to open it, or `view it online <https://framagit.org/simgrid/tutorial-model-checking/-/blob/main/ndet-receive-s4u.cpp>`_
89
90    .. literalinclude:: tuto_mc/ndet-receive-s4u.cpp
91       :language: cpp
92
93 |br|
94 The provided code is rather simple: Three ``client`` are launched with an integer from ``1, 2, 3`` as a parameter. These actors simply
95 send their parameter to a given mailbox. A ``server`` receives 3 messages and assumes that the last received message is the number ``3``.
96 If you compile and run it, it simply works:
97
98 .. code-block:: console
99
100    $ cmake . && make
101    (output omitted)
102    $ ./ndet-receive-s4u small_platform.xml
103    [Jupiter:client:(2) 0.000000] [example/INFO] Sending 1
104    [Bourassa:client:(3) 0.000000] [example/INFO] Sending 2
105    [Ginette:client:(4) 0.000000] [example/INFO] Sending 3
106    [Jupiter:client:(2) 0.020516] [example/INFO] Sent!
107    [Bourassa:client:(3) 0.047027] [example/INFO] Sent!
108    [Ginette:client:(4) 0.064651] [example/INFO] Sent!
109    [Tremblay:server:(1) 0.064651] [example/INFO] OK
110
111 Running and understanding Mc SimGrid
112 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
113
114 If you think of it, that's weird that this code works: all the messages are sent at the exact same time (t=0), so there is no reason for
115 the message ``3`` to arrive last. Depending on the link speed, any order should be possible. To trigger the bug, you could fiddle with the
116 source code and/or the platform file, but this is not a method. Time to start Mc SimGrid, the SimGrid model checker, to exhaustively test
117 all message orders. For that, you simply launch your simulation as a parameter to the ``simgrid-mc`` binary as you would do with ``valgrind``:
118
119 .. code-block:: console
120
121    $ simgrid-mc ./ndet-receive-s4u small_platform.xml
122    (some output ignored)
123    [Tremblay:server:(1) 0.000000] (...) Assertion value_got == 3 failed
124    (more output ignored)
125
126 If it fails with the error ``[root/CRITICAL] Could not wait for the model-checker.``, you need to explicitly add the PTRACE capability to
127 your docker. Restart your docker with the additional parameter ``--cap-add SYS_PTRACE``.
128
129 At the end, it works: Mc SimGrid successfully triggers the bug. But the produced output is somewhat long and hairy. Don't worry, we will
130 now read it together. It can be split in several parts:
131
132 - First, you have some information coming from the application.
133
134   - On top, you see the output of the application, but somewhat stuttering. This is exactly what happens: since Mc SimGrid is exploring
135     all possible outcome of the code, the execution is sometimes rewind to explore another possible branch (here: another possible
136     message ordering). Note also that all times are always 0 in the model checker, since the time is abstracted away in this mode.
137
138     .. code-block:: console
139
140        [0.000000] [mc_safety/INFO] Check a safety property. Reduction is: dpor.
141        [Jupiter:client:(2) 0.000000] [example/INFO] Sending 1
142        [Bourassa:client:(3) 0.000000] [example/INFO] Sending 2
143        [Ginette:client:(4) 0.000000] [example/INFO] Sending 3
144        [Jupiter:client:(2) 0.000000] [example/INFO] Sent!
145        [Bourassa:client:(3) 0.000000] [example/INFO] Sent!
146        [Tremblay:server:(1) 0.000000] [example/INFO] OK
147        [Ginette:client:(4) 0.000000] [example/INFO] Sent!
148        [Jupiter:client:(2) 0.000000] [example/INFO] Sent!
149        [Bourassa:client:(3) 0.000000] [example/INFO] Sent!
150        [Jupiter:client:(2) 0.000000] [example/INFO] Sent!
151        [Bourassa:client:(3) 0.000000] [example/INFO] Sent!
152        [Tremblay:server:(1) 0.000000] [example/INFO] OK
153        [Ginette:client:(4) 0.000000] [example/INFO] Sent!
154        [Jupiter:client:(2) 0.000000] [example/INFO] Sent!
155        [Bourassa:client:(3) 0.000000] [example/INFO] Sent!
156        [Jupiter:client:(2) 0.000000] [example/INFO] Sent!
157
158   - Then you have the error message, along with a backtrace of the application at the point where the assertion fails. Not all the frames of
159     the backtrace are useful, and some are omitted here.
160
161     .. code-block:: console
162
163        [Tremblay:server:(1) 0.000000] /source/tutorial/ndet-receive-s4u.cpp:27: [root/CRITICAL] Assertion value_got == 3 failed
164        Backtrace (displayed in actor server):
165          ->  0# xbt_backtrace_display_current at /source/simgrid.git/src/xbt/backtrace.cpp:30
166          ->  1# server() at /source/tutorial/ndet-receive-s4u.cpp:27
167
168 -  After that comes a lot of information from the model-checker.
169
170   - First, the error message itself. The ``xbt_assert`` in the code result in an ``abort()`` in the application, that is interpreted as an
171     application crash by the model-checker.
172
173     .. code-block:: console
174
175        [0.000000] [mc_ModelChecker/INFO] **************************
176        [0.000000] [mc_ModelChecker/INFO] ** CRASH IN THE PROGRAM **
177        [0.000000] [mc_ModelChecker/INFO] **************************
178        [0.000000] [mc_ModelChecker/INFO] From signal: Aborted
179        [0.000000] [mc_ModelChecker/INFO] A core dump was generated by the system.
180
181   - An execution trace is then given, listing all the actions that led to that faulty execution. This is not easy to read, because the API
182     calls we made (put/get) are split in atomic calls (iSend+Wait/iRecv+Wait), and all executions are interleaved. Also, Mc SimGrid
183     reports the first faulty execution it finds: it may not be the shorter possible one.
184
185     .. code-block:: console
186   
187        [0.000000] [mc_ModelChecker/INFO] Counter-example execution trace:
188        [0.000000] [mc_ModelChecker/INFO]   [(1)Tremblay (server)] iRecv(dst=(1)Tremblay (server), buff=(verbose only), size=(verbose only))
189        [0.000000] [mc_ModelChecker/INFO]   [(2)Jupiter (client)] iSend(src=(2)Jupiter (client), buff=(verbose only), size=(verbose only))
190        [0.000000] [mc_ModelChecker/INFO]   [(1)Tremblay (server)] Wait(comm=(verbose only) [(2)Jupiter (client)-> (1)Tremblay (server)])
191        [0.000000] [mc_ModelChecker/INFO]   [(1)Tremblay (server)] iRecv(dst=(1)Tremblay (server), buff=(verbose only), size=(verbose only))
192        [0.000000] [mc_ModelChecker/INFO]   [(2)Jupiter (client)] Wait(comm=(verbose only) [(2)Jupiter (client)-> (1)Tremblay (server)])
193        [0.000000] [mc_ModelChecker/INFO]   [(4)Ginette (client)] iSend(src=(4)Ginette (client), buff=(verbose only), size=(verbose only))
194        [0.000000] [mc_ModelChecker/INFO]   [(1)Tremblay (server)] Wait(comm=(verbose only) [(4)Ginette (client)-> (1)Tremblay (server)])
195        [0.000000] [mc_ModelChecker/INFO]   [(1)Tremblay (server)] iRecv(dst=(1)Tremblay (server), buff=(verbose only), size=(verbose only))
196        [0.000000] [mc_ModelChecker/INFO]   [(3)Bourassa (client)] iSend(src=(3)Bourassa (client), buff=(verbose only), size=(verbose only))
197        [0.000000] [mc_ModelChecker/INFO]   [(1)Tremblay (server)] Wait(comm=(verbose only) [(3)Bourassa (client)-> (1)Tremblay (server)])
198
199   - Then, the execution path is given.
200
201     .. code-block:: console
202
203        [0.000000] [mc_record/INFO] Path = 1;2;1;1;2;4;1;1;3;1
204
205     This is the magical string (here: ``1;2;1;1;2;4;1;1;3;1``) that you should pass to your simulator to follow the same execution path
206     without ``simgrid-mc``. This is because ``simgrid-mc`` forbids to use a debugger such as gdb or valgrind on the code during the
207     model-checking. For example, you can trigger the same execution in valgrind as follows:
208
209     .. code-block:: console
210
211        $ valgrind ./ndet-receive-s4u small_platform.xml --cfg=model-check/replay:'1;2;1;1;2;4;1;1;3;1'
212        ==402== Memcheck, a memory error detector
213        ==402== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
214        ==402== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
215        ==402== Command: ./ndet-receive-s4u small_platform.xml --cfg=model-check/replay:1;2;1;1;2;4;1;1;3;1
216        ==402== 
217        [0.000000] [xbt_cfg/INFO] Configuration change: Set 'model-check/replay' to '1;2;1;1;2;4;1;1;3;1'
218        [0.000000] [mc_record/INFO] path=1;2;1;1;2;4;1;1;3;1
219        [Jupiter:client:(2) 0.000000] [example/INFO] Sending 1
220        [Bourassa:client:(3) 0.000000] [example/INFO] Sending 2
221        [Ginette:client:(4) 0.000000] [example/INFO] Sending 3
222        [Jupiter:client:(2) 0.000000] [example/INFO] Sent!
223        [Tremblay:server:(1) 0.000000] /source/tutorial/ndet-receive-s4u.cpp:27: [root/CRITICAL] Assertion value_got == 3 failed
224        (some output ignored)
225        ==402== 
226        ==402== Process terminating with default action of signal 6 (SIGABRT): dumping core
227        ==402==    at 0x550FCE1: raise (raise.c:51)
228        ==402==    by 0x54F9536: abort (abort.c:79)
229        ==402==    by 0x10C696: server() (ndet-receive-s4u.cpp:27)
230        (more valgrind output ignored)
231
232   - Then, Mc SimGrid displays some statistics about the amount of expanded states (the unique states in which your program was at a given
233     point of the exploration), the visited states (the amount of times we visited another state -- the same state may have been visited
234     several times) and the amount of transitions.
235
236     .. code-block:: console
237
238        [0.000000] [mc_safety/INFO] Expanded states = 22
239        [0.000000] [mc_safety/INFO] Visited states = 56
240        [0.000000] [mc_safety/INFO] Executed transitions = 52
241
242   - Finally, the application stack trace is displayed as the model-checker sees it. It should be the same as the one displayed from the
243     application side, unless you found a bug our tools.
244
245 Using MPI instead of S4U
246 ^^^^^^^^^^^^^^^^^^^^^^^^
247
248 If you prefer, you can use MPI instead of the SimGrid-specific interface. Inspect the provided ``ndet-receive-mpi.c`` file: that's just a
249 translation of ``ndet-receive-s4u.cpp`` to MPI.
250
251 .. toggle-header::
252    :header: Code of ``ndet-receive-mpi.c``: click here to open it, or `view it online <https://framagit.org/simgrid/tutorial-model-checking/-/blob/main/ndet-receive-mpi.cpp>`_
253
254    .. literalinclude:: tuto_mc/ndet-receive-mpi.c
255       :language: cpp
256
257 |br|
258 You can compile and run it on top of SimGrid as follows.
259
260 .. code-block:: console
261
262    $ smpicc ndet-receive-mpi.c -o ndet-receive-mpi
263    $ smpirun -np 4 -platform small_platform.xml ndet-receive-mpi
264
265 Interestingly enough, the bug is triggered on my machine even without Mc SimGrid, because the simulator happens to use the execution path
266 leading to it. It may not be the case on your machine, as this depends on the iteration order of an unsorted collection. Instead, we
267 should use Mc SimGrid to exhaustively explore the state space and trigger the bug in all cases.
268
269 .. code-block:: console
270
271    $ smpirun -wrapper simgrid-mc -np 4 -platform small_platform.xml ndet-receive-mpi
272
273 The produced output is then very similar to the one you get with S4U, even if the exact execution path leading to the bug may differs. You
274 can also trigger a given execution path out of the model-checker, for example to explore it with valgrind.
275
276 .. code-block:: console
277
278    $ smpirun -wrapper valgrind -np 4 -platform small_platform.xml --cfg=model-check/replay:'1;2;1;1;4;1;1;3;1' ndet-receive-mpi
279
280 Under the hood
281 ^^^^^^^^^^^^^^
282
283 If you want to run such analysis on your own code, out of the provided docker, there is some steps that you should take.
284
285 - SimGrid should naturally :ref:`be compiled <install_src>` with model-checking support. This requires a full set of dependencies
286   (documented on the :ref:`relevant page <install_src>`) and should not be activated by default as there is a small performance penalty for
287   codes using a SimGrid with MC enabled (even if you don't activate the model-checking at run time).
288 - You should pass some specific flags to the linker when compiling your application: ``-Wl,-znorelro -Wl,-znoseparate-code`` In the
289   docker, the provided CMakeLists.txt provides them for you when compiling the provided code. ``smpicc`` and friends also add this
290   parameter automatically.
291 - Also install ``libboost-stacktrace-dev`` to display nice backtraces from the application side (the one from the model-checking side is
292   available in any case, but it contains less details).
293 - Mc SimGrid uses the ``ptrace`` system call to spy on the verified application. Some versions of Docker forbid the use of this call by
294   default for security reason (it could be used to escape the docker containment with older versions of Linux). If you encounter this
295   issue, you should either update your settings (the security issue was solved in later versions of Linux), or add ``--cap-add
296   SYS_PTRACE`` to the docker parameters, as hinted by the text.
297
298 Going further
299 -------------
300
301 This tutorial is not complete yet, as there is nothing on reduction
302 techniques nor on liveness properties. For now, the best source of
303 information on these topics is `this old tutorial
304 <https://simgrid.org/tutorials/simgrid-mc-101.pdf>`_ and `that old
305 presentation
306 <http://people.irisa.fr/Martin.Quinson/blog/2018/0123/McSimGrid-Boston.pdf>`_.
307
308 .. |br| raw:: html
309
310    <br />