source: Deliverables/D4.1/Report/report.tex @ 382

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

Changes from this morning.

File size: 20.1 KB
Line 
1\documentclass[11pt, epsf, a4wide]{article}
2
3\usepackage{../../style/cerco}
4
5\usepackage{amsfonts}
6\usepackage{amsmath}
7\usepackage{amssymb} 
8\usepackage[english]{babel}
9\usepackage{graphicx}
10\usepackage[utf8x]{inputenc}
11\usepackage{listings}
12\usepackage{stmaryrd}
13\usepackage{url}
14
15\title{
16INFORMATION AND COMMUNICATION TECHNOLOGIES\\
17(ICT)\\
18PROGRAMME\\
19\vspace*{1cm}Project FP7-ICT-2009-C-243881 \cerco{}}
20
21\lstdefinelanguage{matita}
22  {keywords={ndefinition,ncoercion,nlemma,ntheorem,nremark,ninductive,nrecord,nqed,nlet,let,in,rec,match,return,with,Type},
23   morekeywords={[2]nwhd,nnormalize,nelim,ncases,ndestruct},
24   mathescape=true,
25  }
26
27\lstset{language=matita,basicstyle=\small\tt,columns=flexible,breaklines=false,
28        keywordstyle=\color{red}\bfseries,
29        keywordstyle=[2]\color{blue},
30        commentstyle=\color{green},
31        stringstyle=\color{blue},
32        showspaces=false,showstringspaces=false}
33
34\lstset{extendedchars=false}
35\lstset{inputencoding=utf8x}
36\DeclareUnicodeCharacter{8797}{:=}
37\DeclareUnicodeCharacter{10746}{++}
38\DeclareUnicodeCharacter{9001}{\ensuremath{\langle}}
39\DeclareUnicodeCharacter{9002}{\ensuremath{\rangle}}
40
41\date{}
42\author{}
43
44\begin{document}
45
46\thispagestyle{empty}
47
48\vspace*{-1cm}
49\begin{center}
50\includegraphics[width=0.6\textwidth]{../../style/cerco_logo.png}
51\end{center}
52
53\begin{minipage}{\textwidth}
54\maketitle
55\end{minipage}
56
57\vspace*{0.5cm}
58\begin{center}
59\begin{LARGE}
60\textbf{
61Report n. D4.1\\
62Intel 8051/8052 emulator prototype, and formalisation in Matita}
63\end{LARGE} 
64\end{center}
65
66\vspace*{2cm}
67\begin{center}
68\begin{large}
69Version 1.0
70\end{large}
71\end{center}
72
73\vspace*{0.5cm}
74\begin{center}
75\begin{large}
76Main Authors:\\
77Claudio Sacerdoti Coen and Dominic P. Mulligan
78\end{large}
79\end{center}
80
81\vspace*{\fill}
82
83\noindent
84Project Acronym: \cerco{}\\
85Project full title: Certified Complexity\\
86Proposal/Contract no.: FP7-ICT-2009-C-243881 \cerco{}\\
87
88\clearpage
89\pagestyle{myheadings}
90\markright{\cerco{}, FP7-ICT-2009-C-243881}
91
92\newpage
93
94\vspace*{7cm}
95\paragraph{Abstract}
96We discuss the design and implementation of an O'Caml emulator for the Intel 8051/8052 eight bit processor, and its subsequent formalisation in the dependently typed proof assistant Matita.
97
98\newpage
99
100\tableofcontents
101
102\newpage
103
104\section{Introduction}
105\label{sect.introduction}
106
107\subsection{Task}
108\label{subsect.task}
109
110The Grant Agreement states the D4.1/D4.2 deliverables consist of the following tasks:
111
112\begin{quotation}
113\textbf{Executable Formal Semantics of Machine Code}: Formal definition of the semantics of the target language.
114The semantics will be given in a functional (and hence executable) form, useful for testing, validation and project assessment.
115\end{quotation}
116
117\begin{quotation}
118\textbf{CIC encoding: Back-end}: Functional Specification in the internal language of the Proof Assistant (the Calculus of Inductive Construction) of the back end of the compiler.
119This unit is meant to be composable with the front-end of deliverable D3.2, to obtain a full working compiler for Milestone M2.
120A first validation of the design principles and implementation choices for the Untrusted Cost-annotating OCaml Compiler D2.2 is achieved and reported in the deliverable, possibly triggering updates of the Untrusted Cost-annotating OCaml Compiler sources.
121\end{quotation}
122We now report on our implementation of these deliverables.
123
124\subsection{A brief overview of the target processor}
125\label{subsect.brief.overview.target.processor}
126
127The MCS-51 is an eight bit microprocessor introduced by Intel in the late 1970s.
128Commonly called the 8051, in the three decades since its introduction the processor has become a highly popular target for embedded systems engineers.
129Further, the processor and its immediate successor, the 8052, is still manufactured by a host of semiconductor suppliers---many of them European---including Atmel, Siemens Semiconductor, NXP (formerly Phillips Semiconductor), Texas Instruments, and Maxim (formerly Dallas Semiconductor).
130
131The 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.
132For instance, the open source Small Device C Compiler (SDCC) recognises a dialect of C, and other compilers targeting the 8051 for BASIC, Forth and Modula-2 are also extant.
133An open source emulator for the processor, MCU8051 IDE, is also available.
134
135The 8051 has a relatively straightforward architecture, unencumbered by advanced features of modern processors, making it an ideal target for formalisation.
136A high-level overview of the processor's memory layout is provided in Figure~\ref{fig.memory.layout}.
137
138Processor RAM is divided into numerous segments, with the most prominent division being between internal and (optional) external memory.
139Internal memory, commonly provided on the die itself with fast access, is further divided into 128 bytes of internal RAM and numerous Special Function Registers (SFRs) which control the operation of the processor.
140Internal RAM (IRAM) is further divided into a eight general purpose bit-addressable registers (R0--R7).
141These sit in the first eight bytes of IRAM, though can be programmatically `shifted up' as needed.
142Bit memory, followed by a small amount of stack space resides in the memory space immediately after the register banks.
143What remains of the IRAM may be treated as general purpose memory.
144A schematic view of IRAM layout is provided in Figure~\ref{fig.iram.layout}.
145
146External RAM (XRAM), limited to 64 kilobytes, is optional, and may be provided on or off chip, depending on the manufacturer.
147XRAM is accessed using a dedicated instruction.
148External code memory (XCODE) is often stored in the form of an EPROM, and limited to 64 kilobytes in size.
149However, depending on the particular manufacturer and processor model, a dedicated on-die read-only memory area for program code (ICODE) may also be supplied.
150
151Memory may be addressed in numerous ways: immediate, direct, indirect, external direct and code indirect.
152As 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.
153For 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.
154
155The 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.
156Further, the processor possesses two eight bit general purpose accumulators, A and B.
157
158Communication with the device is facilitated by an onboard UART serial port, and associated serial controller, which can operate in numerous modes.
159Serial baud rate is determined by one of two sixteen bit timers included with the 8051, which can be set to multiple modes of operation.
160(The 8052 provides an additional sixteen bit timer.)
161As an additional method of communication, the 8051 also provides a four byte bit-addressable input-output port.
162
163The programmer may take advantage of the interrupt mechanism that the processor provides.
164This 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.
165
166Interrupts 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.
167However, interrupts may be set to one of two priorities: low and high.
168The 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.
169
170The 8051 has interrupts disabled by default.
171The programmer is free to handle serial input and output manually, by poking serial flags in the SFRs.
172Similarly, `exceptional circumstances' that would otherwise trigger an interrupt on more modern processors, for example, division by zero, are also signalled by setting flags.
173
174\begin{figure}[t]
175\begin{center}
176\includegraphics[scale=0.5]{memorylayout.png}
177\end{center}
178\caption{High level overview of the 8051 memory layout}
179\label{fig.memory.layout}
180\end{figure}
181
182\begin{figure}[t]
183\begin{center}
184\includegraphics[scale=0.5]{iramlayout.png}
185\end{center}
186\caption{Schematic view of 8051 IRAM layout}
187\label{fig.iram.layout}
188\end{figure}
189
190\section{The emulator in O'Caml}
191\label{sect.emulator.in.ocaml}
192
193\subsection{Anatomy of the emulator}
194\label{subsect.anatomy.emulator}
195
196\subsection{Lack of orthogonality in instruction set}
197\label{subsect.lack.orthogonality.instruction.set}
198
199The instruction set of 8051 assembly is highly irregular.
200For instance, consider the MOV instruction, which implements a data transfer between two memory locations, which takes eighteen possible combinations of addressing modes.
201
202\subsection{Pseudo-instructions}
203\label{subsect.pseudo-instructions}
204
205In validating the design and implementation of the O'Caml emulator we used two tactics:
206\begin{enumerate}
207\item
208Use of multiple manufacturer's data sheets (both the Siemens Semiconductor and Phillips Semiconductor specifications for the 8051, as well as online sources such as the Keil website).
209We found typographic errors in manufacturer's data sheets which were resolved by consulting an alternative sheet.
210\item
211Use of reference compilers and emulators.
212The operation of the emulator was manually tested by reference to \textsc{mcu 8051 ide}, an emulator for the 8051 series processor.
213A number of small C programs were compiled in SDCC\footnote{See the \texttt{GCC} directory for a selection of them.}, and the resulting IHX files were disassembled by \textsc{mcu 8051 ide}.
214The status changes in both emulators were then compared.
215
216For further validation, the output of the compiled C programs from SDCC was compared with the output of the same programs in GCC, in order to pre-empt the introduction of bugs in the emulator inherited from a faulty C compiler.
217\end{enumerate}
218
219As a further check, the design and operation of the emulator was compared with the textual description of online tutorials on 8051 programming, such as those found at \url{http://www.8052.com}.
220
221\subsection{Validation}
222\label{subsect.validation}
223
224\section{The emulator in Matita}
225\label{sect.emulator.in.matita}
226
227\subsection{What we do not implement}
228\label{subsect.what.we.do.not.implement}
229
230Our O'Caml 8051 emulator provides functions for reading and parsing Intel IHX format files.
231We do not implement these functions in the Matita emulator, as Matita provides no means of input or output.
232
233\subsection{Auxilliary data structures and libraries}
234\label{subsect.auxilliary.data.structures.and.libraries}
235
236A small library of data structures was written, along with basic functions operating over them.
237Implemented data structures include: Booleans, option types, lists, Cartesian products, Natural numbers, fixed-length vectors, and sparse tries.
238
239Our type of vectors, in particular, makes heavy use of dependent types.
240Probing vectors is `type safe' for instance: we cannot index into a vector beyond the vector's length.
241
242We represent bits as Boolean values.
243Nibbles, bytes, words, and so on, are represented as fixed length (bit)vectors of the requisite length.
244
245\subsection{The emulator state}
246\label{subsect.emulator.state}
247
248We represent all processor memory in the Matita emulator as a sparse (bitvector)trie:
249
250\begin{quote}
251\begin{lstlisting}
252ninductive BitVectorTrie (A: Type[0]): Nat $\rightarrow$ Type[0] ≝
253  Leaf: A $\rightarrow$ BitVectorTrie A Z
254| Node: ∀n: Nat. BitVectorTrie A n $\rightarrow$ BitVectorTrie A n $\rightarrow$ BitVectorTrie A (S n)
255| Stub: ∀n: Nat. BitVectorTrie A n.
256\end{lstlisting}
257\end{quote}
258
259Nodes are addressed by a bitvector index, representing a path through the tree.
260At any point in the tree, a \texttt{Stub} may be inserted, representing a `hole' in the tree.
261All functions operating on tries use dependent types to enforce the invariant that the height of the tree and the length of the bitvector representing a path through the tree are the same.
262
263We probe a trie with the \texttt{lookup} function.
264This takes an additional argument representing the value to be returned should a stub, representing uninitialised data, be encountered during traversal.
265
266Like the O'Caml emulator, we use a record to represent processor state:
267
268\begin{quote}
269\begin{lstlisting}
270nrecord Status: Type[0] ≝
271{
272  code_memory: BitVectorTrie Byte sixteen;
273  low_internal_ram: BitVectorTrie Byte seven;
274  high_internal_ram: BitVectorTrie Byte seven;
275  external_ram: BitVectorTrie Byte sixteen;
276 
277  program_counter: Word;
278 
279  special_function_registers_8051: Vector Byte nineteen;
280  special_function_registers_8052: Vector Byte five;
281 
282  ...
283}.
284\end{lstlisting}
285\end{quote}
286
287However, we `squash' the \texttt{Status} record in the Matita emulator by grouping all 8051 SFRs (respectively, 8052 SFRs) into a single vector of bytes, as opposed to representing them as explicit fields in the record itself.
288We then provide functions that index into the respective vector to `get' and `set' the respective SFRs.
289This is due to record typechecking in Matita being slow for large records.
290
291\subsection{Dealing with partiality}
292\label{subsect.dealing.with.partiality}
293
294The O'Caml 8051 emulator makes use of a number of partial functions.
295These functions either \texttt{assert false}\footnote{O'Caml idiom: immediately halts execution of the running program.} or do not perform a comprehensive pattern analysis over their inputs.
296There are a number of possible reasons for this:
297\begin{enumerate}
298\item
299\textbf{Incomplete pattern analyses} are used where we are confident that the particular pattern match in question should never occur, for instance if the calling function performs a test beforehand, or where the emulator should fail anyway if a particular unchecked pattern is used as input.
300An example of a function which exhibits the latter behaviour is \texttt{set\_arg\_16} from \texttt{ASMInterpret.ml}, which fails with a pattern match exception if called on an input representing an eight bit argument.
301\item
302\textbf{Assert false} may be called if the emulator finds itself in an `impossible situation', such as encountering an empty list where a list containing one element is expected.
303In this respect, we used \texttt{assert false} in a similar way to the previously described use of incomplete pattern analysis.
304\item
305\textbf{Assert false} may be called is some feature of the physical 8051 processor is not implemented in the O'Caml emulator and an executing program is attempting to use it.
306\end{enumerate}
307
308The three manifestations of partiality above can be split into two types: partiality that manifests itself due to O'Caml's type system not being strong enough to rule the cause out, and partiality that signals a `real' crash in the processor due to the user attempting to use an unimplemented feature.
309Items 1 and 2 belong to the former class, Item 3 to the latter.
310
311Clearly Items 1 and 2 above must be addressed in the Matita formalisation.
312Item 2 is solved through extensive use of dependent types.
313Indexing into lists and vectors, for instance, is always `type safe', as we provide probing functions with strong dependent types.
314
315Item 1 is perhaps the most problematic of the three problems, as we either have to provide an exhaustive case analysis, use pattern wildcards, or find a clever way of encoding the possible patterns that are expected as input in the type of a function.
316We employ a technique that implements the latter idea.
317This is discussed in Subsection~\ref{subsect.addressing.modes.use.of.dependent.types}.
318
319To solve Item 3 above in the Matita formalisation of the emulator, we introduce an axiom \texttt{not\_implemented} of type \texttt{False}.
320When the emulator attempts to use an unimplemented feature, we introduce a metavariable, corresponding to an open proof obligation.
321These obligations are closed by performing a case analysis over \texttt{not\_implemented}.
322
323\subsection{Addressing modes: use of dependent types}
324\label{subsect.addressing.modes.use.of.dependent.types}
325
326We provide an inductive data type representing all possible addressing modes of 8051 assembly.
327This is the type that functions will pattern match against.
328
329\begin{quote}
330\begin{lstlisting}
331ninductive addressing_mode: Type[0] ≝
332  DIRECT: Byte $\rightarrow$ addressing_mode
333| INDIRECT: Bit $\rightarrow$ addressing_mode
334...
335\end{lstlisting}
336\end{quote}
337However, we also wish to express in the type of our functions the \emph{impossibility} of pattern matching against certain constructors.
338In order to do this, we introduce an inductive type of addressing mode `tags'.
339The constructors of \texttt{addressing\_mode\_tag} are in one-one correspondence with the constructors of \texttt{addressing\_mode}:
340\begin{quote}
341\begin{lstlisting}
342ninductive addressing_mode_tag : Type[0] ≝
343  direct: addressing_mode_tag
344| indirect: addressing_mode_tag
345...
346\end{lstlisting}
347\end{quote}
348We then provide a function that checks whether an \texttt{addressing\_mode} is `morally' an \texttt{addressing\_mode\_tag}, as follows:
349\begin{quote}
350\begin{lstlisting}
351nlet rec is_a (d:addressing_mode_tag) (A:addressing_mode) on d ≝
352  match d with
353   [ direct $\Rightarrow$ match A with [ DIRECT _ $\Rightarrow$ true | _ $\Rightarrow$ false ]
354   | indirect $\Rightarrow$ match A with [ INDIRECT _ $\Rightarrow$ true | _ $\Rightarrow$ false ]
355...
356\end{lstlisting}
357\end{quote}
358We also extend this check to vectors of \texttt{addressing\_mode\_tag}'s in the obvious manner:
359\begin{quote}
360\begin{lstlisting}
361nlet rec is_in (n: Nat) (l: Vector addressing_mode_tag n) (A:addressing_mode) on l ≝
362 match l return $\lambda$m.$\lambda$_ :Vector addressing_mode_tag m.Bool with
363  [ VEmpty $\Rightarrow$ false
364  | VCons m he (tl: Vector addressing_mode_tag m) $\Rightarrow$
365     is_a he A $\vee$ is_in ? tl A ].
366\end{lstlisting}
367\end{quote}
368Here \texttt{VEmpty} and \texttt{VCons} are the two constructors of the \texttt{Vector} data type, and $\mathtt{\vee}$ is inclusive disjunction on Booleans.
369\begin{quote}
370\begin{lstlisting}
371nrecord subaddressing_mode (n: Nat) (l: Vector addressing_mode_tag (S n)) : Type[0] ≝
372{
373  subaddressing_modeel :> addressing_mode;
374  subaddressing_modein: bool_to_Prop (is_in ? l subaddressing_modeel)
375}.
376\end{lstlisting}
377\end{quote}
378We can now provide an inductive type of preinstructions with precise typings:
379\begin{quote}
380\begin{lstlisting}
381ninductive preinstruction (A: Type[0]): Type[0] ≝
382   ADD: $\llbracket$ acc_a $\rrbracket$ $\rightarrow$ $\llbracket$ register; direct; indirect; data $\rrbracket$ $\rightarrow$ preinstruction A
383 | ADDC: $\llbracket$ acc_a $\rrbracket$ $\rightarrow$ $\llbracket$ register; direct; indirect; data $\rrbracket$ $\rightarrow$ preinstruction A
384...
385\end{lstlisting}
386\end{quote}
387Here $\llbracket - \rrbracket$ is syntax denoting a vector.
388We 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.
389
390The 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.
391The previous machinery allows us to state in the type of a function what addressing modes that function expects.
392For instance, consider \texttt{set\_arg\_16}, which expects only a \texttt{DPTR}:
393\begin{quote}
394\begin{lstlisting}
395ndefinition set_arg_16: Status $\rightarrow$ Word $\rightarrow$ $\llbracket$ dptr $\rrbracket$ $\rightarrow$ Status ≝
396  $\lambda$s, v, a.
397   match a return $\lambda$x. bool_to_Prop (is_in ? $\llbracket$ dptr $\rrbracket$ x) $\rightarrow$ ? with
398     [ DPTR $\Rightarrow$ $\lambda$_: True.
399       let 〈 bu, bl 〉 := split $\ldots$ eight eight v in
400       let status := set_8051_sfr s SFR_DPH bu in
401       let status := set_8051_sfr status SFR_DPL bl in
402         status
403     | _ $\Rightarrow$ $\lambda$_: False.
404       match K in False with
405       [
406       ]
407     ] (subaddressing_modein $\ldots$ a).
408\end{lstlisting}
409\end{quote}
410All other cases are discharged by the catch-all at the bottom of the match expression.
411Attempting to match against another addressing mode not indicated in the type (for example, \texttt{REGISTER}) will produce a type-error.
412
413\end{document}
Note: See TracBrowser for help on using the repository browser.