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

Last change on this file since 565 was 565, checked in by mulligan, 9 years ago

down to 16 pages after a bit of rewriting

File size: 57.4 KB
20        {\setlength{\fboxsep}{5pt}
21                \setlength{\mylength}{\linewidth}%
22                \addtolength{\mylength}{-2\fboxsep}%
23                \addtolength{\mylength}{-2\fboxrule}%
24                \Sbox
25                \minipage{\mylength}%
26                        \setlength{\abovedisplayskip}{0pt}%
27                        \setlength{\belowdisplayskip}{0pt}%
28                }%
29                {\endminipage\endSbox
30                        \[\fbox{\TheSbox}\]}
[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  }
39        keywordstyle=\color{red}\bfseries,
40        keywordstyle=[2]\color{blue},
41        keywordstyle=[3]\color{blue}\bfseries,
42        commentstyle=\color{green},
43        stringstyle=\color{blue},
44        showspaces=false,showstringspaces=false}
[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}
[495]68We summarise our formalisation of an emulator for the MCS-51 microprocessor in the Matita proof assistant.
69The MCS-51 is a widely used 8-bit microprocessor, especially popular in embedded devices.
71We proceeded in two stages, first implementing in O'Caml a prototype emulator, where bugs could be `ironed out' quickly.
72We then ported our O'Caml emulator to Matita's internal language.
73Though mostly straight-forward, this porting presented multiple problems.
74Of particular interest is how we handle the extreme non-orthoganality of the MSC-51's instruction set.
75In O'Caml, this was handled through heavy use of polymorphic variants.
[501]76In Matita, we achieve the same effect through a non-standard use of dependent types.
78Both the O'Caml and Matita emulators are `executable'.
79Assembly programs may be animated within Matita, producing a trace of instructions executed.
81Our formalisation is a major component of the ongoing EU-funded CerCo project.
85% SECTION                                                                      %
[512]90Formal methods are designed to increase our confidence in the design and implementation of software (and hardware).
[551]91Ideally, we would like all software to come equipped with a formal specification, along with a proof of correctness that the software meets this specification.
92Today the majority of programs are written in high level languages and then compiled into low level ones.
[512]93Specifications are therefore also given at a high level and correctness can be proved by reasoning automatically or interactively on the program's source code.
94The code that is actually run, however, is not the high level source code that we reason on, but the object code that is generated by the compiler.
[565]95A few questions now arise:
[509]98What properties are preserved during compilation?
[509]100What properties are affected by the compilation strategy?
[509]102To what extent can you trust your compiler in preserving those properties?
[555]104These 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]105So far, the field has only been focused on the first and last questions.
106Much attention has been placed on verifying compiler correctness with respect to extensional properties of programs, which are easily preserved during compilation; it is sufficient to completely preserve the denotational semantics of the input program.
[565]108If we consider intensional properties of programs---space, time, and so forth---the situation is more complex.
109To express these properties, and reason about them, we must adopt a cost model that assigns a cost to single, or blocks, of instructions.
110A compositional cost model---assigning the same cost to all occurrences of one instruction---would be ideal.
111However, 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]112Therefore both the cost model and intensional specifications are affected by the compilation process.
[565]114In the CerCo project (`Certified Complexity')~\cite{cerco:2011} we approach the problem of reasoning about intensional properties of programs as follows.
115We are currently developing a compiler that induces a cost model on high level source code.
116Costs are assigned to each block of high level instructions by considering the costs of the corresponding blocks of compiled code.
117The cost model is therefore inherently non-compositional, but has the potential to be extremely \emph{precise}, capturing a program's \emph{realistic} cost.
118That is, the compilation process is taken into account, not ignored.
[514]119A prototype compiler, where no approximation of the cost is provided, has been developed.
[565]120(The technical details of the cost model is explained in~\cite{amadio:certifying:2010}.)
[565]122We believe that our approach is applicable to certifying real time programs.
123A 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.
[565]125We also see our approach as being relevant to the compiler verification (and construction) itself.
126An optimisation specified only extensionally is only half specified; though the optimisation may preserve the denotational semantics of a program, there is no guarantee that any intensional properties of the program will be improved.
[515]127Another potential application is toward completeness and correctness of the compilation process in the presence of space constraints.
[565]128A compiler could potentially reject a source program targetting an embedded system when the size of the compiled code exceeds the available ROM size.
129Preservation of a program's semantics may only be required for those programs that do not exhaust the stack or heap.
[515]130Hence the statement of completeness of the compiler must take in to account a realistic cost model.
[565]132With the CerCo methodology, we assume we can assign to the object code exact and realistic costs for sequential blocks of instructions.
133This is possible with modern processors (see~\cite{bate:wcet:2011,yan:wcet:2008} for instance) but difficult, as the execution of a program has an influence on the speed of processing.
134Caching, memory effects, and other advanced features such as branch prediction all have a profound effect on execution speeds.
[515]135For this reason CerCo decided to focus on 8-bit microprocessors.
[565]136These are still widely used in embedded systems, with the advantage of an easily predictable cost model due to their relative paucity of features.
[565]138We 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.
139The latter is what we describe in this paper.
140The focus of the formalisation has been on capturing the intensional behaviour of the processor.
[515]141However, the design of the MCS-51 itself has caused problems in our formalisation.
142For example, the MCS-51 has a highly unorthogonal instruction set.
[565]143To cope with this unorthogonality, and to produce an executable specification, we have Matita's dependent types.
[493]145\subsection{The 8051/8052}
148The MCS-51 is an eight bit microprocessor introduced by Intel in the late 1970s.
149Commonly called the 8051, in the three decades since its introduction the processor has become a highly popular target for embedded systems engineers.
[515]150Further, the processor, its immediate successor the 8052, and many derivatives are still manufactured \emph{en masse} by a host of semiconductor suppliers.
152The 8051 is a well documented processor, and has the additional support of numerous open source and commercial tools, such as compilers for high-level languages and emulators.
[550]153For instance, the open source Small Device C Compiler (SDCC) recognises a dialect of C~\cite{sdcc:2010}, and other compilers targeting the 8051 for BASIC, Forth and Modula-2 are also extant.
154An open source emulator for the processor, MCU-8051 IDE, is also available~\cite{mcu8051ide:2010}.
[515]155Both MCU-8051 IDE and SDCC were used profitably in the implementation of our formalisation.
161\put(12,410){\makebox(80,0)[b]{Internal (256B)}}
165\put(12,400){\makebox(0,0)[r]{0h}}  \put(14,400){\makebox(0,0)[l]{Register bank 0}}
167\put(12,386){\makebox(0,0)[r]{8h}}  \put(14,386){\makebox(0,0)[l]{Register bank 1}}
169\put(12,372){\makebox(0,0)[r]{10h}}  \put(14,372){\makebox(0,0)[l]{Register bank 2}}
171\put(12,358){\makebox(0,0)[r]{18h}} \put(14,358){\makebox(0,0)[l]{Register bank 3}}
173\put(12,344){\makebox(0,0)[r]{20h}} \put(14,344){\makebox(0,0)[l]{Bit addressable}}
176  \put(14,309){\makebox(0,0)[l]{\quad \vdots}}
179  \put(14,263){\makebox(0,0)[l]{\quad \vdots}}
196% bit access to sfrs?
204\put(164,410){\makebox(80,0)[b]{External (64kB)}}
210\put(164,324){\makebox(80,0){Paged access}}
211  \put(164,310){\makebox(80,0){Direct/indirect}}
213  \put(164,228){\makebox(80,0){\vdots}}
214  \put(164,210){\makebox(80,0){Direct/indirect}}
216\put(264,410){\makebox(80,0)[b]{Code (64kB)}}
221  \put(264,228){\makebox(80,0){\vdots}}
222  \put(264,324){\makebox(80,0){Direct}}
223  \put(264,310){\makebox(80,0){PC relative}}
225\caption{The 8051 memory model}
229The 8051 has a relatively straightforward architecture, unencumbered by advanced features of modern processors, making it an ideal target for formalisation.
[559]230A 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}.
232Processor RAM is divided into numerous segments, with the most prominent division being between internal and (optional) external memory.
[552]233Internal 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) which control the operation of the processor.
[516]234Internal RAM (IRAM) is further divided into eight general purpose bit-addressable registers (R0--R7).
[493]235These sit in the first eight bytes of IRAM, though can be programmatically `shifted up' as needed.
[516]236Bit memory, followed by a small amount of stack space, resides in the memory space immediately after the register banks.
[493]237What remains of the IRAM may be treated as general purpose memory.
[559]238A schematic view of IRAM layout is also provided in Figure~\ref{fig.memory.layout}.
[516]240External RAM (XRAM), limited to a maximum size of 64 kilobytes, is optional, and may be provided on or off chip, depending on the manufacturer.
241XRAM is accessed using a dedicated instruction, and requires sixteen bits to address fully.
[493]242External code memory (XCODE) is often stored in the form of an EPROM, and limited to 64 kilobytes in size.
243However, depending on the particular manufacturer and processor model, a dedicated on-die read-only memory area for program code (ICODE) may also be supplied.
245Memory may be addressed in numerous ways: immediate, direct, indirect, external direct and code indirect.
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.
[553]247For instance, the 128 bytes of extra internal RAM that the 8052 features cannot be addressed using indirect addressing; rather, external (in)direct addressing must be used. Moreover, some memory segments are addressed using 8 bits pointers while others require 16 bits.
249The 8051 series possesses an eight bit Arithmetic and Logic Unit (ALU), with a wide variety of instructions for performing arithmetic and logical operations on bits and integers.
250Further, the processor possesses two eight bit general purpose accumulators, A and B.
252Communication with the device is facilitated by an onboard UART serial port, and associated serial controller, which can operate in numerous modes.
253Serial baud rate is determined by one of two sixteen bit timers included with the 8051, which can be set to multiple modes of operation.
254(The 8052 provides an additional sixteen bit timer.)
255As an additional method of communication, the 8051 also provides a four byte bit-addressable input-output port.
257The programmer may take advantage of the interrupt mechanism that the processor provides.
258This is especially useful when dealing with input or output involving the serial device, as an interrupt can be set when a whole character is sent or received via the serial port.
260Interrupts 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.
261However, interrupts may be set to one of two priorities: low and high.
262The 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.
264The 8051 has interrupts disabled by default.
265The programmer is free to handle serial input and output manually, by poking serial flags in the SFRs.
[565]266`Exceptional circumstances' that would otherwise trigger an interrupt on more modern processors, (e.g. division by zero) are also signalled by setting flags.
272%\caption{Schematic view of 8051 IRAM layout}
277% SECTION                                                                      %
279\subsection{Overview of paper}
[538]282In Section~\ref{} we discuss design issues in the development of the formalisation.
283In Section~\ref{sect.validation} we discuss how we validated the design and implementation of our emulator to ensure that what we formalised was an accurate model of an MCS-51 series microprocessor.
284In Section~\ref{} we describe previous work, with an eye toward describing its relation with the work described herein.
[565]285In Section~\ref{sect.conclusions} we conclude.
288% SECTION                                                                      %
[527]290\section{Design issues in the formalisation}
[540]293From hereonin, we typeset O'Caml source with \texttt{\color{blue}{blue}} and Matita source with \texttt{\color{red}{red}} to distinguish the two syntaxes.
294Matita's syntax is largely straightforward to those familiar with Coq or O'Caml.
[554]295The only subtlety is the use of `\texttt{?}' in an argument position denoting an argument that should be inferred automatically.
[557]297A full account of the formalisation can be found in~\cite{cerco-report:2011}.
[527]299\subsection{Development strategy}
[538]302Our implementation progressed in two stages.
[565]303We began with an emulator written in O'Caml to `iron out' any bugs in our design and implementation.
304O'Caml's ability to perform file I/O also eased debugging and validation.
[506]305Once we were happy with the performance and design of the O'Caml emulator, we moved to the Matita formalisation.
[506]307Matita's syntax is lexically similar to O'Caml's.
[565]308This eased the translation, as code was merely copied with minor modifications.
309However, several major issues had to be addresses when moving from to Matita.
[506]310These are now discussed.
313% SECTION                                                                      %
[554]315\subsection{Representation of bytes, words, etc.}
322type 'a vect = bit list
[554]323type nibble = [`Sixteen] vect
[527]324type byte = [`Eight] vect
[554]325$\color{blue}{\mathtt{let}}$ split_word w = split_nth 4 w
326$\color{blue}{\mathtt{let}}$ split_byte b = split_nth 2 b
[532]333type 'a vect
334type word = [`Sixteen] vect
335type byte = [`Eight] vect
[554]336val split_word: word -> byte * word
337val split_byte: byte -> nibble * nibble
340\caption{Sample of O'Caml implementation and interface for bitvectors module}
[555]344The formalization of MCS-51 must deal with bytes (8 bits), words (16 bits) but also with more exoteric quantities (7 bits, 3 bits, 9 bits).
345To avoid size mismatch bugs difficult to spot, we represent all of these quantities using bitvectors, i.e. fixed length vectors of booleans.
[557]346In our 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]347From within the bitvector module (left column) bitvectors are just lists of bits and no guarantee is provided on sizes.
348However, the module's interface (right column) enforces the size invariants in the rest of the code.
[554]350In Matita, we are able to use the full power of dependent types to always work with vectors of a known size:
352inductive Vector (A: Type[0]): nat → Type[0] ≝
353  VEmpty: Vector A O
354| VCons: ∀n: nat. A → Vector A n → Vector A (S n).
356We define \texttt{BitVector} as a specialization of \texttt{Vector} to \texttt{bool}.
[554]357We may use Matita's type system to provide precise typing for functions that are
358polymorphic in the size without having to duplicate the code as we did in O'Caml:
360let rec split (A: Type[0]) (m,n: nat) on m:
361   Vector A (plus m n) $\rightarrow$ (Vector A m) $\times$ (Vector A n) := ...
365% SECTION                                                                      %
[511]367\subsection{Representing memory}
[565]370The MCS-51 has numerous disjoint memory spaces addressed by pointers of different sizes.
371In our prototype implementation, we use a map data structure (from O'Caml's standard library) for each space.
372Matita's standard library is small, and does not contain a generic map data structure.
373We 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.
374We assumed that large swathes of memory would often be uninitialized.
[565]376We picked a modified form of trie of fixed height $h$.
377Paths are represented by bitvectors (already used in our implementation for addresses and registers) of length $h$:
379inductive BitVectorTrie (A: Type[0]): nat $\rightarrow$ Type[0] ≝
380  Leaf: A $\rightarrow$ BitVectorTrie A 0
381| Node: ∀n. BitVectorTrie A n $\rightarrow$ BitVectorTrie A n $\rightarrow$ BitVectorTrie A (S n)
382| Stub: ∀n. BitVectorTrie A n.
[565]384\texttt{Stub} is a constructor that can appear at any point in a trie.
385It represents `uninitialized data'.
[516]386Performing a lookup in memory is now straight-forward.
[565]387We traverse a path, and if we encounter \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.}.
390% SECTION                                                                      %
[519]392\subsection{Labels and pseudoinstructions}
[523]395Aside from implementing the core MCS-51 instruction set, we also provided \emph{pseudoinstructions}, \emph{labels} and \emph{cost labels}.
396The purpose of \emph{cost labels} will be explained in Subsection~\ref{subsect.computation.cost.traces}.
[522]398Introducing 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]399To see why, consider the fact that the MCS-51's instruction set has numerous instructions for unconditional and conditional jumps to memory locations.
[519]400For instance, the instructions \texttt{AJMP}, \texttt{JMP} and \texttt{LJMP} all perform unconditional jumps.
401However, these instructions differ in how large the maximum size of the offset of the jump to be performed can be.
[522]402Further, all jump instructions require a concrete memory address---to jump to---to be specified.
[565]403Compilers that support separate compilation cannot directly compute these offsets and select the appropriate jump instructions.
404These operations are also burdensome for compilers that do not do separate compilation and are handled by the assemblers, as we decided to do.
[565]406While introducing pseudoinstructions, we also introduced labels for locations to jump to, and for global data.
407To specify global data via labels, we introduced a preamble before the program where labels and the size of reserved space for data is associated.
[522]408A pseudoinstruction \texttt{Mov} moves (16-bit) data stored at a label into the (16-bit) register \texttt{DPTR}.
[565]410Our pseudoinstructions and labels induce an assembly language similar to that of SDCC.
411All pseudoinstructions and labels are `assembled away' prior to program execution.
412Jumps are computed in two stages.
413A map associating memory addresses to labels is built, before removing pseudojumps with concrete jumps to the correct address.
414The algorithm currently implemented does not try to minimize the object code size by always picking the shortest possible jump instruction.
415A better algorithm is currently left for future work.
418% SECTION                                                                      %
[524]420\subsection{Anatomy of the (Matita) emulator}
[517]423The internal state of our Matita emulator is represented as a record:
[561]425record Status: Type[0] ≝ {
[517]426  code_memory: BitVectorTrie Byte 16;
427  low_internal_ram: BitVectorTrie Byte 7;
428  high_internal_ram: BitVectorTrie Byte 7;
429  external_ram: BitVectorTrie Byte 16;
430  program_counter: Word;
431  special_function_registers_8051: Vector Byte 19;
432  special_function_registers_8052: Vector Byte 5;
[561]433  ...  }.
435This record neatly encapsulates the current memory contents, the program counter, the state of the current SFRs, and so on.
[565]437Here the MCS-51 memory model is implemented using four disjoint memory spaces plus the SFRs.
438From the programmer's point of view, what matters are addressing modes that are in a many-to-many relation with the spaces.
439\texttt{DIRECT} addressing can be used to address either low internal RAM (if the first bit is 0) or the SFRs (if the first bit is 1), for instance.
440That's why DIRECT uses 8-bit addresses but pointers to the low internal RAM only use 7 bits.
441The complexity of the memory model is captured in the \texttt{get\_arg\_XX} and \texttt{set\_arg\_XX} functions that get and set data of size \texttt{XX} from memory, considering all addressing modes
[561]443%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.
[524]445Both the Matita and O'Caml emulators follows the classic `fetch-decode-execute' model of processor operation.
[532]446The next instruction to be processed, indexed by the program counter, is fetched from code memory with \texttt{fetch}.
[524]447An updated program counter, along with the concrete cost, in processor cycles for executing this instruction, is also returned.
[555]448These costs are taken from a Siemens Semiconductor Group data sheet for the MCS-51~\cite{siemens:2011}, and will likely vary across manufacturers and particular derivatives of the processor.
[561]450definition fetch: BitVectorTrie Byte 16 $\rightarrow$ Word $\rightarrow$ instruction $\times$ Word $\times$ nat
[561]452Instruction are assembled to bit encodings by \texttt{assembly1}:
[561]454definition assembly1: instruction $\rightarrow$ list Byte
[565]456An assembly program---comprising a preamble containing global data and a list of pseudoinstructions---is assembled using \texttt{assembly}.
457Pseudoinstructions and labels are eliminated in favour of instructions from the MCS-51 instruction set.
458A map associating memory locations and cost labels (see Subsection~\ref{subsect.computation.cost.traces}) is produced.
[532]460definition assembly:
[561]461  assembly_program $\rightarrow$ option (list Byte $\times$ (BitVectorTrie String 16))
[561]463A single fetch-decode-execute cycle is performed by \texttt{execute\_1}:
[561]465definition execute_1: Status $\rightarrow$ Status
[561]467The \texttt{execute} functions performs a fixed number of cycles by iterating
470let rec execute (n: nat) (s: Status) on n: Status := ...
[565]472This differs from the O'Caml emulator, which executed a program indefinitely.
473A callback function was also accepted as an argument, which could `witness' the execution as it happened, providing a print-out of the processor state.
474Due to Matita's termination requirement, \texttt{execute} cannot execute a program indefinitely.
475An alternative would be to produce an infinite stream of statuses representing an execution trace.
476Matita supports infinite streams through co-inductive types.
479% SECTION                                                                      %
481\subsection{Instruction set unorthogonality}
[508]484A peculiarity of the MCS-51 is the non-orthogonality of its instruction set.
[561]485For instance, the \texttt{MOV} instruction, can be invoked using one of sixteen combinations of addressing modes out of 361.
[520]487% Show example of pattern matching with polymorphic variants
[508]489Such non-orthogonality in the instruction set was handled with the use of polymorphic variants in the O'Caml emulator.
490For instance, we introduced types corresponding to each addressing mode:
492type direct = [ `DIRECT of byte ]
493type indirect = [ `INDIRECT of bit ]
[561]496Which were then combined in our inductive datatype for assembly instructions using the union operator `$|$':
498type 'addr preinstruction =
499 [ `ADD of acc * [ reg | direct | indirect | data ]
501 | `MOV of
502    (acc * [ reg | direct | indirect | data ],
503     [ reg | indirect ] * [ acc | direct | data ],
504     direct * [ acc | reg | direct | indirect | data ],
505     dptr * data16,
506     carry * bit,
507     bit * carry
508     ) union6
511Here, \texttt{union6} is a disjoint union type, defined as follows:
513type ('a,'b,'c,'d,'e,'f) union6 = [ `U1 of 'a | ... | `U6 of 'f ]
[510]515For our purposes, the types \texttt{union2}, \texttt{union3} and \texttt{union6} sufficed.
[510]517This polymorphic variant machinery worked well: it introduced a certain level of type safety (for instance, the type of our \texttt{MOV} instruction 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.
518However, this polymorphic variant machinery is \emph{not} present in Matita.
519We needed some way to produce the same effect, which Matita supported.
520For this task, we used dependent types.
[510]522We first provided an inductive data type representing all possible addressing modes, a type that functions will pattern match against:
[510]524inductive addressing_mode: Type[0] ≝
[495]525  DIRECT: Byte $\rightarrow$ addressing_mode
526| INDIRECT: Bit $\rightarrow$ addressing_mode
[510]529We also wished to express in the type of functions the \emph{impossibility} of pattern matching against certain constructors.
530In order to do this, we introduced an inductive type of addressing mode `tags'.
531The constructors of \texttt{addressing\_mode\_tag} are in one-to-one correspondence with the constructors of \texttt{addressing\_mode}:
[510]533inductive addressing_mode_tag : Type[0] ≝
[495]534  direct: addressing_mode_tag
535| indirect: addressing_mode_tag
[561]538The \texttt{is\_a} function checks if an \texttt{addressing\_mode} matches an \texttt{addressing\_mode\_tag}:
[539]540let rec is_a (d: addressing_mode_tag) (A: addressing_mode) on d :=
[495]541  match d with
542   [ direct $\Rightarrow$ match A with [ DIRECT _ $\Rightarrow$ true | _ $\Rightarrow$ false ]
543   | indirect $\Rightarrow$ match A with [ INDIRECT _ $\Rightarrow$ true | _ $\Rightarrow$ false ]
[561]546The \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.
548Finally, a \texttt{subaddressing\_mode} is an ad-hoc non empty $\Sigma$-type of addressing
549modes constrained to be in a given set of tags:
[561]551record subaddressing_mode n (l: Vector addressing_mode_tag (S n)): Type[0] :=
552 { subaddressing_modeel :> addressing_mode;
553   subaddressing_modein: bool_to_Prop (is_in ? l subaddressing_modeel) }.
[561]555An implicit coercion is provided to promote vectors of tags (denoted with
556$\llbracket - \rrbracket$)
557to the
558corresponding \texttt{subaddressing\_mode} so that we can use a syntax
559close to the O'Caml one to specify preinstructions:
[510]561inductive preinstruction (A: Type[0]): Type[0] ≝
[495]562   ADD: $\llbracket$ acc_a $\rrbracket$ $\rightarrow$ $\llbracket$ register; direct; indirect; data $\rrbracket$ $\rightarrow$ preinstruction A
563 | ADDC: $\llbracket$ acc_a $\rrbracket$ $\rightarrow$ $\llbracket$ register; direct; indirect; data $\rrbracket$ $\rightarrow$ preinstruction A
566We see that the constructor \texttt{ADD} expects two parameters, the first being the accumulator A (\texttt{acc\_a}), and the second being one of a register, direct, indirect or data addressing mode.
[520]568% One of these coercions opens up a proof obligation which needs discussing
569% Have lemmas proving that if an element is a member of a sub, then it is a member of a superlist, and so on
[495]570The final, missing 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]571The 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.
572These coercions were first introduced by PVS to implement subset types~\cite{pvs?}, and later in Coq as an addition~\cite{russell}.
573In Matita all coercions can open proof obligations.
[561]575Proof obligations impels us to state and prove a few auxilliary lemmas related
576to transitivity of subtyping. For instance, an addressing mode that belongs
577to an allowed set also belongs to any one of its super-set. At the moment,
578Matita's automation exploits these lemmas to completely solve all the proof
579obligations opened in our formalization, comprising the 200 proof obligations
580related to the main \texttt{execute\_1} function.
582The machinery just described allows us to restrict the set of addressing
583modes expected by a function and use this information during pattern matching
584to skip impossible cases.
[495]585For instance, consider \texttt{set\_arg\_16}, which expects only a \texttt{DPTR}:
[561]587definition set_arg_16: Status $\rightarrow$ Word $\rightarrow$ $\llbracket$ dptr $\rrbracket$ $\rightarrow$ Status ≝ $~\lambda$s, v, a.
[495]588   match a return $\lambda$x. bool_to_Prop (is_in ? $\llbracket$ dptr $\rrbracket$ x) $\rightarrow$ ? with
589     [ DPTR $\Rightarrow$ $\lambda$_: True.
590       let 〈 bu, bl 〉 := split $\ldots$ eight eight v in
591       let status := set_8051_sfr s SFR_DPH bu in
592       let status := set_8051_sfr status SFR_DPL bl in
593         status
[561]594     | _ $\Rightarrow$ $\lambda$_: False. $\bot$ ] $~$(subaddressing_modein $\ldots$ a).
[565]596We 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 match expression.
597In 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}.
598Attempting to match against a disallowed addressing mode (replacing \texttt{False} with \texttt{True} in the branch) produces a type-error.
[565]600Other dependently and non-dependently typed solutions we tried were clumsy in practice.
601As we need a large number of different combinations of addressing modes to describe the whole instruction set, it is unfeasible to declare a data type for each one of these combinations.
602The current solution is the one that best matches the corresponding O'Caml code, to the point that the translation from O'Caml to Matita is almost syntactical.
603We would like to investigate the possibility of changing the code extraction procedure of Matita to recognise this programming pattern and output O'Caml code using polymorphic variants.
[520]605% 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
606% 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
609% SECTION                                                                      %
[521]611\subsection{I/O and timers}
614% `Real clock' for I/O and timers
[545]615The O'Caml emulator has code for handling timers, asynchronous I/O and interrupts (these are not yet ported to the Matita emulator).
[525]616All three of these features interact with each other in subtle ways.
[565]617Interrupts 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.
[548]619To accurately model timers and I/O, we add an unbounded integral field \texttt{clock} to the central \texttt{status} record.
620This field is only logical, since it does not represent any quantity stored in the actual processor, and is used to keep track of the current processor time.
621Before every execution step, \texttt{clock} is incremented by the number of processor cycles that the instruction just fetched will take to execute.
622The processor 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.}. In order to model I/O, we also store in the status a
[562]623\emph{continuation} which is a description of the behaviour of the environment:
625type line =
626  [ `P1 of byte | `P3 of byte
627  | `SerialBuff of [ `Eight of byte | `Nine of BitVectors.bit * byte ]]
628type continuation =
629  [`In of time * line * epsilon * continuation] option *
630  [`Out of (time -> line -> time * continuation)]
[562]632At 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. Let $\pi_2(k)(\tau,o) = \langle \tau',k' \rangle$.
[548]633If the processor 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'$.
[562]634Moreover the status is immediately updated with the continuation $k'$.
[548]636Further, 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 processor and the status will be updated with the continuation $k'$.
[565]637This input is visible to the processor only at time $\tau' + \epsilon$.
[548]639The time required to perform an I/O operation is partially specified in the data sheets of the UART module.
[565]640This computation is complex so we prefer to abstract over it.
641We leave the computation of the delay time to the environment.
[548]643We use only the P1 and P3 lines despite the MCS-51 having four output lines, P0--P3.
644This is because P0 and P2 become inoperable if the processor is equipped with XRAM (which we assume it is).
[548]646The UART port can work in several modes, depending on the how the SFRs are set.
647In an asyncrhonous mode, the UART transmits eight bits at a time, using a ninth line for syncrhonization.
648In a syncrhonous mode the ninth line is used to transmit an additional bit.
651% SECTION                                                                      %
653\subsection{Computation of cost traces}
[529]656As mentioned in Subsection~\ref{subsect.labels.pseudoinstructions} we introduced a notion of \emph{cost label}.
657Cost labels are inserted by the prototype C compiler in specific locations in the object code.
658Roughly, for those familiar with control flow graphs, they are inserted at the start of every basic block.
[529]660Cost labels are used to calculate a precise costing for a program by marking the location of basic blocks.
661During the assembly phase, where labels and pseudoinstructions are eliminated, a map is generated associating cost labels with memory locations.
662This 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.
663These block costings are stored in another map, and will later be passed back to the prototype compiler.
666% SECTION                                                                      %
[565]671We spent considerable effort attempting to ensure that what we have formalised is an accurate model of the MCS-51 microprocessor.
[562]673First, we made use of multiple data sheets, each from a different semiconductor manufacturer.  This helped us spot errors in the specification of the processor's instruction set, and its behaviour, for instance, in a datasheet from Philips.
675The O'Caml prototype was especially useful for validation purposes.
676This is because we wrote a module for parsing and loading the Intel HEX file format.
677HEX is a standard format that all compilers targetting the MCS-51, and similar processors, produce.
678It is essentially a snapshot of the processor's code memory in compressed form.
679Using this, we were able to compile C programs with SDCC, an open source compiler, and load the resulting program directly into our emulator's code memory, ready for execution.
680Further, we are able to produce a HEX file from our emulator's code memory, for loading into third party tools.
681After each step of execution, we can print out both the instruction that had been executed, along with its arguments, and a snapshot of the processor's state, including all flags and register contents.
682For example:
68708: mov 81 #07
689 Processor status:                               
[560]691   ACC: 0   B: 0   PSW: 0
[546]692    with flags set as:
[560]693     CY: false  AC: false  FO: false  RS1: false
694     RS0: false  OV: false UD: false  P: false
695   SP: 7  IP: 0  PC: 8  DPL: 0  DPH: 0  SCON: 0
696   SBUF: 0  TMOD: 0  TCON: 0
[511]697   Registers:                                   
[560]698    R0: 0  R1: 0  R2: 0  R3: 0  R4: 0  R5: 0  R6: 0  R7: 0
703Here, the traces indicates that the instruction \texttt{mov 81 \#07} has just been executed by the processor, which is now in the state indicated.
704These traces were useful in spotting anything that was `obviously' wrong with the execution of the program.
[549]706Further, we used MCU 8051 IDE as a reference.
707Using our execution traces, we were able to step through a compiled program, one instruction at a time, in MCU 8051 IDE, and compare the resulting execution trace with the trace produced by our emulator.
709Our Matita formalisation was largely copied from the O'Caml source code, apart from changes related to addressing modes already mentioned.
710However, 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.
713% SECTION                                                                      %
[493]715\section{Related work}
[546]717There exists a large body of literature on the formalisation of microprocessors.
718The majority of it aims to prove correctness of the implementation of the microprocessor at the microcode or gate level.
[562]719 We 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]720In particular, we are interested in intensional properties of the processor; precise timings of instruction execution in clock cycles.
721Moreover, in addition to formalising the interface of an MCS-51 processor, we have also built a complete MCS-51 ecosystem: the UART, the I/O lines, and hardware timers, along with an assembler.
[549]723Similar work to ours can be found in~\cite{fox:trustworthy:2010}.
[546]724Here, the authors describe the formalisation, in HOL4, of the ARMv7 instruction set architecture, and point to a good list of references to related work in the literature.
725This formalisation also considers the machine code level, as opposed to only considering an abstract assembly language.
726In particular, instruction decoding is explicitly modelled inside HOL4's logic.
[562]727We go further in also providing an assembly language, complete with assembler, to translate instructions and pseudoinstruction to machine code.
[549]729Further, in~\cite{fox:trustworthy:2010} the authors validated their formalisation by using development boards and random testing.
[562]730We currently rely on non-exhaustive testing against a third party emulator.
731We leave exhaustive testing for future work.
[549]733Executability is another key difference between our work and~\cite{fox:trustworthy:2010}.
[555]734Our formalisation is executable: applying the emulation function to an input state eventually reduces to an output state that already satisfies the appropriate conditions.
735This is because Matita is based on a logic that internalizes conversion.
[549]736In~\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]737We do not need single step theorems of this form.
[546]739Our main difficulties resided in the non-uniformity of an old 8-bit architecture, in terms of the instruction set, addressing modes and memory models.
740In contrast, the ARM instruction set and memory model is relatively uniform, simplifying any formalisation considerably.
[563]742Perhaps the closest project to CerCo is CompCert~\cite{leroy:formally:2009}.
743CompCert concerns the certification of a C compiler and includes a formalisation in Coq of a subset of PowerPC.
[546]744Coq and Matita essentially share the same logic.
[546]746Despite this similarity, the two formalisations do not have much in common.
[564]747First, CompCert provides a formalisation at the assembly level (no instruction decoding), and this impels them to trust an unformalised assembler and linker, whereas we provide our own. Our formalization is directly executable, while the
748one in CompCert only provides a relation that describes execution.
[546]749I/O is also not considered at all in CompCert.
750Moreover an idealized abstract and uniform memory model is assumed, while we take into account the complicated overlapping memory model of the MCS-51 architecture.
[564]751Finally, 82 instructions of the 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.
[546]752Even from a technical level the two formalisations differ: while we tried to exploit dependent types as often as possible, CompCert largely sticks to the non-dependent fragment of Coq.
[549]754In~\cite{atkey:coqjvm:2007} Atkey presents an executable specification of the Java virtual machine which uses dependent types.
[546]755As we do, dependent types are used to remove spurious partiality from the model, and to lower the need for over-specifying the behaviour of the processor in impossible cases.
756Our use of dependent types will also help to maintain invariants when we prove the correctness of the CerCo prototype compiler.
[565]758Finally, Sarkar et al~\cite{sarkar:semantics:2009} provide an executable semantics for x86-CC multiprocessor machine code.
[548]759This machine code exhibits a high degree of non-uniformity similar to the MCS-51.
[565]760However, 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.
[548]762Further, it seems that the definition of the decode function is potentially error prone.
763A small domain specific language of patterns is formalised in HOL4.
764This is similar to the specification language of the x86 instruction set found in manufacturer's data sheets.
765A decode function is implemented by copying lines from data sheets into the proof script.
[548]767We are currently considering implementing a similar domain specific language in Matita.
768However, we would prefer to certify in Matita the compiler for this language.
769Data 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.
772% SECTION                                                                      %
[565]777The CerCo project is interested in the certification of a compiler for C that induces a precise cost model on the source code.
778Our cost model assigns costs to blocks of instructions by tracing the way that blocks are compiled, and by computing exact costs on generated assembly code.
779To perform this accurately, we have provided an executable semantics for the MCS-51 family of processors, better known as 8051/8052.
780The formalisation was done twice, first in O'Caml and then in Matita, and captures the exact timings of the processor.
781Moreover, the O'Caml formalisation also considers timers and I/O.
782Adding support for I/O and timers in Matita is an 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.
[565]784The formalisation is done at machine level and not at assembly level; we also formalise fetching and decoding.
785We separately provide an assembly language, enhanched with labels and pseudo-instructions, and an assembler from this language to machine code.
786We 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.
787For the O'Caml version, we provide a parser and pretty printer from code memory to Intel HEX format.
788Hence we can perform testing on programs compiled using any free or commercial compiler.
[565]790Our main difficulty in formalising the MCS-51 was the unorthogonality of its memory model and instruction set.
791These problems are easily handled in O'Caml by using advanced language features like polymorphic variants and phantom types, simulating Generalized Abstract Data Types.
792In Matita, we use dependent types to recover the same flexibility, to reduce spurious partiality, and to grant invariants that will be useful in the formalization of the CerCo compiler.
[565]794The formalisation has been partially verified by computing execution traces on selected programs and comparing them with an existing emulator.
795All 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.
796I/O in particular has not been tested yet, and it is currently unclear how to provide exhaustive testing in the presence of I/O.
797Finally, 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.
807\section{Listing of main O'Caml functions}
810\subsubsection{From \texttt{}}
814Name & Description \\
816\texttt{assembly} & Assembles an abstract syntax tree representing an 8051 assembly program into a list of bytes, its compiled form. \\
817\texttt{initialize} & Initializes the emulator status. \\
818\texttt{load} & Loads an assembled program into the emulator's code memory. \\
819\texttt{fetch} & Fetches the next instruction, and automatically increments the program counter. \\
820\texttt{execute} & Emulates the processor.  Accepts as input a function that pretty prints the emulator status after every emulation loop. \\
[541]824\subsubsection{From \texttt{}}
828Name & Description \\
830\texttt{compute} & Computes a map associating costings to basic blocks in the program.
[540]834\subsubsection{From \texttt{}}
838Name & Description \\
840\texttt{intel\_hex\_of\_file} & Reads in a file and parses it if in Intel IHX format, otherwise raises an exception. \\
841\texttt{process\_intel\_hex} & Accepts a parsed Intel IHX file and populates a hashmap (of the same type as code memory) with the contents.
845\subsubsection{From \texttt{}}
849Name & Description \\
851\texttt{subb8\_with\_c} & Performs an eight bit subtraction on bitvectors.  The function also returns the most important PSW flags for the 8051: carry, auxiliary carry and overflow. \\
852\texttt{add8\_with\_c} & Performs an eight bit addition on bitvectors.  The function also returns the most important PSW flags for the 8051: carry, auxiliary carry and overflow. \\
853\texttt{dec} & Decrements an eight bit bitvector with underflow, if necessary. \\
854\texttt{inc} & Increments an eight bit bitvector with overflow, if necessary.
860\section{Listing of main Matita functions}
863\subsubsection{From \texttt{}}
867Title & Description \\
869\texttt{add\_n\_with\_carry} & Performs an $n$ bit addition on bitvectors.  The function also returns the most important PSW flags for the 8051: carry, auxiliary carry and overflow. \\
870\texttt{sub\_8\_with\_carry} & Performs an eight bit subtraction on bitvectors. The function also returns the most important PSW flags for the 8051: carry, auxiliary carry and overflow. \\
871\texttt{half\_add} & Performs a standard half addition on bitvectors, returning the result and carry bit. \\
872\texttt{full\_add} & Performs a standard full addition on bitvectors and a carry bit, returning the result and a carry bit.
876\subsubsection{From \texttt{}}
880Title & Description \\
882\texttt{assemble1} & Assembles a single 8051 assembly instruction into its memory representation. \\
883\texttt{assemble} & Assembles an 8051 assembly program into its memory representation.\\
884\texttt{assemble\_unlabelled\_program} &\\& Assembles a list of (unlabelled) 8051 assembly instructions into its memory representation.
888\subsubsection{From \texttt{}}
892Title & Description \\
894\texttt{lookup} & Returns the data stored at the end of a particular path (a bitvector) from the trie.  If no data exists, returns a default value. \\
895\texttt{insert} & Inserts data into a tree at the end of the path (a bitvector) indicated.  Automatically expands the tree (by filling in stubs) if necessary.
899\subsubsection{From \texttt{}}
903Title & Description \\
905\texttt{execute\_trace} & Executes an assembly program for a fixed number of steps, recording in a trace which instructions were executed.
909\subsubsection{From \texttt{}}
913Title & Description \\
915\texttt{fetch} & Decodes and returns the instruction currently pointed to by the program counter and automatically increments the program counter the required amount to point to the next instruction. \\
919\subsubsection{From \texttt{}}
923Title & Description \\
925\texttt{execute\_1} & Executes a single step of an 8051 assembly program. \\
926\texttt{execute} & Executes a fixed number of steps of an 8051 assembly program.
930\subsubsection{From \texttt{}}
934Title & Description \\
936\texttt{load} & Loads an assembled 8051 assembly program into code memory.
Note: See TracBrowser for help on using the repository browser.