source: src/ASM/CPP2012-asm/cpp-2012-asm.tex @ 2053

Last change on this file since 2053 was 2053, checked in by mulligan, 8 years ago

Introduction changed, with many paragraphs deleted.

File size: 49.3 KB
Line 
1\documentclass{llncs}
2
3\usepackage{amsfonts}
4\usepackage{amsmath}
5\usepackage{amssymb} 
6\usepackage[english]{babel}
7\usepackage{color}
8\usepackage{fancybox}
9\usepackage{graphicx}
10\usepackage[colorlinks]{hyperref}
11\usepackage{hyphenat}
12\usepackage[utf8x]{inputenc}
13\usepackage{listings}
14\usepackage{mdwlist}
15\usepackage{microtype}
16\usepackage{stmaryrd}
17\usepackage{url}
18
19\renewcommand{\verb}{\lstinline}
20\def\lstlanguagefiles{lst-grafite.tex}
21\lstset{language=Grafite}
22
23\newlength{\mylength}
24\newenvironment{frametxt}%
25        {\setlength{\fboxsep}{5pt}
26                \setlength{\mylength}{\linewidth}%
27                \addtolength{\mylength}{-2\fboxsep}%
28                \addtolength{\mylength}{-2\fboxrule}%
29                \Sbox
30                \minipage{\mylength}%
31                        \setlength{\abovedisplayskip}{0pt}%
32                        \setlength{\belowdisplayskip}{0pt}%
33                }%
34                {\endminipage\endSbox
35                        \[\fbox{\TheSbox}\]}
36
37\title{On the correctness of an assembler for the Intel MCS-51 microprocessor\thanks{The project CerCo acknowledges the financial support of the Future and Emerging Technologies (FET) programme within the Seventh Framework Programme for Research of the European Commission, under FET-Open grant number: 243881}}
38\author{Dominic P. Mulligan \and Claudio Sacerdoti Coen}
39\institute{Dipartimento di Scienze dell'Informazione, Universit\'a di Bologna}
40
41\bibliographystyle{splncs03}
42
43\begin{document}
44
45\maketitle
46
47\begin{abstract}
48We present a proof of correctness, in the Matita proof assistant, for an optimising assembler for the MCS-51 8-bit microcontroller.
49This assembler constitutes a major component of the EU's CerCo (`Certified Complexity') project.
50
51The efficient expansion of pseudoinstructions---particularly jumps---into MCS-51 machine instructions is complex.
52We isolate the decision making over how jumps should be expanded from the expansion process itself as much as possible using `policies'.
53This makes the proof of correctness for the assembler significantly more straightforward.
54
55We observe that it is impossible for an optimising assembler to preserve the semantics of every assembly program.
56Assembly language programs can manipulate concrete addresses in arbitrary ways.
57Our proof strategy contains a notion of `good addresses' and only assembly programs that use good addresses have their semantics preserved under assembly.
58Our strategy offers increased flexibility over the traditional approach of keeping addresses in assembly opaque.
59In particular, we may experiment with allowing the benign manipulation of addresses.
60\end{abstract}
61
62% ---------------------------------------------------------------------------- %
63% SECTION                                                                      %
64% ---------------------------------------------------------------------------- %
65\section{Introduction}
66\label{sect.introduction}
67
68We consider the formalisation of an assembler for the Intel MCS-51 8-bit microprocessor in the Matita proof assistant~\cite{asperti:user:2007}.
69This formalisation forms a major component of the EU-funded CerCo (`Certified Complexity') project~\cite{cerco:2011}, concerning the construction and formalisation of a concrete complexity preserving compiler for a large subset of the C programming language.
70
71The MCS-51 dates from the early 1980s and is commonly called the 8051/8052.
72Despite the microprocessor's age, derivatives are still widely manufactured by a number of semiconductor foundries.
73As a result the processor is widely used, especially in embedded systems development, where well-tested, cheap, predictable microprocessors find their niche.
74
75The MCS-51 has a relative paucity of features compared to its more modern brethren, with the lack of any caching or pipelining features means that timing of execution is predictable, making the MCS-51 very attractive for CerCo's ends.
76Yet, as in most things, what one hand giveth the other taketh away, and the MCS-51's paucity of features---though an advantage in many respects---also quickly become a hindrance.
77In particular, the MCS-51 features a relatively minuscule series of memory spaces by modern standards.
78As a result our C compiler, to have any sort of hope of successfully compiling realistic programs for embedded devices, ought to produce `tight' machine code.
79
80For example, the MCS-51 features three unconditional jump instructions: \texttt{LJMP} and \texttt{SJMP}---`long jump' and `short jump' respectively---and an 11-bit oddity of the MCS-51, \texttt{AJMP}.
81Each of these three instructions expects arguments in different sizes and behaves in markedly different ways: \texttt{SJMP} may only perform a `local jump'; \texttt{LJMP} may jump to any address in the MCS-51's memory space and \texttt{AJMP} may jump to any address in the current memory page.
82Consequently, the size of each opcode is different, and to squeeze as much code as possible into the MCS-51's limited code memory, the smallest possible opcode that will suffice should be selected.
83This is a well known problem to assembler writers, often referred to as `branch displacement'.
84
85Branch displacement is not a simple problem to solve and requires the implementation of an optimising assembler.
86Labels, conditional jumps to labels, a program preamble containing global data and a \texttt{MOV} instruction for moving this global data into the MCS-51's one 16-bit register all feature in our assembly language.
87We simplify the process by assuming that all assembly programs are pre-linked (i.e. we do not formalise a linker).
88The assembler expands pseudoinstructions into MCS-51 machine code, but this assembly process is not trivial, for numerous reasons.
89For example, our conditional jumps to labels behave differently from their machine code counterparts.
90At the machine code level, all conditional jumps are `short', limiting their range.
91However, at the assembly level, conditional jumps may jump to a label that appears anywhere in the program, significantly liberalising the use of conditional jumps.
92
93Yet, the situation is even more complex than having to expand pseudoinstructions correctly.
94In particular, when formalising the assembler, we must make sure that the assembly process does not change the timing characteristics of an assembly program for two reasons.
95
96First, the semantics of some functions of the MCS-51, notably I/O, depend on the microprocessor's clock.
97Changing how long a particular program takes to execute can affect the semantics of a program.
98This is undesirable.
99
100Second, CerCo imposes a cost model on C programs or, more specifically, on simple blocks of instructions.
101This cost model is induced by the compilation process itself, and its non-compositional nature allows us to assign different costs to identical blocks of instructions depending on how they are compiled.
102In short, we aim to obtain a very precise costing for a program by embracing the compilation process, not ignoring it.
103This, however, complicates the proof of correctness for the compiler proper.
104In each translation pass from intermediate language to intermediate language, we must prove that both the meaning and concrete complexity characteristics of the program are preserved.
105This also applies for the translation from assembly language to machine code.
106
107Naturally, this raises a question: how do we assign an \emph{accurate} cost to a pseudoinstruction?
108As mentioned, conditional jumps at the assembly level can jump to a label appearing anywhere in the program.
109However, at the machine code level, conditional jumps are limited to jumping `locally', using a measly byte offset.
110To translate a jump to a label, a single conditional jump pseudoinstruction may be translated into a block of three real instructions as follows (here, \texttt{JZ} is `jump if accumulator is zero'):
111{\small{
112\begin{displaymath}
113\begin{array}{r@{\quad}l@{\;\;}l@{\qquad}c@{\qquad}l@{\;\;}l}
114       & \mathtt{JZ}  & \mathtt{label}                      &                 & \mathtt{JZ}   & \text{size of \texttt{SJMP} instruction} \\
115       & \ldots       &                            & \text{translates to}   & \mathtt{SJMP} & \text{size of \texttt{LJMP} instruction} \\
116\mathtt{label:} & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B}   & \Longrightarrow & \mathtt{LJMP} & \text{address of \textit{label}} \\
117       &              &                            &                 & \ldots        & \\
118       &              &                            &                 & \mathtt{MOV}  & \mathtt{A}\;\;\mathtt{B}
119\end{array}
120\end{displaymath}}}
121Here, if \texttt{JZ} fails, we fall through to the \texttt{SJMP} which jumps over the \texttt{LJMP}.
122Naturally, if \texttt{label} is close enough, a conditional jump pseudoinstruction is mapped directly to a conditional jump machine instruction; the above translation only applies if \texttt{label} is not sufficiently local.
123We address the calculation of whether a label is indeed `close enough' for the simpler translation to be used below.
124
125Crucially, the above translation demonstrates the difficulty in predicting how many clock cycles a pseudoinstruction will take to execute.
126A conditional jump may be mapped to a single machine instruction or a block of three.
127Perhaps more insidious is the realisation that the number of cycles needed to execute the instructions in the two branches of a translated conditional jump may be different.
128Depending on the particular MCS-51 derivative at hand, an \texttt{SJMP} could in theory take a different number of clock cycles to execute than an \texttt{LJMP}.
129These issues must also be dealt with in order to prove that the translation pass preserves the concrete complexity of assembly code, and that the semantics of a program using the MCS-51's I/O facilities does not change.
130We address this problem by parameterising the semantics over a cost model.
131We prove the preservation of concrete complexity only for the program-dependent cost model induced by the optimisation.
132
133Yet one more question remains: how do we decide whether to expand a jump into an \texttt{SJMP} or an \texttt{LJMP}?
134To understand, again, why this problem is not trivial, consider the following snippet of assembly code:
135{\small{
136\begin{displaymath}
137\begin{array}{r@{\qquad}r@{\quad}l@{\;\;}l@{\qquad}l}
138\text{1:} & \mathtt{(0x000)}  & \texttt{LJMP} & \texttt{0x100}  & \text{\texttt{;; Jump forward 256.}} \\
139\text{2:} & \mathtt{...}    & \mathtt{...}  &                 &                                               \\
140\text{3:} & \mathtt{(0x0FA)}  & \texttt{LJMP} & \texttt{0x100}  & \text{\texttt{;; Jump forward 256.}} \\
141\text{4:} & \mathtt{...}    & \mathtt{...}  &                 &                                               \\
142\text{5:} & \mathtt{(0x100)}  & \texttt{LJMP} & \texttt{-0x100}  & \text{\texttt{;; Jump backward 256.}} \\
143\end{array}
144\end{displaymath}}}
145We observe that $100_{16} = 256_{10}$, and lies \emph{just} outside the range expressible in an 8-bit byte (0--255).
146
147As our example shows, given an occurrence $l$ of an \texttt{LJMP} instruction, it may be possible to shrink $l$ to an occurrence of an \texttt{SJMP}---consuming fewer bytes of code memory---provided we can shrink any \texttt{LJMP}s that exist between $l$ and its target location.
148In particular, if we wish to shrink the \texttt{LJMP} occurring at line 1, then we must shrink the \texttt{LJMP} occurring at line 3.
149However, to shrink the \texttt{LJMP} occurring at line 3 we must also shrink the \texttt{LJMP} occurring at line 5, and \emph{vice versa}.
150
151Further, consider what happens if, instead of appearing at memory address \texttt{0x100}, the instruction at line 5 instead appeared \emph{just} beyond the size of code memory, and all other memory addresses were shifted accordingly.
152Now, in order to be able to successfully fit our program into the MCS-51's limited code memory, we are \emph{obliged} to shrink the \texttt{LJMP} occurring at line 5.
153That is, the shrinking process is not just related to the optimisation of generated machine code but also the completeness of the assembler itself.
154
155How we went about resolving this problem affected the shape of our proof of correctness for the whole assembler in a rather profound way.
156We first attempted to synthesise a solution bottom up: starting with no solution, we gradually refine a solution using the same functions that implement the jump expansion process.
157Using this technique, solutions can fail to exist, and the proof of correctness for the assembler quickly descends into a diabolical quagmire.
158
159Abandoning this attempt, we instead split the `policy'---the decision over how any particular jump should be expanded---from the implementation that actually expands assembly programs into machine code.
160Assuming the existence of a correct policy, we proved the implementation of the assembler correct.
161Further, we proved that the assembler fails to assemble an assembly program if and only if a correct policy does not exist.
162This is achieved by means of dependent types: the assembly function is total over a program, a policy and the proof that the policy is correct for that program.
163
164Policies do not exist in only a limited number of circumstances: namely, if a pseudoinstruction attempts to jump to a label that does not exist, or the program is too large to fit in code memory, even after shrinking jumps according to the best policy.
165The first circumstance is an example of a serious compiler error, as an ill-formed assembly program was generated, and does not (and should not) count as a mark against the completeness of the assembler.
166
167The rest of this paper is a detailed description of our proof that is, in part, still a work in progress.
168
169% ---------------------------------------------------------------------------- %
170% SECTION                                                                      %
171% ---------------------------------------------------------------------------- %
172\subsection{Overview of the paper}
173\label{subsect.overview.of.the.paper}
174In Section~\ref{sect.matita} we provide a brief overview of the Matita proof assistant for the unfamiliar reader.
175In Section~\ref{sect.the.proof} we discuss the design and implementation of the proof proper.
176In Section~\ref{sect.conclusions} we conclude.
177
178% ---------------------------------------------------------------------------- %
179% SECTION                                                                      %
180% ---------------------------------------------------------------------------- %
181\section{Matita}
182\label{sect.matita}
183
184Matita is a proof assistant based on a variant of the Calculus of (Co)inductive Constructions~\cite{asperti:user:2007}.
185In particular, it features dependent types that we heavily exploit in the formalisation.
186The syntax of the statements and definitions in the paper should be self-explanatory, at least to those exposed to dependent type theory.
187We only remark the use of of `$\mathtt{?}$' or `$\mathtt{\ldots}$' for omitting single terms or sequences of terms to be inferred automatically by the system, respectively.
188Those that are not inferred are left to the user as proof obligations.
189Pairs are denoted with angular brackets, $\langle-, -\rangle$.
190
191Matita features a liberal system of coercions.
192It is possible to define a uniform coercion $\lambda x.\langle x,?\rangle$ from every type $T$ to the dependent product $\Sigma x:T.P~x$.
193The coercion opens a proof obligation that asks the user to prove that $P$ holds for $x$.
194When a coercion must be applied to a complex term (a $\lambda$-abstraction, a local definition, or a case analysis), the system automatically propagates the coercion to the sub-terms
195 For instance, to apply a coercion to force $\lambda x.M : A \to B$ to have type $\forall x:A.\Sigma y:B.P~x~y$, the system looks for a coercion from $M: B$ to $\Sigma y:B.P~x~y$ in a context augmented with $x:A$.
196This is significant when the coercion opens a proof obligation, as the user will be presented with multiple, but simpler proof obligations in the correct context.
197In this way, Matita supports the ``Russell'' proof methodology developed by Sozeau in~\cite{sozeau:subset:2006}, with an implementation that is lighter and more tightly integrated with the system than that of Coq.
198
199% ---------------------------------------------------------------------------- %
200% SECTION                                                                      %
201% ---------------------------------------------------------------------------- %
202\section{The proof}
203\label{sect.the.proof}
204
205\subsection{The assembler and semantics of machine code}
206\label{subsect.the.assembler.and.semantics.of.machine.code}
207
208The formalisation in Matita of the semantics of MCS-51 machine code is described in~\cite{mulligan:executable:2011}.
209We merely describe enough here to understand the rest of the proof.
210
211The emulator centres around a \texttt{Status} record, describing the microprocessor's state.
212This record contains fields corresponding to the microprocessor's program counter, registers, and so on.
213At the machine code level, code memory is implemented as a compact trie of bytes, addressed by the program counter.
214Machine code programs are loaded into \texttt{Status} using the \texttt{load\_code\_memory} function.
215
216We may execute a single step of a machine code program using the \texttt{execute\_1} function, which returns an updated \texttt{Status}:
217\begin{lstlisting}
218definition execute_1: Status $\rightarrow$ Status := $\ldots$
219\end{lstlisting}
220The function \texttt{execute} allows one to execute an arbitrary, but fixed (due to Matita's normalisation requirement) number of steps of a program.
221
222Naturally, assembly programs have analogues.
223The counterpart of the \texttt{Status} record is \texttt{PseudoStatus}.
224Instead of code memory being implemented as tries of bytes, code memory is here implemented as lists of pseudoinstructions, and program counters are merely indices into this list.
225Both \texttt{Status} and \texttt{PseudoStatus} are specialisations of the same \texttt{PreStatus} record, parametric in the representation of code memory.
226This allows us to share some code that is common to both records (for instance, `setter' and `getter' functions).
227
228Our analogue of \texttt{execute\_1} is \texttt{execute\_1\_pseudo\_instruction}:
229\begin{lstlisting}
230definition execute_1_pseudo_instruction: (Word $\rightarrow$ nat $\times$ nat) $\rightarrow$
231                                         PseudoStatus $\rightarrow$ PseudoStatus := $\ldots$
232\end{lstlisting}
233Notice, here, that the emulation function for assembly programs takes an additional argument.
234This is a function that maps program counters (at the assembly level) to pairs of natural numbers representing the number of clock ticks that the pseudoinstruction needs to execute, post expansion.
235We call this function a \emph{costing}, and note that the costing is induced by the particular strategy we use to expand pseudoinstructions.
236If we change how we expand conditional jumps to labels, for instance, then the costing needs to change, hence \texttt{execute\_1\_pseudo\_instruction}'s parametricity in the costing.
237
238The costing returns \emph{pairs} of natural numbers because, in the case of expanding conditional jumps to labels, the expansion of the `true branch' and `false branch' may differ in execution time.
239This timing information is used inside \texttt{execute\_1\_pseudo\_instruction} to update the clock of the \texttt{PseudoStatus}.
240During the proof of correctness of the assembler we relate the clocks of \texttt{Status}es and \texttt{PseudoStatus}es for the policy induced by the cost model and optimisations.
241
242The assembler, mapping programs consisting of lists of pseudoinstructions to lists of bytes, operates in a mostly straightforward manner.
243To a degree of approximation, the assembler on an assembly program, consisting of $n$ pseudoinstructions $\mathtt{P_i}$ for $1 \leq i \leq n$, works as in the following diagram (we use $-^{*}$ to denote a combined map and flatten operation):
244\begin{displaymath}
245[\mathtt{P_1}, \ldots \mathtt{P_n}] \xrightarrow{\left(\mathtt{P_i} \xrightarrow{\mbox{\fontsize{7}{9}\selectfont$\mathtt{expand\_pseudo\_instruction}$}} \mathtt{[I^1_i, \ldots I^q_i]} \xrightarrow{\mbox{\fontsize{7}{9}\selectfont$\mathtt{~~~~~~~~assembly1^{*}~~~~~~~~}$}} \mathtt{[0110]}\right)^{*}} \mathtt{[010101]}
246\end{displaymath}
247Here $\mathtt{I^j_i}$ for $1 \leq j \leq q$ are the $q$ machine code instructions obtained by expanding, with \texttt{expand\_pseudo\_instruction}, a single pseudoinstruction $P_i$.
248Each machine code instruction $\mathtt{I^i_j}$ is then assembled, using the \texttt{assembly1} function, into a list of bytes.
249This process is iterated for each pseudoinstruction, before the lists are flattened into a single bit list representation of the original assembly program.
250
251% ---------------------------------------------------------------------------- %
252% SECTION                                                                      %
253% ---------------------------------------------------------------------------- %
254\subsection{Policies}
255\label{subsect.policies}
256
257Policies exist to dictate how conditional and unconditional jumps at the assembly level should be expanded into machine code instructions.
258Using policies, we are able to completely decouple the decision over how jumps are expanded with the act of expansion, simplifying our proofs.
259As mentioned, the MCS-51 instruction set includes three different jump instructions: \texttt{SJMP}, \texttt{AJMP} and \texttt{LJMP}; call these `short', `medium' and `long' jumps, respectively:
260\begin{lstlisting}
261inductive jump_length: Type[0] :=
262  |short_jump:jump_length |medium_jump:jump_length |long_jump:jump_length.
263\end{lstlisting}
264
265A \texttt{jump\_expansion\_policy} is a map from pseudo program counters (implemented as \texttt{Word}s) to \texttt{jump\_length}s.
266Efficient implementations of policies are based on tries.
267Intuitively, a policy maps positions in a program (indexed using program counters implemented as \texttt{Word}s) to a particular variety of jump:
268\begin{lstlisting}
269definition policy_type := Word $\rightarrow$ jump_length.
270\end{lstlisting}
271
272Next, we require a series of `sigma' functions.
273These functions map assembly program counters to their machine code counterparts, establishing the correspondence between `positions' in an assembly program and `positions' in a machine code program.
274At the heart of this process is \texttt{sigma0} which traverses an assembly program building maps from pseudo program counters to program counters.
275This function fails if and only if an internal call to \texttt{assembly\_1\_pseudoinstruction\_safe} fails, which happens if a jump pseudoinstruction is expanded incorrectly:
276\begin{lstlisting}
277definition sigma0: pseudo_assembly_program $\rightarrow$ policy_type
278  $\rightarrow$ option (nat $\times$ (nat $\times$ (BitVectorTrie Word 16))) := $\ldots$
279\end{lstlisting}
280Here, the returned \texttt{BitVectorTrie} is a map between pseudo program counters and program counters, and is constructed by successively expanding pseudoinstructions and incrementing the two program counters the requisite amount to keep them in correct correspondence.
281The two natural numbers returned are the maximum values that the two program counters attained.
282
283We eventually lift this to functions from pseudo program counters to program counters, implemented as \texttt{Word}s:
284\begin{lstlisting}
285definition sigma_safe:
286  pseudo_assembly_program $\rightarrow$ policy_type $\rightarrow$ option (Word $\rightarrow$ Word) := $\ldots$
287\end{lstlisting}
288
289Now, it's possible to define what a `good policy' is for a program \texttt{p}.
290A policy \texttt{pol} is deemed good when it prevents \texttt{sigma\_safe} from failing on \texttt{p}.
291Failure is only possible when the policy dictates that short or medium jumps be expanded to jumps to locations too far away, or when the produced object code does not fit into code memory.
292A \texttt{policy} for a program \texttt{p} is a policy that is good for \texttt{p}:
293\begin{lstlisting}
294definition policy_ok := $\lambda$pol.$\lambda$p. sigma_safe p $\neq$ None $\ldots$
295definition policy :=
296  $\lambda$p. $\Sigma$jump_expansion: policy_type. policy_ok jump_expansion p
297\end{lstlisting}
298
299Finally, we obtain \texttt{sigma}, a mapping from pseudo program counters to program counters that takes in input a good policy and thus never fails.
300Note how we avoid failure here, and in most of the remaining functions, by restricting the domain using the dependent type \texttt{policy}:
301\begin{lstlisting}
302definition sigma: $\forall$p. policy p $\rightarrow$ Word $\rightarrow$ Word := $\ldots$
303\end{lstlisting}
304
305% ---------------------------------------------------------------------------- %
306% SECTION                                                                      %
307% ---------------------------------------------------------------------------- %
308\subsection{Correctness of the assembler with respect to fetching}
309\label{subsect.total.correctness.of.the.assembler}
310
311Using our policies, we now work toward proving the total correctness of the assembler.
312By `total correctness', we mean that the assembly process never fails when provided with a good policy and that the process does not change the semantics of a certain class of well behaved assembly programs.
313Naturally, this necessitates keeping some sort of correspondence between addresses at the assembly level and addresses at the machine code level.
314For this, we use the \texttt{sigma} machinery defined at the end of Subsection~\ref{subsect.policies}.
315
316We expand pseudoinstructions using the function \texttt{expand\_pseudo\_instruction}.
317This takes an assembly program (consisting of a list of pseudoinstructions), a good policy for the program and a pointer to the pseudo code memory.
318It returns a list of instructions, corresponding to the expanded pseudoinstruction referenced by the pointer.
319The policy is used to decide how to expand \texttt{Call}s, \texttt{Jmp}s and conditional jumps.
320The function is given a dependent type that incorporates its specification.
321Its pre- and post-conditions are omitted in the paper due to lack of space.
322We show them as an example in the next function, \texttt{build\_maps}.
323\begin{lstlisting}
324definition expand_pseudo_instruction:
325  $\forall$program. $\forall$pol: policy program.
326  $\forall$ppc:Word. $\ldots$ $\Sigma$res. list instruction. $\ldots$ := $\ldots$
327\end{lstlisting}
328
329The following function, \texttt{build\_maps}, is used to construct a pair of mappings from program counters to labels and cost labels, respectively.
330Cost labels are a technical device used in the CerCo prototype C compiler for proving that the compiler is cost preserving.
331For our purposes in this paper, they can be safely ignored, though the interested reader may consult~\cite{amadio:certifying:2010} for an overview.
332
333The label map, on the other hand, records the position of labels that appear in an assembly program, so that the pseudoinstruction expansion process can replace them with real memory addresses:
334\begin{lstlisting}
335definition build_maps:
336 $\forall$p. $\forall$pol: policy p.
337 $\Sigma$res : ((BitVectorTrie Word 16) $\times$ (BitVectorTrie Word 16)).
338   let $\langle$labels, costs$\rangle$ := res in
339     $\forall$id. occurs_exactly_once id ($\pi_2$ p) $\rightarrow$
340    let addr := address_of_word_labels_code_mem ($\pi_2$ p) id in
341      lookup $\ldots$ id labels (zero $\ldots$) = sigma pseudo_program pol addr := $\ldots$
342\end{lstlisting}
343The type of \texttt{build\_maps} owes to our use of Matita's Russell facility to provide a strong specification for the function in the type (c.f. the use of $\Sigma$-types and coercions, through which Russell is simulated in Matita).
344We express that for all labels that appear exactly once in any assembly program, the newly created map used in the implementation, and the stronger \texttt{sigma} function used in the specification, agree.
345
346Using \texttt{build\_maps}, we can express the following lemma, expressing the correctness of the assembly function:
347\begin{lstlisting}
348lemma assembly_ok: $\forall$p,pol,assembled.
349  let $\langle$labels, costs$\rangle$ := build_maps p pol in
350  $\langle$assembled,costs$\rangle$ = assembly p pol $\rightarrow$
351  let cmem := load_code_memory assembled in
352  let preamble := $\pi_1$ p in
353  let dlbls := construct_datalabels preamble in
354  let addr := address_of_word_labels_code_mem ($\pi_2$ p) in
355  let lk_lbls := λx. sigma p pol (addr x) in
356  let lk_dlbls := λx. lookup $\ldots$ x datalabels (zero ?) in
357  $\forall$ppc, pi, newppc.
358  $\forall$prf: $\langle$pi, newppc$\rangle$ = fetch_pseudo_instruction ($\pi_2$ p) ppc.
359  $\forall$len, assm.
360  let spol := sigma program pol ppc in
361  let spol_len := spol + len in
362  let echeck := encoding_check cmem spol spol_len assm in
363  let a1pi := assembly_1_pseudoinstruction in
364  $\langle$len, assm$\rangle$ = a1pi p pol ppc lk_lbls lk_dlbls pi (refl $\ldots$) (refl $\ldots$) ? $\rightarrow$
365    echeck $\wedge$ sigma p pol newppc = spol_len.
366\end{lstlisting}
367Suppose also we assemble our program \texttt{p} in accordance with a policy \texttt{pol} to obtain \texttt{assembled}.
368Here, we perform a `sanity check' to ensure that the two cost label maps generated are identical, before loading the assembled program into code memory \texttt{cmem}.
369Then, for every pseudoinstruction \texttt{pi}, pseudo program counter \texttt{ppc} and new pseudo program counter \texttt{newppc}, such that we obtain \texttt{pi} and \texttt{newppc} from fetching a pseudoinstruction at \texttt{ppc}, we check that assembling this pseudoinstruction produces the correct number of machine code instructions, and that the new pseudo program counter \texttt{ppc} has the value expected of it.
370
371Theorem \texttt{fetch\_assembly} establishes that the \texttt{fetch} and \texttt{assembly1} functions interact correctly.
372The \texttt{fetch} function, as its name implies, fetches the instruction indexed by the program counter in the code memory, while \texttt{assembly1} maps a single instruction to its byte encoding:
373\begin{lstlisting}
374theorem fetch_assembly: $\forall$pc, i, cmem, assembled.  assembled=assembly1 i $\rightarrow$
375  let len := length $\ldots$ assembled in
376  encoding_check cmem pc (pc + len) assembled $\rightarrow$
377    let fetched := fetch code_memory (bitvector_of_nat $\ldots$ pc) in
378    let $\langle$instr_pc, ticks$\rangle$ := fetched in
379    let $\langle$instr, pc'$\rangle$ := instr_pc in
380      (eq_instruction instr i $\wedge$ eqb ticks (ticks_of_instruction instr) $\wedge$
381       eq_bv $\ldots$ pc' (pc + len)) = true.
382\end{lstlisting}
383In particular, we read \texttt{fetch\_assembly} as follows.
384Given an instruction, \texttt{i}, we first assemble the instruction to obtain \texttt{assembled}, checking that the assembled instruction was stored in code memory correctly.
385Fetching from code memory, we obtain \texttt{fetched}, a tuple consisting of the instruction, new program counter, and the number of ticks this instruction will take to execute.
386Deconstructing these tuples, we finally check that the fetched instruction is the same instruction that we began with, and the number of ticks this instruction will take to execute is the same as the result returned by a lookup function, \texttt{ticks\_of\_instruction}, devoted to tracking this information.
387Or, in plainer words, assembling and then immediately fetching again gets you back to where you started.
388
389Lemma \texttt{fetch\_assembly\_pseudo} (slightly simplified, here) is obtained by composition of \texttt{expand\_pseudo\_instruction} and \texttt{assembly\_1\_pseudoinstruction}:
390\begin{lstlisting}
391lemma fetch_assembly_pseudo:
392 ∀program.∀pol:policy program.∀ppc.∀code_memory.
393  let pi := $\pi_1$ (fetch_pseudo_instruction ($\pi_2$ program) ppc) in
394  let instructions := expand_pseudo_instruction program pol ppc ... in
395  let $\langle$len,assembled$\rangle$ := assembly_1_pseudoinstruction program pol ppc ... in
396  encoding_check code_memory pc (pc + len) assembled →
397  fetch_many code_memory (pc + len) pc instructions.
398\end{lstlisting}
399Here, \texttt{len} is the number of machine code instructions the pseudoinstruction at hand has been expanded into, and \texttt{encoding\_check} is a recursive function that checks that assembled machine code is correctly stored in code memory.
400We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{jump\_expansion} and \texttt{expand\_pseudo\_instruction}.
401The function \texttt{fetch\_many} fetches multiple machine code instructions from code memory and performs some routine checks.
402
403Intuitively, Lemma \texttt{fetch\_assembly\_pseudo} can be read as follows.
404Suppose we expand the pseudoinstruction at \texttt{ppc} with the policy decision \texttt{pol}, obtaining the list of machine code instructions \texttt{instructions}.
405Suppose we also assemble the pseudoinstruction at \texttt{ppc} to obtain \texttt{assembled}, a list of bytes.
406Then, we check with \texttt{fetch\_many} that the number of machine instructions that were fetched matches the number of instruction that \texttt{expand\_pseudo\_instruction} expanded.
407
408The final lemma in this series is \texttt{fetch\_assembly\_pseudo2} that combines the Lemma \texttt{fetch\_assembly\_pseudo} with the correctness of the functions that load object code into the processor's memory.
409\begin{lstlisting}
410lemma fetch_assembly_pseudo2:
411 ∀program,pol,ppc.
412  let $\langle$labels,costs$\rangle$ := build_maps program pol in
413  let assembled := $\pi_1$ (assembly program pol) in
414  let code_memory := load_code_memory assembled in
415  let data_labels := construct_datalabels ($\pi_1$ program) in
416  let lookup_labels :=
417    λx. sigma $\ldots$ pol (address_of_word_labels_code_mem ($\pi_2$ program) x) in
418  let lookup_datalabels := λx. lookup ? ? x data_labels (zero ?) in
419  let $\langle$pi,newppc$\rangle$ := fetch_pseudo_instruction ($\pi_2$ program) ppc in
420  let instrs ≝ expand_pseudo_instruction program pol ppc ... in
421   fetch_many code_memory (sigma $\ldots$ pol newppc) (sigma $\ldots$ pol ppc) instrs.
422\end{lstlisting}
423
424We read \texttt{fetch\_assembly\_pseudo2} as follows.
425Suppose we are able to successfully assemble an assembly program using \texttt{assembly} and produce a code memory, \texttt{code\_memory}.
426Then, fetching a pseudoinstruction from the pseudo code memory at address \texttt{ppc} corresponds to fetching a sequence of instructions from the real code memory at address \texttt{sigma program pol ppc}.
427The fetched sequence corresponds to the expansion, according to \texttt{pol}, of the pseudoinstruction.
428
429At first, the lemmas appears to immediately imply the correctness of the assembler.
430However, this property is \emph{not} strong enough to establish that the semantics of an assembly program has been preserved by the assembly process since it does not establish the correspondence between the semantics of a pseudo-instruction and that of its expansion.
431In particular, the two semantics differ on instructions that \emph{could} directly manipulate program addresses.
432
433% ---------------------------------------------------------------------------- %
434% SECTION                                                                      %
435% ---------------------------------------------------------------------------- %
436\subsection{Total correctness for `well behaved' assembly programs}
437\label{subsect.total.correctness.for.well.behaved.assembly.programs}
438
439In any `reasonable' assembly language addresses in code memory are just data that can be manipulated in multiple ways by the program.
440An assembly program can forge, compare and move addresses around, shift existing addresses or apply logical and arithmetical operations to them.
441Further, every optimising assembler is allowed to modify code memory.
442Hence only the semantics of a few of the aforementioned operations are preserved by an optimising assembler/compiler.
443Moreover, this characterisation of well behaved programs is clearly undecidable.
444
445To obtain a reasonable statement of correctness for our assembler, we need to trace memory locations (and, potentially, registers) that contain memory addresses.
446This is necessary for two purposes.
447
448First we must detect (at run time) programs that manipulate addresses in well behaved ways, according to some approximation of well-behavedness.
449Second, we must compute statuses that correspond to pseudo-statuses.
450The contents of the program counter must be translated, as well as the contents of all traced locations, by applying the \texttt{sigma} map.
451Remaining memory cells are copied \emph{verbatim}.
452
453For instance, after a function call, the two bytes that form the return pseudo address are pushed on top of the stack, i.e. in internal RAM.
454This pseudo internal RAM corresponds to an internal RAM where the stack holds the real addresses after optimisation, and all the other values remain untouched.
455
456We use an \texttt{internal\_pseudo\_address\_map} to trace addresses of code memory addresses in internal RAM.
457The current code is parametric on the implementation of the map itself.
458\begin{lstlisting}
459axiom internal_pseudo_address_map: Type[0].
460\end{lstlisting}
461
462The \texttt{low\_internal\_ram\_of\_pseudo\_low\_internal\_ram} function converts the lower internal RAM of a \texttt{PseudoStatus} into the lower internal RAM of a \texttt{Status}.
463A similar function exists for higher internal RAM.
464Note that both RAM segments are indexed using addresses 7-bits long.
465The function is currently axiomatised, and an associated set of axioms prescribe the behaviour of the function:
466\begin{lstlisting}
467axiom low_internal_ram_of_pseudo_low_internal_ram:
468 internal_pseudo_address_map$\rightarrow$BitVectorTrie Byte 7$\rightarrow$BitVectorTrie Byte 7.
469\end{lstlisting}
470
471Next, we are able to translate \texttt{PseudoStatus} records into \texttt{Status} records using \texttt{status\_of\_pseudo\_status}.
472Translating a \texttt{PseudoStatus}'s code memory requires we expand pseudoinstructions and then assemble to obtain a trie of bytes.
473This never fails, providing that our policy is correct:
474\begin{lstlisting}
475definition status_of_pseudo_status: internal_pseudo_address_map $\rightarrow$
476  $\forall$ps:PseudoStatus. policy (code_memory $\ldots$ ps) $\rightarrow$ Status
477\end{lstlisting}
478
479The \texttt{next\_internal\_pseudo\_address\_map} function is responsible for run time monitoring of the behaviour of assembly programs, in order to detect well behaved ones.
480It returns a map that traces memory addresses in internal RAM after execution of the next pseudoinstruction, failing when the instruction tampers with memory addresses in unanticipated (but potentially correct) ways.
481It thus decides the membership of a strict subset of the set of well behaved programs.
482\begin{lstlisting}
483definition next_internal_pseudo_address_map: internal_pseudo_address_map
484  $\rightarrow$ PseudoStatus $\rightarrow$ option internal_pseudo_address_map
485\end{lstlisting}
486
487The function \texttt{ticks\_of} computes how long---in clock cycles---a pseudoinstruction will take to execute when expanded in accordance with a given policy.
488The function returns a pair of natural numbers, needed for recording the execution times of each branch of a conditional jump.
489\begin{lstlisting}
490definition ticks_of:
491  $\forall$p:pseudo_assembly_program. policy p $\rightarrow$ Word $\rightarrow$ nat $\times$ nat := $\ldots$
492\end{lstlisting}
493
494Finally, we are able to state and prove our main theorem.
495This relates the execution of a single assembly instruction and the execution of (possibly) many machine code instructions, as long .
496That is, the assembly process preserves the semantics of an assembly program, as it is translated into machine code, as long as we are able to track memory addresses properly:
497\begin{lstlisting}
498theorem main_thm:
499 ∀M,M':internal_pseudo_address_map.∀ps.∀pol: policy ps.
500  next_internal_pseudo_address_map M ps = Some $\ldots$ M' →
501   ∃n.
502      execute n (status_of_pseudo_status M ps pol)
503    = status_of_pseudo_status M'
504       (execute_1_pseudo_instruction (ticks_of (code_memory $\ldots$ ps) pol) ps)
505       [pol].
506\end{lstlisting}
507The statement is standard for forward simulation, but restricted to \texttt{PseudoStatuses} \texttt{ps} whose next instruction to be executed is well-behaved with respect to the \texttt{internal\_pseudo\_address\_map} \texttt{M}.
508Theorem \texttt{main\_thm} establishes the total correctness of the assembly process and can simply be lifted to the forward simulation of an arbitrary number of well behaved steps on the assembly program.
509
510% ---------------------------------------------------------------------------- %
511% SECTION                                                                      %
512% ---------------------------------------------------------------------------- %
513\section{Conclusions}
514\label{sect.conclusions}
515
516We are proving the total correctness of an assembler for MCS-51 assembly language.
517In particular, our assembly language featured labels, arbitrary conditional and unconditional jumps to labels, global data and instructions for moving this data into the MCS-51's single 16-bit register.
518Expanding these pseudoinstructions into machine code instructions is not trivial, and the proof that the assembly process is `correct', in that the semantics of a subset of assembly programs are not changed is complex.
519Further, we have observed the `shocking' fact that any optimising assembler cannot preserve the semantics of all assembly programs.
520
521The formalisation is a key component of the CerCo project, which aims to produce a verified concrete complexity preserving compiler for a large subset of the C programming language.
522The verified assembler, complete with the underlying formalisation of the semantics of MCS-51 machine code (described fully in~\cite{mulligan:executable:2011}), will form the bedrock layer upon which the rest of the CerCo project will build its verified compiler platform.
523However, further work is needed.
524In particular, as it stands, the code produced by the prototype CerCo C compiler does not fall into the `semantics preserving' subset of assembly programs for our assembler.
525This is because the MCS-51 features a small stack space, and a larger stack is customarily manually emulated in external RAM.
526As a result, the majority of programs feature slices of memory addresses and program counters being moved in-and-out of external RAM via the registers, simulating the stack mechanism.
527At the moment, this movement is not tracked by \texttt{internal\_pseudo\_address\_map}, which only tracks the movement of memory addresses in low internal RAM.
528We leave extending this tracking of memory addresses throughout the whole of the MCS-51's address spaces as future work.
529
530It is interesting to compare our work to an `industrial grade' assembler for the MCS-51: SDCC~\cite{sdcc:2011}.
531SDCC is the only open source C compiler that targets the MCS-51 instruction set.
532It appears that all pseudojumps in SDCC assembly are expanded to \texttt{LJMP} instructions, the worst possible jump expansion policy from an efficiency point of view.
533Note that this policy is the only possible policy \emph{in theory} that can preserve the semantics of an assembly program during the assembly process.
534However, this comes at the expense of assembler completeness: the generated program may be too large to fit into code memory.
535In this respect, there is a trade-off between the completeness of the assembler and the efficiency of the assembled program.
536The definition and proof of a complete, optimal (in the sense that object code size is minimised) and correct jump expansion policy is ongoing work.
537
538Aside from their application in verified compiler projects such as CerCo and CompCert, verified assemblers such as ours could also be applied to the verification of operating system kernels.
539Of particular note is the verified seL4 kernel~\cite{klein:sel4:2009,klein:sel4:2010}.
540This verification explicitly assumes the existence of, amongst other things, a trustworthy assembler and compiler.
541
542Note that both CompCert and the seL4 formalisation assume the existence of `trustworthy' assemblers.
543Our observation that an optimising assembler cannot preserve the semantics of every assembly program may have important consequences for these projects.
544If CompCert chooses to assume the existence of an optimising assembler, then care should be made to ensure that any assembly program produced by the CompCert compiler falls into the subset of programs that have a hope of having their semantics preserved by an optimising assembler.
545
546Our formalisation exploits dependent types in different ways and for multiple
547purposes. The first purpose is to reduce potential errors in the formalisation
548of the microprocessor. In particular,
549dependent types are used to constraint the size of bit-vectors and
550tries that represent memory quantities and memory areas respectively.
551They are also used as explained in~\cite{mulligan:executable:2011}.
552to simulate polymorphic variants in Matita. Polymorphic variants nicely
553capture the absolutely unorthogonal instruction set of the MCS-51 where every
554opcode must accept its own subset of the 11 addressing mode of the processor.
555
556The second purpose is to single out the sources of incompleteness. By
557abstracting our functions over the dependent type of correct policies, we were
558able to manifest the fact that the compiler never refuses to compile a program
559where a correct policy exists. This also allowed to simplify the
560initial proof by dropping lemmas establishing that one function fails if and
561only if some other one does so.
562
563Finally, dependent types, together with Matita's liberal system of coercions,
564allow to simulate almost entirely in user space the proof methodology
565``Russell'' of Sozeau~\cite{sozeau:subset:2006}. However, not every
566proof has been done this way: we only used this style to prove that a
567function satisfies a specification that only involves that function in a
568significant way. For example, it would be unnatural to see the proof that
569fetch and assembly commute as the specification of one of the two functions.
570
571\subsection{Related work}
572\label{subsect.related.work}
573
574% piton
575We are not the first to consider the total correctness of an assembler for a non-trivial assembly language.
576Perhaps the most impressive piece of work in this domain is the Piton stack~\cite{moore:piton:1996,moore:grand:2005}.
577This was a stack of verified components, written and verified in ACL2, ranging from a proprietary FM9001 microprocessor verified at the gate level, to assemblers and compilers for two high-level languages---a dialect of Lisp and $\mu$Gypsy~\cite{moore:grand:2005}.
578
579% jinja
580Klein and Nipkow consider a Java-like programming language, Jinja~\cite{klein:machine:2006,klein:machine:2010}.
581They provide a compiler, virtual machine and operational semantics for the programming language and virtual machine, and prove that their compiler is semantics and type preserving.
582
583We believe some other verified assemblers exist in the literature.
584However, what sets our work apart from that above is our attempt to optimise the machine code generated by our assembler.
585This complicates any formalisation effort, as the best possible selection of machine instructions must be made, especially important on a device such as the MCS-51 with a miniscule code memory.
586Further, care must be taken to ensure that the time properties of an assembly program are not modified by the assembly process lest we affect the semantics of any program employing the MCS-51's I/O facilities.
587This is only possible by inducing a cost model on the source code from the optimisation strategy and input program.
588This will be a \emph{leit motif} of CerCo.
589
590Finally, mention of CerCo will invariably invite comparisons with CompCert~\cite{compcert:2011,leroy:formal:2009}, another verified compiler project related to CerCo.
591As previously mentioned, CompCert considers only extensional correctness of the compiler, and not intensional correctness, which CerCo focusses on.
592However, CerCo also extends CompCert in other ways.
593Namely, the CompCert verified compilation chain terminates at the assembly level, and takes for granted the existence of a trustworthy assembler.
594CerCo chooses to go further, by considering a verified compilation chain all the way down to the machine code level.
595The work presented in this publication is one part of CerCo's extension over CompCert.
596
597\subsection{Resources}
598\label{subsect.resources}
599
600All files relating to our formalisation effort can be found online at~\url{http://cerco.cs.unibo.it}. The code of the compiler has been completed, and the
601proof of correctness described here is still in progress. In particular, we
602have assumed several properties of ``library functions'' related in particular
603to modular arithmetics and datastructures manipulation. Moreover, we only
604completed the interesting cases of some of the main theorems that proceed by
605cases on all the possible opcodes.
606We thus believe that the proof strategy is sound and that we will be able to
607close soon all axioms, up to possible minor bugs that should have local fixes
608that do not affect the global proof strategy.
609
610The development, including the definition of the executable semantics of the MCS-51, is spread across 17 files, totalling around 11,500 lines of Matita source.
611The bulk of the proof described herein is contained in a single file, \texttt{AssemblyProof.ma}, consisting at the moment of approximately 2500 lines of Matita source. Another 1000 lines of proofs are spread all over the development because
612of dependent types and the Russell proof style, that do not allow to separate the code from the proofs. The low ratio between the number of lines of code and
613the number of lines of proof is unusual. It is justified by the fact that
614the pseudo-assembly and the assembly language share most constructs and that
615large parts of the semantics is also shared. Thus many lines of code are
616required to describe the complex semantics of the processor, but, for
617the shared cases, the proof of preservation of the semantics is essentially
618trivial.
619
620\bibliography{cpp-2012-asm.bib}
621
622\end{document}\renewcommand{\verb}{\lstinline}
623\def\lstlanguagefiles{lst-grafite.tex}
624\lstset{language=Grafite}
Note: See TracBrowser for help on using the repository browser.