# source:Deliverables/D4.1/ITP-Paper/itp-2011.tex@574

Last change on this file since 574 was 574, checked in by mulligan, 10 years ago

Tweaked the document, and removed all junk from the end of the file.

File size: 51.5 KB
RevLine
[492]1\documentclass{llncs}
2
[495]3\usepackage{amsfonts}
4\usepackage{amsmath}
5\usepackage{amssymb}
[493]6\usepackage[english]{babel}
[495]7\usepackage{color}
[511]8\usepackage{fancybox}
[493]9\usepackage{graphicx}
[495]11\usepackage[utf8x]{inputenc}
12\usepackage{listings}
[512]13\usepackage{mdwlist}
[504]14\usepackage{microtype}
[495]15\usepackage{stmaryrd}
16\usepackage{url}
[493]17
[511]18\newlength{\mylength}
19\newenvironment{frametxt}%
20        {\setlength{\fboxsep}{5pt}
21                \setlength{\mylength}{\linewidth}%
24                \Sbox
25                \minipage{\mylength}%
26                        \setlength{\abovedisplayskip}{0pt}%
27                        \setlength{\belowdisplayskip}{0pt}%
28                }%
29                {\endminipage\endSbox
30                        $\fbox{\TheSbox}$}
31
[495]32\lstdefinelanguage{matita-ocaml}
[539]33  {keywords={definition,coercion,lemma,theorem,remark,inductive,record,qed,let,in,rec,match,return,with,Type,try,on,to},
[510]34   morekeywords={[2]whd,normalize,elim,cases,destruct},
[532]35   morekeywords={[3]type,of,val,assert,let,function},
[495]36   mathescape=true,
37  }
38\lstset{language=matita-ocaml,basicstyle=\small\tt,columns=flexible,breaklines=false,
39        keywordstyle=\color{red}\bfseries,
40        keywordstyle=[2]\color{blue},
41        keywordstyle=[3]\color{blue}\bfseries,
43        stringstyle=\color{blue},
44        showspaces=false,showstringspaces=false}
45\lstset{extendedchars=false}
46\lstset{inputencoding=utf8x}
47\DeclareUnicodeCharacter{8797}{:=}
48\DeclareUnicodeCharacter{10746}{++}
49\DeclareUnicodeCharacter{9001}{\ensuremath{\langle}}
50\DeclareUnicodeCharacter{9002}{\ensuremath{\rangle}}
51
[543]52\author{Dominic P. Mulligan\thanks{The project CerCo acknowledges the financial support of the Future and
53Emerging Technologies (FET) programme within the Seventh Framework
54Programme for Research of the European Commission, under FET-Open grant
55number: 243881} \and Claudio Sacerdoti Coen$^\star$}
[527]56\authorrunning{D. P. Mulligan and C. Sacerdoti Coen}
[501]57\title{An executable formalisation of the MCS-51 microprocessor in Matita}
58\titlerunning{An executable formalisation of the MCS-51}
[544]59\institute{Dipartimento di Scienze dell'Informazione, Universit\a di Bologna}
[492]60
[555]61\bibliographystyle{plain}
[549]62
[492]63\begin{document}
64
65\maketitle
66
67\begin{abstract}
[574]68We summarise the formalisation of an emulator for the MCS-51 microprocessor in the Matita proof assistant.
[495]69The MCS-51 is a widely used 8-bit microprocessor, especially popular in embedded devices.
70
[572]71The formalisation proceeded in two stages, first implementing an O'Caml prototype, for quickly ironing out' bugs, and then porting the O'Caml emulator to Matita.
[495]72Though mostly straight-forward, this porting presented multiple problems.
[574]73Of particular interest is how the unorthoganality of the MSC-51's instruction set is handled.
[569]74In O'Caml, this was handled with polymorphic variants.
75In Matita, we achieved the same effect with a non-standard use of dependent types.
[495]76
77Both the O'Caml and Matita emulators are executable'.
78Assembly programs may be animated within Matita, producing a trace of instructions executed.
[568]79The formalisation is a major component of the ongoing EU-funded CerCo project.
[492]80\end{abstract}
81
[493]82%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
83% SECTION                                                                      %
84%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[569]85\section{Introduction}
[493]86\label{sect.introduction}
87
[569]88Formal methods aim to increase our confidence in the design and implementation of software.
89Ideally, all software should come equipped with a formal specification and a proof of correctness for the corresponding implementation.
90The majority of programs are written in high level languages and then compiled into low level ones.
91Specifications are therefore also given at a high level and correctness can be proved by reasoning on the program's source code.
92The code that is actually run, however, is not the high level source code that we reason on, but low level code generated by the compiler.
[565]93A few questions now arise:
[512]94\begin{itemize*}
95\item
[509]96What properties are preserved during compilation?
[512]97\item
[509]98What properties are affected by the compilation strategy?
[512]99\item
[509]100To what extent can you trust your compiler in preserving those properties?
[512]101\end{itemize*}
[555]102These questions, and others like them, motivate a current hot topic' in computer science research: \emph{compiler verification} (for instance~\cite{leroy:formal:2009,chlipala:verified:2010}, and many others).
[565]103So far, the field has only been focused on the first and last questions.
[569]104Much attention has been placed on verifying compiler correctness with respect to extensional properties of programs.
105These are easily' preserved during compilation.
[509]106
[565]107If we consider intensional properties of programs---space, time, and so forth---the situation is more complex.
108To express these properties, and reason about them, we must adopt a cost model that assigns a cost to single, or blocks, of instructions.
[569]109A compositional cost model, assigning the same cost to all occurrences of one instruction, would be ideal.
[565]110However, compiler optimisations are inherently non-compositional: each occurrence of a high level instruction may be compiled in a different way depending on its context.
[513]111Therefore both the cost model and intensional specifications are affected by the compilation process.
[509]112
[565]113In the CerCo project (Certified Complexity')~\cite{cerco:2011} we approach the problem of reasoning about intensional properties of programs as follows.
114We are currently developing a compiler that induces a cost model on high level source code.
115Costs are assigned to each block of high level instructions by considering the costs of the corresponding blocks of compiled code.
116The cost model is therefore inherently non-compositional, but has the potential to be extremely \emph{precise}, capturing a program's \emph{realistic} cost.
117That is, the compilation process is taken into account, not ignored.
[514]118A prototype compiler, where no approximation of the cost is provided, has been developed.
[565]119(The technical details of the cost model is explained in~\cite{amadio:certifying:2010}.)
[509]120
[565]121We believe that our approach is applicable to certifying real time programs.
122A user can certify that deadlines' are met whilst wringing as many clock cycles from the processor---using a cost model that does not over-estimate---as possible.
[514]123
[569]124We also see our approach as being relevant to compiler verification (and construction) itself.
125\emph{An optimisation specified only extensionally is only half specified}.
126Though the optimisation may preserve the denotational semantics of a program, there is no guarantee that any intensional properties of the program will be improved.
127
[515]128Another potential application is toward completeness and correctness of the compilation process in the presence of space constraints.
[569]129A compiler could reject a source program targetting an embedded system when the size of the compiled code exceeds the available ROM size.
[565]130Preservation of a program's semantics may only be required for those programs that do not exhaust the stack or heap.
[569]131The statement of completeness of the compiler must therefore take in to account a realistic cost model.
[509]132
[569]133With the CerCo methodology, we assume we can assign to object code exact and realistic costs for sequential blocks of instructions.
134This is possible with modern processors (see~\cite{bate:wcet:2011,yan:wcet:2008} for instance) but difficult, as the structure and execution of a program itself has an influence on the speed of processing.
135Caching, memory effects, and advanced features such as branch prediction all have an effect on execution speed.
[515]136For this reason CerCo decided to focus on 8-bit microprocessors.
[569]137These are still used in embedded systems, with the advantage of a predictable cost model due to their relative paucity of features.
[509]138
[569]139We have fully formalised an executable formal semantics of a family of 8-bit Freescale microprocessors~\cite{oliboni:matita:2008}, and provided a similar executable formal semantics for the MCS-51 microprocessor.
[565]140The latter is what we describe in this paper.
141The focus of the formalisation has been on capturing the intensional behaviour of the processor.
[574]142However, the design of the MCS-51 itself has caused problems in the formalisation.
[515]143For example, the MCS-51 has a highly unorthogonal instruction set.
[569]144To cope with this unorthogonality, and to produce an executable specification, we rely on Matita's dependent types.
[509]145
[568]147The MCS-51 is an 8-bit microprocessor introduced by Intel in the late 1970s.
[569]148Commonly called the 8051, in the decades since its introduction the processor has become a popular component of embedded systems.
149The processor, its successor the 8052, and derivatives are still manufactured \emph{en masse} by a host of vendors.
[493]150
[569]151The 8051 is a well documented processor, and has the support of numerous open source and commercial tools, such as compilers and emulators.
152For instance, the open source Small Device C Compiler (SDCC) recognises a dialect of C~\cite{sdcc:2010}, and other compilers for BASIC, Forth and Modula-2 are also extant.
153An open source emulator for the processor, MCU 8051 IDE, is also available~\cite{mcu8051ide:2010}.
[574]154Both MCU 8051 IDE and SDCC were used in for validating the formalisation.
[493]155
156\begin{figure}[t]
[559]157\setlength{\unitlength}{0.87pt}
158\begin{picture}(410,250)(-50,200)
159%\put(-50,200){\framebox(410,250){}}
160\put(12,410){\makebox(80,0)[b]{Internal (256B)}}
161\put(13,242){\line(0,1){165}}
162\put(93,242){\line(0,1){165}}
163\put(13,407){\line(1,0){80}}
164\put(12,400){\makebox(0,0)[r]{0h}}  \put(14,400){\makebox(0,0)[l]{Register bank 0}}
165\put(13,393){\line(1,0){80}}
166\put(12,386){\makebox(0,0)[r]{8h}}  \put(14,386){\makebox(0,0)[l]{Register bank 1}}
167\put(13,379){\line(1,0){80}}
168\put(12,372){\makebox(0,0)[r]{10h}}  \put(14,372){\makebox(0,0)[l]{Register bank 2}}
169\put(13,365){\line(1,0){80}}
170\put(12,358){\makebox(0,0)[r]{18h}} \put(14,358){\makebox(0,0)[l]{Register bank 3}}
171\put(13,351){\line(1,0){80}}
173\put(13,323){\line(1,0){80}}
174\put(12,316){\makebox(0,0)[r]{30h}}
176\put(13,291){\line(1,0){80}}
177\put(12,284){\makebox(0,0)[r]{80h}}
179\put(12,249){\makebox(0,0)[r]{ffh}}
180\put(13,242){\line(1,0){80}}
181
182\qbezier(-2,407)(-6,407)(-6,393)
183\qbezier(-6,393)(-6,324)(-10,324)
184\put(-12,324){\makebox(0,0)[r]{Indirect/stack}}
185\qbezier(-6,256)(-6,324)(-10,324)
186\qbezier(-2,242)(-6,242)(-6,256)
187
188\qbezier(94,407)(98,407)(98,393)
189\qbezier(98,393)(98,349)(102,349)
190\put(104,349){\makebox(0,0)[l]{Direct}}
191\qbezier(98,305)(98,349)(102,349)
192\qbezier(94,291)(98,291)(98,305)
193
194\put(102,242){\framebox(20,49){SFR}}
196
197\qbezier(124,291)(128,291)(128,277)
198\qbezier(128,277)(128,266)(132,266)
199\put(134,266){\makebox(0,0)[l]{Direct}}
200\qbezier(128,257)(128,266)(132,266)
201\qbezier(124,242)(128,242)(128,256)
202
203\put(164,410){\makebox(80,0)[b]{External (64kB)}}
204\put(164,220){\line(0,1){187}}
205\put(164,407){\line(1,0){80}}
206\put(244,220){\line(0,1){187}}
207\put(164,242){\line(1,0){80}}
208\put(163,400){\makebox(0,0)[r]{0h}}
209\put(164,324){\makebox(80,0){Paged access}}
210  \put(164,310){\makebox(80,0){Direct/indirect}}
211\put(163,235){\makebox(0,0)[r]{80h}}
212  \put(164,228){\makebox(80,0){\vdots}}
213  \put(164,210){\makebox(80,0){Direct/indirect}}
214
215\put(264,410){\makebox(80,0)[b]{Code (64kB)}}
216\put(264,220){\line(0,1){187}}
217\put(264,407){\line(1,0){80}}
218\put(344,220){\line(0,1){187}}
219\put(263,400){\makebox(0,0)[r]{0h}}
220  \put(264,228){\makebox(80,0){\vdots}}
221  \put(264,324){\makebox(80,0){Direct}}
222  \put(264,310){\makebox(80,0){PC relative}}
223\end{picture}
224\caption{The 8051 memory model}
[493]225\label{fig.memory.layout}
226\end{figure}
227
228The 8051 has a relatively straightforward architecture, unencumbered by advanced features of modern processors, making it an ideal target for formalisation.
[559]229A high-level overview of the processor's memory layout, along with the ways in which different memory spaces may be addressed, is provided in Figure~\ref{fig.memory.layout}.
[493]230
231Processor RAM is divided into numerous segments, with the most prominent division being between internal and (optional) external memory.
[569]232Internal memory, commonly provided on the die itself with fast access, is composed of 256 bytes, but, in direct addressing mode, half of them are overloaded with 128 bytes of memory-mapped Special Function Registers (SFRs).
233SFRs control the operation of the processor.
234Internal RAM (IRAM) is divided again into 8 general purpose bit-addressable registers (R0--R7).
235These sit in the first 8 bytes of IRAM, though can be programmatically shifted up' as needed.
236Bit memory, followed by a small amount of stack space, resides in the memory space immediately following the register banks.
237What remains of IRAM may be treated as general purpose memory.
[559]238A schematic view of IRAM layout is also provided in Figure~\ref{fig.memory.layout}.
[493]239
[569]240External RAM (XRAM), limited to a maximum size of 64 kilobytes, is optional, and may be provided on or off chip, depending on the vendor.
[568]241XRAM is accessed using a dedicated instruction, and requires 16 bits to address fully.
[569]242External code memory (XCODE) is often stored as an EPROM, and limited to 64 kilobytes in size.
243However, depending on the particular processor model, a dedicated on-die read-only memory area for program code (ICODE) may be supplied.
[493]244
245Memory may be addressed in numerous ways: immediate, direct, indirect, external direct and code indirect.
[569]246As the latter two addressing modes hint, there are some restrictions enforced by the 8051, and its derivatives, on which addressing modes may be used with specific types of memory.
247For instance, the extra 128 bytes of IRAM of the 8052 cannot be addressed using indirect addressing; rather, external (in)direct addressing must be used. Moreover, some memory segments are addressed using 8-bit pointers while others require 16-bits.
[493]248
[568]249The 8051 possesses an 8-bit Arithmetic and Logic Unit (ALU), with a variety of instructions for performing arithmetic and logical operations on bits and integers.
250Two 8-bit general purpose accumulators, A and B, are provided.
[493]251
[569]252Communication with the device is handled by an inbuilt UART serial port and controller.
253This can operate in numerous modes.
[568]254Serial baud rate is determined by one of two 16-bit timers included with the 8051, which can be set to multiple modes of operation.
255(The 8052 provides an additional 16-bit timer.)
[569]256The 8051 also provides a 4 byte bit-addressable I/O port.
[493]257
[569]258The programmer may take advantage of an interrupt mechanism.
259This is especially useful when dealing with I/O involving the serial device, as an interrupt can be set when a whole character is sent or received via the UART.
[493]260
261Interrupts immediately halt the flow of execution of the processor, and cause the program counter to jump to a fixed address, where the requisite interrupt handler is stored.
262However, interrupts may be set to one of two priorities: low and high.
263The interrupt handler of an interrupt with high priority is executed ahead of the interrupt handler of an interrupt of lower priority, interrupting a currently executing handler of lower priority, if necessary.
264
265The 8051 has interrupts disabled by default.
266The programmer is free to handle serial input and output manually, by poking serial flags in the SFRs.
[565]267Exceptional circumstances' that would otherwise trigger an interrupt on more modern processors, (e.g. division by zero) are also signalled by setting flags.
[493]268
[559]269%\begin{figure}[t]
270%\begin{center}
271%\includegraphics[scale=0.5]{iramlayout.png}
272%\end{center}
273%\caption{Schematic view of 8051 IRAM layout}
274%\label{fig.iram.layout}
275%\end{figure}
[493]276
[538]278In Section~\ref{sect.design.issues.formalisation} we discuss design issues in the development of the formalisation.
[574]279In Section~\ref{sect.validation} we discuss how we validated the design and implementation of the emulator to ensure that what we formalised was an accurate model of an MCS-51 series microprocessor.
[538]280In Section~\ref{sect.related.work} we describe previous work, with an eye toward describing its relation with the work described herein.
[565]281In Section~\ref{sect.conclusions} we conclude.
[494]282
[493]283%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
284% SECTION                                                                      %
285%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[527]286\section{Design issues in the formalisation}
287\label{sect.design.issues.formalisation}
[493]288
[570]289From hereonin, we typeset O'Caml source with \texttt{\color{blue}{blue}} and Matita source with \texttt{\color{red}{red}}.
290Matita's syntax is straightforward if familiar with Coq or O'Caml.
291One subtlety is the use of \texttt{?}' in an argument position denoting an argument to be inferred.
[527]292
[557]293A full account of the formalisation can be found in~\cite{cerco-report:2011}.
294
[527]295\subsection{Development strategy}
296\label{subsect.development.strategy}
297
[574]298The implementation progressed in two stages.
[570]299We began with an emulator written in O'Caml to iron out' any bugs in the design and implementation.
[565]300O'Caml's ability to perform file I/O also eased debugging and validation.
[570]301Once we were happy with the design of the O'Caml emulator, we moved to Matita.
[495]302
[506]303Matita's syntax is lexically similar to O'Caml's.
[570]304This eased the translation, as swathes of code were copied with minor modifications.
[565]305However, several major issues had to be addresses when moving from to Matita.
[506]306These are now discussed.
[495]307
[493]308%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
309% SECTION                                                                      %
310%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[554]311\subsection{Representation of bytes, words, etc.}
[519]312\label{subsect.representation.integers}
[494]313
[532]314\begin{figure}[t]
[536]315\begin{minipage}[t]{0.45\textwidth}
[532]316\vspace{0pt}
[527]317\begin{lstlisting}
318type 'a vect = bit list
[554]319type nibble = [Sixteen] vect
[527]320type byte = [Eight] vect
[554]321$\color{blue}{\mathtt{let}}$ split_word w = split_nth 4 w
322$\color{blue}{\mathtt{let}}$ split_byte b = split_nth 2 b
[527]323\end{lstlisting}
[532]324\end{minipage}
[536]325%
326\begin{minipage}[t]{0.55\textwidth}
[532]327\vspace{0pt}
[527]328\begin{lstlisting}
[532]329type 'a vect
330type word = [Sixteen] vect
331type byte = [Eight] vect
[554]332val split_word: word -> byte * word
333val split_byte: byte -> nibble * nibble
[527]334\end{lstlisting}
[532]335\end{minipage}
336\caption{Sample of O'Caml implementation and interface for bitvectors module}
337\label{fig.ocaml.implementation.bitvectors}
338\end{figure}
339
[570]340The formalization of MCS-51 must deal with bytes (8-bits), words (16-bits), and also more exoteric quantities (7, 3 and 9-bits).
341To avoid difficult-to-trace size mismatch bugs, we represented all quantities using bitvectors, i.e. fixed length vectors of booleans.
[574]342In the O'Caml emulator, we faked' bitvectors using phantom types~\cite{leijen:domain:1999} implemented with polymorphic variants~\cite{garrigue:programming:1998}, as in Figure~\ref{fig.ocaml.implementation.bitvectors}.
[555]343From within the bitvector module (left column) bitvectors are just lists of bits and no guarantee is provided on sizes.
[570]344However, the module's interface (right column) enforces size invariants in the rest of the code.
[532]345
[554]346In Matita, we are able to use the full power of dependent types to always work with vectors of a known size:
[527]347\begin{lstlisting}
[569]348inductive Vector (A: Type[0]): nat $\rightarrow$ Type[0] ≝
[527]349  VEmpty: Vector A O
[569]350| VCons: $\forall$n: nat. A $\rightarrow$ Vector A n $\rightarrow$ Vector A (S n).
[527]351\end{lstlisting}
352We define \texttt{BitVector} as a specialization of \texttt{Vector} to \texttt{bool}.
[570]353We may use Matita's type system to provide precise typings for functions that are polymorphic in the size without code duplication:
[527]354\begin{lstlisting}
355let rec split (A: Type[0]) (m,n: nat) on m:
356   Vector A (plus m n) $\rightarrow$ (Vector A m) $\times$ (Vector A n) := ...
357\end{lstlisting}
358
[494]359%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
360% SECTION                                                                      %
361%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[511]362\subsection{Representing memory}
363\label{subsect.representing.memory}
364
[570]365The MCS-51 has numerous disjoint memory spaces addressed by differently sized pointers.
[574]366In the O'Caml implementation, we use a map data structure (from the standard library) for each space.
[565]367Matita's standard library is small, and does not contain a generic map data structure.
368We had the opportunity of crafting a dependently typed special-purpose data structure for the job to enforce the correspondence between the size of pointer and the size of the memory space.
[570]369Further, we assumed that large swathes of memory would often be uninitialized.
[516]370
[565]371We picked a modified form of trie of fixed height $h$.
[574]372Paths are represented by bitvectors (already used in the implementation for addresses and registers) of length $h$:
[516]373\begin{lstlisting}
374inductive BitVectorTrie (A: Type[0]): nat $\rightarrow$ Type[0] ≝
375  Leaf: A $\rightarrow$ BitVectorTrie A 0
376| Node: ∀n. BitVectorTrie A n $\rightarrow$ BitVectorTrie A n $\rightarrow$ BitVectorTrie A (S n)
377| Stub: ∀n. BitVectorTrie A n.
378\end{lstlisting}
[565]379\texttt{Stub} is a constructor that can appear at any point in a trie.
380It represents uninitialized data'.
[516]381Performing a lookup in memory is now straight-forward.
[570]382The only subtlety over normal trie lookup is how we handle \texttt{Stub}.
383We traverse a path, and upon encountering \texttt{Stub}, we return a default value\footnote{All manufacturer data sheets that we consulted were silent on the subject of what should be returned if we attempt to access uninitialized memory.  We defaulted to simply returning zero, though our \texttt{lookup} function is parametric in this choice.  We do not believe that this is an outrageous decision, as SDCC for instance generates code which first zeroes out' all memory in a preamble before executing the program proper.  This is in line with the C standard, which guarantees that all global variables will be zero initialized piecewise.}.
[516]384
[511]385%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
386% SECTION                                                                      %
387%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[519]388\subsection{Labels and pseudoinstructions}
389\label{subsect.labels.pseudoinstructions}
390
[523]391Aside from implementing the core MCS-51 instruction set, we also provided \emph{pseudoinstructions}, \emph{labels} and \emph{cost labels}.
392The purpose of \emph{cost labels} will be explained in Subsection~\ref{subsect.computation.cost.traces}.
393
[522]394Introducing pseudoinstructions had the effect of simplifying a C compiler---another component of the CerCo project---that was being implemented in parallel with our implementation.
[565]395To see why, consider the fact that the MCS-51's instruction set has numerous instructions for unconditional and conditional jumps to memory locations.
[519]396For instance, the instructions \texttt{AJMP}, \texttt{JMP} and \texttt{LJMP} all perform unconditional jumps.
397However, these instructions differ in how large the maximum size of the offset of the jump to be performed can be.
[565]399Compilers that support separate compilation cannot directly compute these offsets and select the appropriate jump instructions.
[570]400These operations are also burdensome for compilers that do not do separate compilation and are handled by assemblers.
401We followed suit.
[519]402
[565]403While introducing pseudoinstructions, we also introduced labels for locations to jump to, and for global data.
[570]404To specify global data via labels, we introduced a preamble before the program where labels and the size of reserved space for data is stored.
405A pseudoinstruction \texttt{Mov} moves (16-bit) data stored at a label into the MCS-51's one 16-bit register, \texttt{DPTR}.
[522]406
[574]407The pseudoinstructions and labels induce an assembly language similar to that of SDCC's.
[565]408All pseudoinstructions and labels are assembled away' prior to program execution.
409Jumps are computed in two stages.
[570]410A map associating memory addresses to labels is built, before replacing pseudojumps with concrete jumps to the correct address.
411The algorithm currently implemented does not try to minimize object code size by picking the shortest possible jump instruction.
412A better algorithm is left for future work.
[522]413
[519]414%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
415% SECTION                                                                      %
416%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[524]417\subsection{Anatomy of the (Matita) emulator}
418\label{subsect.anatomy.matita.emulator}
[494]419
[571]420The internal state of the Matita emulator is represented as a record:
[517]421\begin{lstlisting}
[561]422record Status: Type[0] ≝ {
[517]423  code_memory: BitVectorTrie Byte 16;
424  low_internal_ram: BitVectorTrie Byte 7;
425  high_internal_ram: BitVectorTrie Byte 7;
426  external_ram: BitVectorTrie Byte 16;
427  program_counter: Word;
428  special_function_registers_8051: Vector Byte 19;
429  special_function_registers_8052: Vector Byte 5;
[561]430  ...  }.
[517]431\end{lstlisting}
[571]432This record encapsulates the current memory contents, the program counter, the state of the current SFRs, and so on.
[510]433
[571]434Here the MCS-51's memory model is implemented using four disjoint memory spaces, plus SFRs.
435From the programmer's point of view, what \emph{really} matters are the addressing modes that are in a many-to-many relationship with the spaces.
436\texttt{DIRECT} addressing can be used to address either lower IRAM (if the first bit is 0) or the SFRs (if the first bit is 1), for instance.
437That's why DIRECT uses 8-bit addresses but pointers to lower IRAM only use 7 bits.
438The complexity of the memory model is captured in a pair of functions, \texttt{get\_arg\_XX} and \texttt{set\_arg\_XX}, that get' and set' data of size \texttt{XX} from memory.
[536]439
[561]440%Overlapping, and checking which addressing modes can be used to address particular memory spaces, is handled through numerous \texttt{get\_arg\_XX} and \texttt{set\_arg\_XX} (for 1, 8 and 16 bits) functions.
[536]441
[571]442Both the Matita and O'Caml emulators follow the classic fetch-decode-execute' model of processor operation.
[532]443The next instruction to be processed, indexed by the program counter, is fetched from code memory with \texttt{fetch}.
[571]444An updated program counter, along with its concrete cost in processor cycles, is also returned.
445These costs are taken from a Siemens Semiconductor Group data sheet for the MCS-51~\cite{siemens:2011}, and will likely vary across manufacturers and derivatives of the processor.
[524]446\begin{lstlisting}
[561]447definition fetch: BitVectorTrie Byte 16 $\rightarrow$ Word $\rightarrow$ instruction $\times$ Word $\times$ nat
[524]448\end{lstlisting}
[561]449Instruction are assembled to bit encodings by \texttt{assembly1}:
[524]450\begin{lstlisting}
[561]451definition assembly1: instruction $\rightarrow$ list Byte
[524]452\end{lstlisting}
[565]453An assembly program---comprising a preamble containing global data and a list of pseudoinstructions---is assembled using \texttt{assembly}.
454Pseudoinstructions and labels are eliminated in favour of instructions from the MCS-51 instruction set.
455A map associating memory locations and cost labels (see Subsection~\ref{subsect.computation.cost.traces}) is produced.
[524]456\begin{lstlisting}
[532]457definition assembly:
[561]458  assembly_program $\rightarrow$ option (list Byte $\times$ (BitVectorTrie String 16))
[524]459\end{lstlisting}
[561]460A single fetch-decode-execute cycle is performed by \texttt{execute\_1}:
[524]461\begin{lstlisting}
[561]462definition execute_1: Status $\rightarrow$ Status
[524]463\end{lstlisting}
[561]464The \texttt{execute} functions performs a fixed number of cycles by iterating
465\texttt{execute\_1}:
[524]466\begin{lstlisting}
467let rec execute (n: nat) (s: Status) on n: Status := ...
468\end{lstlisting}
[565]469This differs from the O'Caml emulator, which executed a program indefinitely.
470A callback function was also accepted as an argument, which could witness' the execution as it happened, providing a print-out of the processor state.
471Due to Matita's termination requirement, \texttt{execute} cannot execute a program indefinitely.
[571]472An alternative approach would be to produce an infinite stream of statuses representing an execution trace.
[565]473Matita supports infinite streams through co-inductive types.
[524]474
[517]475%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
476% SECTION                                                                      %
477%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
478\subsection{Instruction set unorthogonality}
479\label{subsect.instruction.set.unorthogonality}
480
[571]481A peculiarity of the MCS-51 is its unorthogonal instruction set.
482For instance, the \texttt{MOV} instruction can be invoked using one of 16 combinations of addressing modes out of a possible 361.
[508]483
[520]484% Show example of pattern matching with polymorphic variants
485
[571]486Such unorthogonality in the instruction set was handled with the use of polymorphic variants in O'Caml.
[508]487For instance, we introduced types corresponding to each addressing mode:
488\begin{lstlisting}
489type direct = [ DIRECT of byte ]
490type indirect = [ INDIRECT of bit ]
491...
492\end{lstlisting}
[574]493Which were then combined in the inductive datatype for assembly preinstructions using the union operator $|$':
[508]494\begin{lstlisting}
496 [ ADD of acc * [ reg | direct | indirect | data ]
497...
498 | MOV of
499    (acc * [ reg | direct | indirect | data ],
500     [ reg | indirect ] * [ acc | direct | data ],
501     direct * [ acc | reg | direct | indirect | data ],
502     dptr * data16,
503     carry * bit,
504     bit * carry
505     ) union6
506...
507\end{lstlisting}
508Here, \texttt{union6} is a disjoint union type, defined as follows:
509\begin{lstlisting}
510type ('a,'b,'c,'d,'e,'f) union6 = [ U1 of 'a | ... | U6 of 'f ]
511\end{lstlisting}
[510]512For our purposes, the types \texttt{union2}, \texttt{union3} and \texttt{union6} sufficed.
[508]513
[571]514This polymorphic variant machinery worked well: it introduced a certain level of type safety (for instance, the type of \texttt{MOV} above guarantees it cannot be invoked with arguments in the \texttt{carry} and \texttt{data16} addressing modes, respectively), and also allowed us to pattern match against instructions, when necessary.
[510]515However, this polymorphic variant machinery is \emph{not} present in Matita.
516We needed some way to produce the same effect, which Matita supported.
517For this task, we used dependent types.
[508]518
[510]519We first provided an inductive data type representing all possible addressing modes, a type that functions will pattern match against:
[495]520\begin{lstlisting}
[495]522  DIRECT: Byte $\rightarrow$ addressing_mode
523| INDIRECT: Bit $\rightarrow$ addressing_mode
524...
525\end{lstlisting}
[510]526We also wished to express in the type of functions the \emph{impossibility} of pattern matching against certain constructors.
527In order to do this, we introduced an inductive type of addressing mode tags'.
528The constructors of \texttt{addressing\_mode\_tag} are in one-to-one correspondence with the constructors of \texttt{addressing\_mode}:
[495]529\begin{lstlisting}
533...
534\end{lstlisting}
[495]536\begin{lstlisting}
[495]538  match d with
539   [ direct $\Rightarrow$ match A with [ DIRECT _ $\Rightarrow$ true | _ $\Rightarrow$ false ]
540   | indirect $\Rightarrow$ match A with [ INDIRECT _ $\Rightarrow$ true | _ $\Rightarrow$ false ]
541...
542\end{lstlisting}
[561]543The \texttt{is\_in} function checks if an \texttt{addressing\_mode} matches a set of tags represented as a vector. It simply extends the \texttt{is\_a} function in the obvious manner.
544
[571]545A \texttt{subaddressing\_mode} is an \emph{ad hoc} non-empty $\Sigma$-type of \texttt{addressing\_mode}s constrained to be in a set of tags:
[495]546\begin{lstlisting}
[495]550\end{lstlisting}
[571]551An implicit coercion is provided to promote vectors of tags (denoted with $\llbracket - \rrbracket$) to the corresponding \texttt{subaddressing\_mode} so that we can use a syntax close to that of O'Caml to specify \texttt{preinstruction}s:
[495]552\begin{lstlisting}
[510]553inductive preinstruction (A: Type[0]): Type[0] ≝
[495]554   ADD: $\llbracket$ acc_a $\rrbracket$ $\rightarrow$ $\llbracket$ register; direct; indirect; data $\rrbracket$ $\rightarrow$ preinstruction A
555 | ADDC: $\llbracket$ acc_a $\rrbracket$ $\rightarrow$ $\llbracket$ register; direct; indirect; data $\rrbracket$ $\rightarrow$ preinstruction A
556...
557\end{lstlisting}
[568]558The constructor \texttt{ADD} expects two parameters, the first being the accumulator A (\texttt{acc\_a}), the second being a register, direct, indirect or data addressing mode.
[495]559
[520]560% One of these coercions opens up a proof obligation which needs discussing
561% Have lemmas proving that if an element is a member of a sub, then it is a member of a superlist, and so on
[571]562The final component is a pair of type coercions from \texttt{addressing\_mode} to \texttt{subaddressing\_mode} and from \texttt{subaddressing\_mode} to \texttt{Type$\lbrack0\rbrack$}, respectively.
[565]563The first is a forgetful coercion, while the second opens a proof obligation wherein we must prove that the provided value is in the admissible set.
[571]564These coercions were first introduced by PVS to implement subset types~\cite{shankar:principles:1999}, and later in Coq as part of Russell~\cite{sozeau:subset:2006}.
[565]565In Matita all coercions can open proof obligations.
[539]566
[571]567Proof obligations require us to state and prove a few auxilliary lemmas related to the transitivity of subtyping.
568For instance, an \texttt{addressing\_mode} that belongs to an allowed set also belongs to any one of its supersets.
[574]569At the moment, Matita's automation exploits these lemmas to completely solve all the proof obligations opened in the formalisation.
[571]570The \texttt{execute\_1} function, for instance, opens over 200 proof obligations during type checking.
[561]571
[571]572The machinery just described allows us to restrict the set of \texttt{addressing\_mode}s expected by a function and use this information during pattern matching.
573This allows us to skip impossible cases.
[495]574For instance, consider \texttt{set\_arg\_16}, which expects only a \texttt{DPTR}:
575\begin{lstlisting}
[561]576definition set_arg_16: Status $\rightarrow$ Word $\rightarrow$ $\llbracket$ dptr $\rrbracket$ $\rightarrow$ Status ≝ $~\lambda$s, v, a.
[495]577   match a return $\lambda$x. bool_to_Prop (is_in ? $\llbracket$ dptr $\rrbracket$ x) $\rightarrow$ ? with
578     [ DPTR $\Rightarrow$ $\lambda$_: True.
579       let 〈 bu, bl 〉 := split $\ldots$ eight eight v in
580       let status := set_8051_sfr s SFR_DPH bu in
581       let status := set_8051_sfr status SFR_DPL bl in
582         status
[561]583     | _ $\Rightarrow$ $\lambda$_: False. $\bot$ ] $~$(subaddressing_modein $\ldots$ a).
[495]584\end{lstlisting}
[571]585We give a proof (the expression \texttt{(subaddressing\_modein} $\ldots$ \texttt{a)}) that the argument $a$ is in the set $\llbracket$ \texttt{dptr} $\rrbracket$ to the \texttt{match} expression.
[565]586In every case but \texttt{DPTR}, the proof is a proof of \texttt{False}, and the system opens a proof obligation $\bot$ that can be discarded using \emph{ex falso}.
[571]587Attempting to match against a disallowed addressing mode (replacing \texttt{False} with \texttt{True} in the branch) produces a type error.
[495]588
[571]589We tried other dependently and non-dependently typed solutions before settling on this approach.
590As we need a large number of different combinations of addressing modes to describe the whole instruction set, it is infeasible to declare a datatype for each one of these combinations.
591The current solution is closest to the corresponding O'Caml code, to the point that the translation from O'Caml to Matita is almost syntactical.
592We would like to investigate the possibility of changing the code extraction procedure of Matita so that it recognises this programming pattern and outputs O'Caml code using polymorphic variants.
[561]593
[520]594% Talk about extraction to O'Caml code, which hopefully will allow us to extract back to using polymorphic variants, or when extracting vectors we could extract using phantom types
595% Discuss alternative approaches, i.e. Sigma types to piece together smaller types into larger ones, as opposed to using a predicate to cut out' pieces of a larger type, which is what we did
596
[494]597%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
598% SECTION                                                                      %
599%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[521]600\subsection{I/O and timers}
601\label{subsect.i/o.timers}
602
603% Real clock' for I/O and timers
[545]604The O'Caml emulator has code for handling timers, asynchronous I/O and interrupts (these are not yet ported to the Matita emulator).
[525]605All three of these features interact with each other in subtle ways.
[565]606Interrupts can fire' when an input is detected on the processor's UART port, and, in certain modes, timers reset when a high signal is detected on one of the MCS-51's communication pins.
[521]607
[548]608To accurately model timers and I/O, we add an unbounded integral field \texttt{clock} to the central \texttt{status} record.
[571]609This field is only logical, since it does not represent any quantity stored in the physical processor, and is used to keep track of the current processor time'.
[548]610Before every execution step, \texttt{clock} is incremented by the number of processor cycles that the instruction just fetched will take to execute.
[571]611The emulator then executes the instruction, followed by the code implementing the timers and I/O\footnote{Though it isn't fully specified by the manufacturer's data sheets if I/O is handled at the beginning or the end of each cycle.}.
612In order to model I/O, we also store in \texttt{status} a \emph{continuation} which is a description of the behaviour of the environment:
[536]613\begin{lstlisting}
614type line =
615  [ P1 of byte | P3 of byte
616  | SerialBuff of [ Eight of byte | Nine of BitVectors.bit * byte ]]
617type continuation =
618  [In of time * line * epsilon * continuation] option *
619  [Out of (time -> line -> time * continuation)]
620\end{lstlisting}
[571]621At each moment, the second projection of the continuation $k$ describes how the environment will react to an output event performed in the future by the processor.
622Suppose $\pi_2(k)(\tau,o) = \langle \tau',k' \rangle$.
623If the emulator at time $\tau$ starts an asynchronous output $o$ either on the P1 or P3 output lines, or on the UART, then the environment will receive the output at time $\tau'$.
624Moreover \texttt{status} is immediately updated with the continuation $k'$.
[525]625
[571]626Further, if $\pi_1(k) = \mathtt{Some}~\langle \tau',i,\epsilon,k'\rangle$, then at time $\tau'$ the environment will send the asynchronous input $i$ to the emulator and \texttt{status} is updated with the continuation $k'$.
627This input is visible to the emulator only at time $\tau' + \epsilon$.
[537]628
[548]629The time required to perform an I/O operation is partially specified in the data sheets of the UART module.
[565]630This computation is complex so we prefer to abstract over it.
631We leave the computation of the delay time to the environment.
[545]632
[574]633We use only the P1 and P3 lines despite the MCS-51 having 4 output lines, P0--P3.
[571]634This is because P0 and P2 become inoperable if the processor is equipped with XRAM (we assume it is).
[545]635
[548]636The UART port can work in several modes, depending on the how the SFRs are set.
[571]637In an asyncrhonous mode, the UART transmits 8 bits at a time, using a ninth line for synchronisation.
638In a synchronous mode the ninth line is used to transmit an additional bit.
[548]639
[521]640%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
641% SECTION                                                                      %
642%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
643\subsection{Computation of cost traces}
644\label{subsect.computation.cost.traces}
645
[529]646As mentioned in Subsection~\ref{subsect.labels.pseudoinstructions} we introduced a notion of \emph{cost label}.
[571]647Cost labels are inserted by the prototype C compiler at specific locations in the object code.
[529]648Roughly, for those familiar with control flow graphs, they are inserted at the start of every basic block.
[521]649
[529]650Cost labels are used to calculate a precise costing for a program by marking the location of basic blocks.
651During the assembly phase, where labels and pseudoinstructions are eliminated, a map is generated associating cost labels with memory locations.
652This map is later used in a separate analysis which computes the cost of a program by traversing through a program, fetching one instruction at a time, and computing the cost of blocks.
653These block costings are stored in another map, and will later be passed back to the prototype compiler.
654
[521]655%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
656% SECTION                                                                      %
657%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[494]658\section{Validation}
659\label{sect.validation}
660
[565]661We spent considerable effort attempting to ensure that what we have formalised is an accurate model of the MCS-51 microprocessor.
[511]662
[571]663We made use of multiple data sheets, each from a different semiconductor manufacturer.
664This helped us triangulate errors in the specification of the processor's instruction set, and its behaviour, for instance, in a data sheet from Philips Semiconductor.
[511]665
666The O'Caml prototype was especially useful for validation purposes.
[571]667We wrote a module for parsing and loading Intel HEX format files.
668Intel HEX is a standard format that all compilers targetting the MCS-51, and similar processors, produce.
[511]669It is essentially a snapshot of the processor's code memory in compressed form.
[574]670Using this we were able to compile C programs with SDCC and load the resulting program directly into the emulator's code memory, ready for execution.
671Further, we can produce a HEX file from the emulator's code memory for loading into third party tools.
[571]672After each step of execution, we can print out both the instruction that had been executed and a snapshot of the processor's state, including all flags and register contents.
[511]673For example:
674\begin{frametxt}
[562]675\begin{small}
[511]676\begin{verbatim}
677...
67808: mov 81 #07
679
680 Processor status:
681
[560]682   ACC: 0   B: 0   PSW: 0
[546]683    with flags set as:
[560]684     CY: false  AC: false  FO: false  RS1: false
685     RS0: false  OV: false UD: false  P: false
686   SP: 7  IP: 0  PC: 8  DPL: 0  DPH: 0  SCON: 0
687   SBUF: 0  TMOD: 0  TCON: 0
[511]688   Registers:
[560]689    R0: 0  R1: 0  R2: 0  R3: 0  R4: 0  R5: 0  R6: 0  R7: 0
[511]690...
691\end{verbatim}
[562]692\end{small}
[511]693\end{frametxt}
[571]694Here, the trace indicates that the instruction \texttt{mov 81 \#07} has just been executed by the processor, which is now in the state indicated.
[511]695These traces were useful in spotting anything that was obviously' wrong with the execution of the program.
696
[571]697We further used MCU 8051 IDE as a reference, which allows a user to step through an assembly program one instruction at a time.
[574]698Using these execution traces, we were able to step through a compiled program in MCU 8051 IDE and compare the resulting execution trace with the trace produced by our emulator.
[511]699
[574]700The Matita formalisation was largely copied from the O'Caml source code, apart from the changes already mentioned.
[511]701However, as the Matita emulator is executable, we could perform further validation by comparing the trace of a program's execution in the Matita emulator with the trace of the same program in the O'Caml emulator.
702
[494]703%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
704% SECTION                                                                      %
705%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[493]706\section{Related work}
707\label{sect.related.work}
[571]708A large body of literature on the formalisation of microprocessors exists.
709The majority of it deals with proving correctness of implementations of microprocessors at the microcode or gate level.
710We are interested in providing a precise specification of the behaviour of the microprocessor in order to prove the correctness of a compiler which will target the processor.
[546]711In particular, we are interested in intensional properties of the processor; precise timings of instruction execution in clock cycles.
[571]712Moreover, in addition to formalising the interface of an MCS-51 processor, we have also built a complete MCS-51 ecosystem: UART, I/O lines, and hardware timers, complete with an assembler.
[493]713
[571]714Work closely related to our own can be found in~\cite{fox:trustworthy:2010}.
715Here, the authors describe the formalisation, in HOL4, of the ARMv7 instruction set architecture.
716They further point to an excellent list of references to related work in the literature for the interested reader.
717This formalisation also considers the machine code level, opposed to their formalisation, which only considering an abstract assembly language.
718In particular, instruction decoding is explicitly modeled inside HOL4's logic.
719We go further in also providing an assembly language, complete with assembler, to translate instructions and pseudoinstruction into machine code.
[526]720
[549]721Further, in~\cite{fox:trustworthy:2010} the authors validated their formalisation by using development boards and random testing.
[562]722We currently rely on non-exhaustive testing against a third party emulator.
[571]723We recognise the importance of this exhaustive testing, but currently leave it for future work.
[526]724
[571]725Executability is another key difference between our work and that of~\cite{fox:trustworthy:2010}.
726Our formalisation is executable: applying the emulation function to an input state eventually reduces to an output state.
727This is because Matita is based on a logic, CIC, which internalizes conversion.
[549]728In~\cite{fox:trustworthy:2010} the authors provide an automation layer to derive single step theorems: if the processor is in a particular state that satisfies some preconditions, then after execution of an instruction it will reside in another state satisfying some postconditions.
[546]729We do not need single step theorems of this form.
[526]730
[546]731Our main difficulties resided in the non-uniformity of an old 8-bit architecture, in terms of the instruction set, addressing modes and memory models.
732In contrast, the ARM instruction set and memory model is relatively uniform, simplifying any formalisation considerably.
[526]733
[563]734Perhaps the closest project to CerCo is CompCert~\cite{leroy:formally:2009}.
735CompCert concerns the certification of a C compiler and includes a formalisation in Coq of a subset of PowerPC.
[571]736(Coq and Matita essentially share the same logic.)
[526]737
[546]738Despite this similarity, the two formalisations do not have much in common.
[571]739First, CompCert provides a formalisation at the assembly level (no instruction decoding).
740This impels them to trust an unformalised assembler and linker, whereas we provide our own.
741Our formalisation is \emph{directly} executable, while the one in CompCert only provides a relation that describes execution.
[546]742I/O is also not considered at all in CompCert.
743Moreover an idealized abstract and uniform memory model is assumed, while we take into account the complicated overlapping memory model of the MCS-51 architecture.
[571]744Finally, 82 instructions of the more than 200 offered by the processor are formalised in CompCert, and the assembly language is augmented with macro instructions that are turned into real' instructions only during communication with the external assembler.
745Even from a technical level the two formalisations differ: we tried to exploit dependent types whilst CompCert largely sticks to a non-dependent fragment of Coq.
[526]746
[571]747In~\cite{atkey:coqjvm:2007} an executable specification of the Java Virtual Machine, using dependent types, is presented.
748As we do, dependent types there are used to remove spurious partiality from the model.
749They also lower the need for over-specifying the behaviour of the processor in impossible cases.
750Our use of dependent types will also help to maintain invariants when we prove the correctness of the CerCo prototype C compiler.
[526]751
[571]752Finally~\cite{sarkar:semantics:2009} provides an executable semantics for x86-CC multiprocessor machine code.
[548]753This machine code exhibits a high degree of non-uniformity similar to the MCS-51.
[565]754However, only a small subset of the instruction set is considered, and they over-approximate the possibilities of unorthogonality of the instruction set, largely dodging the problems we had to face.
[526]755
[548]756Further, it seems that the definition of the decode function is potentially error prone.
757A small domain specific language of patterns is formalised in HOL4.
758This is similar to the specification language of the x86 instruction set found in manufacturer's data sheets.
[571]759A decode function is implemented by copying lines from data sheets into the proof script, which are then interpreted.
[526]760
[548]761We are currently considering implementing a similar domain specific language in Matita.
762However, we would prefer to certify in Matita the compiler for this language.
763Data sheets could then be compiled down to the efficient code that we currently provide, instead of inefficiently interpreting the data sheets every time an instruction is executed.
764
[493]765%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
766% SECTION                                                                      %
767%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
768\section{Conclusions}
769\label{sect.conclusions}
770
[571]771In CerCo, we are interested in the certification of a compiler for C that induces a precise cost model on the source code.
772Our cost model assigns costs to blocks of instructions by tracing the way that blocks are compiled, and by computing exact costs on generated machine language.
773To perform this accurately, we have provided an executable semantics for the MCS-51 family of processors.
774The formalisation was done twice, first in O'Caml and then in Matita, and captures the exact timings of the processor (according to a Siemen's data sheet).
[565]775Moreover, the O'Caml formalisation also considers timers and I/O.
[571]776Adding support for I/O and timers in Matita is on-going work that will not present any major problem, and was delayed only because the addition is not immediately useful for the formalisation of the CerCo compiler.
[542]777
[565]778The formalisation is done at machine level and not at assembly level; we also formalise fetching and decoding.
[569]779We separately provide an assembly language, enhanched with labels and pseudoinstructions, and an assembler from this language to machine code.
[571]780This assembly language is similar to those found in `industrial strength' compilers, such as SDCC.
[565]781We introduce cost labels in the machine language to relate the data flow of the assembly program to that of the C source language, in order to associate costs to the C program.
782For the O'Caml version, we provide a parser and pretty printer from code memory to Intel HEX format.
783Hence we can perform testing on programs compiled using any free or commercial compiler.
[542]784
[565]785Our main difficulty in formalising the MCS-51 was the unorthogonality of its memory model and instruction set.
786These problems are easily handled in O'Caml by using advanced language features like polymorphic variants and phantom types, simulating Generalized Abstract Data Types.
[571]787In Matita, we use dependent types to recover the same flexibility, to reduce spurious partiality, and to grant invariants that will be later useful in other formalisations in the CerCo project.
[564]788
[565]789The formalisation has been partially verified by computing execution traces on selected programs and comparing them with an existing emulator.
790All instructions have been tested at least once, but we have not yet pushed testing further, for example with random testing or by using development boards.
791I/O in particular has not been tested yet, and it is currently unclear how to provide exhaustive testing in the presence of I/O.
[571]792Finally, we are aware of having over-specified the processor in several places, by fixing a behaviour hopefully consistent with the real machine, where manufacturer data sheets are ambiguous or under-specified.
[564]793
[549]794\bibliography{itp-2011.bib}
795
[557]796\end{document}
Note: See TracBrowser for help on using the repository browser.