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} |
---|
48 | We consider the formalisation of an assembler for Intel MCS-51 assembly language in the Matita proof assistant. |
---|
49 | This formalisation forms a major component of the EU-funded CerCo project, concering the construction and formalisation of a concrete complexity preserving compiler for a large subset of the C programming language. |
---|
50 | |
---|
51 | The efficient expansion of pseudoinstructions---particularly jumps---into MCS-51 machine instructions is complex. |
---|
52 | We employ a strategy, involving the use of `policies', that separates the decision making over how jumps should be expanded from the expansion process itself. |
---|
53 | This makes the proof of correctness for the assembler significantly more straightforward. |
---|
54 | |
---|
55 | We prove, under the assumption of the existence of a correct policy, that the assembly process never fails and preserves the semantics of a subset of assembly programs. |
---|
56 | Correct policies fail to exist only in a limited number of pathological circumstances. |
---|
57 | Quite surprisingly, it is impossible for an optimising assembler to preserve the semantics of every assembly program. |
---|
58 | \end{abstract} |
---|
59 | |
---|
60 | % ---------------------------------------------------------------------------- % |
---|
61 | % SECTION % |
---|
62 | % ---------------------------------------------------------------------------- % |
---|
63 | \section{Introduction} |
---|
64 | \label{sect.introduction} |
---|
65 | |
---|
66 | We consider the formalisation of an assembler for the Intel MCS-51 8-bit microprocessor in the Matita proof assistant~\cite{asperti:user:2007}. |
---|
67 | This formalisation forms a major component of the EU-funded CerCo project~\cite{cerco:2011}, concering the construction and formalisation of a concrete complexity preserving compiler for a large subset of the C programming language. |
---|
68 | |
---|
69 | The MCS-51 dates from the early 1980s and is commonly called the 8051/8052. |
---|
70 | Despite the microprocessor's age, derivatives are still widely manufactured by a number of semiconductor foundries. |
---|
71 | As a result the processor is widely used, especially in embedded systems development, where well-tested, cheap, predictable microprocessors find their niche. |
---|
72 | |
---|
73 | The MCS-51 has a relative paucity of features compared to its more modern brethren. |
---|
74 | In particular, the MCS-51 does not possess a cache or any instruction pipelining that would make predicting the concrete cost of executing a single instruction an involved process. |
---|
75 | Instead, each semiconductor foundry that produces an MCS-51 derivative is able to provide accurate timing information in clock cycles for each instruction in their derivative's instruction set. |
---|
76 | It is important to stress that this timing information, unlike in more sophisticated processors, is not an estimate, it is a definition. |
---|
77 | For the MCS-51, if a manufacturer states that a particular opcode takes three clock cycles to execute, then that opcode \emph{always} takes three clock cycles to execute. |
---|
78 | |
---|
79 | This predicability of timing information is especially attractive to the CerCo consortium. |
---|
80 | We are in the process of constructing a certified, concrete complexity compiler for a realistic processor, and not for building and formalising the worst case execution time (WCET) tools that would be necessary to achieve the same result with, for example, a modern ARM or PowerPC microprocessor. |
---|
81 | |
---|
82 | However, the MCS-51's paucity of features is a double edged sword. |
---|
83 | In particular, the MCS-51 features relatively miniscule memory spaces (including read-only code memory, stack and internal/external random access memory) by modern standards. |
---|
84 | As a result our compiler, to have any sort of hope of successfully compiling realistic C programs, ought to produce `tight' machine code. |
---|
85 | This is not simple and requires the use of optimisations. |
---|
86 | |
---|
87 | For 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}. |
---|
88 | Each of these three instructions expects arguments in different sizes and behaves in 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. |
---|
89 | Consequently, 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 should be selected. |
---|
90 | |
---|
91 | The prototype CerCo C compiler does not attempt to select the smallest jump opcode in this manner, as this was thought to unneccessarily complicate the compilation chain. |
---|
92 | Instead, the compiler targets an assembly language, complete with pseudoinstructions including bespoke \texttt{Jmp} and \texttt{Call} instructions. |
---|
93 | Labels, 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 also feature. |
---|
94 | This latter feature will ease any later consideration of separate compilation in the CerCo compiler. |
---|
95 | An assembler is used to expand pseudoinstructions into MCS-51 machine code. |
---|
96 | |
---|
97 | However, this assembly process is not trivial, for numerous reasons. |
---|
98 | For example, our conditional jumps to labels behave differently from their machine code counterparts. |
---|
99 | At the machine code level, all conditional jumps are `short', limiting their range. |
---|
100 | However, at the assembly level, conditional jumps may jump to a label that appears anywhere in the program, significantly liberalising the use of conditional jumps and further simplifying the design of the CerCo compiler. |
---|
101 | |
---|
102 | Further, trying to na\"ively relate assembly programs with their machine code counterparts simply does not work. |
---|
103 | Machine code programs that fetch from constant addresses in code memory or programs that combine the program counter with constant shifts do not make sense at the assembly level, since the position of instructions in code memory will be known only after assembly and optimisation. |
---|
104 | More generally, memory addresses can only be compared with other memory addresses. |
---|
105 | However, checking that memory addresses are only compared against each other at the assembly level is in fact undecidable. |
---|
106 | In short, we come to the shocking realisation that, with optimisations, the full preservation of the semantics of the two languages is impossible. |
---|
107 | We believe that this revelation is significant for large formalisation projects that assume the existence of a correct assembler. |
---|
108 | Projects in this class include both the recent CompCert~\cite{compcert:2011,leroy:formal:2009} and seL4 formalisations~\cite{klein:sel4:2009}. |
---|
109 | |
---|
110 | Yet, the situation is even more complex than having to expand pseudoinstructions correctly. |
---|
111 | In 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. |
---|
112 | First, the semantics of some functions of the MCS-51, notably I/O, depend on the microprocessor's clock. |
---|
113 | Changing how long a particular program takes to execute can affect the semantics of a program. |
---|
114 | This is undesirable. |
---|
115 | |
---|
116 | Second, as mentioned, the CerCo consortium is in the business of constructing a verified compiler for the C programming language. |
---|
117 | However, unlike CompCert~\cite{compcert:2011,leroy:formal:2009,leroy:formally:2009}---which currently represents the state of the art for `industrial grade' verified compilers---CerCo considers not just the \emph{extensional correctness} of the compiler, but also its \emph{intensional correctness}. |
---|
118 | That is, CompCert focusses solely on the preservation of the \emph{meaning} of a program during the compilation process, guaranteeing that the program's meaning does not change as it is gradually transformed into assembly code. |
---|
119 | However in any realistic compiler (even the CompCert compiler!) there is no guarantee that the program's time properties are preserved during the compilation process; a compiler's `optimisations' could, in theory, even conspire to degrade the concrete complexity of certain classes of programs. |
---|
120 | CerCo aims to expand the current state of the art by producing a compiler where this temporal degradation is guaranteed not to happen. |
---|
121 | Moreover, CerCo's approach lifts a program's timing information to the source (C language) level, wherein the programmer can reason about a program's intensional properties by directly examining the source code that they write. |
---|
122 | |
---|
123 | In order to achieve this CerCo imposes a cost model on programs, or more specifically, on simple blocks of instructions. |
---|
124 | This 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. |
---|
125 | In short, we aim to obtain a very precise costing for a program by embracing the compilation process, not ignoring it. |
---|
126 | This, however, complicates the proof of correctness for the compiler proper: for every translation pass from intermediate language to intermediate language, we must prove that not only has the meaning of a program been preserved, but also its complexity characteristics. |
---|
127 | This also applies for the translation from assembly language to machine code. |
---|
128 | |
---|
129 | How do we assign a cost to a pseudoinstruction? |
---|
130 | As mentioned, conditional jumps at the assembly level can jump to a label appearing anywhere in the program. |
---|
131 | However, at the machine code level, conditional jumps are limited to jumping `locally', using a measly byte offset. |
---|
132 | To 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'): |
---|
133 | \begin{displaymath} |
---|
134 | \begin{array}{r@{\quad}l@{\;\;}l@{\qquad}c@{\qquad}l@{\;\;}l} |
---|
135 | & \mathtt{JZ} & label & & \mathtt{JZ} & \text{size of \texttt{SJMP} instruction} \\ |
---|
136 | & \ldots & & \text{translates to} & \mathtt{SJMP} & \text{size of \texttt{LJMP} instruction} \\ |
---|
137 | label: & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} & \Longrightarrow & \mathtt{LJMP} & \text{address of \textit{label}} \\ |
---|
138 | & & & & \ldots & \\ |
---|
139 | & & & & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} |
---|
140 | \end{array} |
---|
141 | \end{displaymath} |
---|
142 | In the translation, if \texttt{JZ} fails, we fall through to the \texttt{SJMP} which jumps over the \texttt{LJMP}. |
---|
143 | Naturally, if \textit{label} is close enough, a conditional jump pseudoinstruction is mapped directly to a conditional jump machine instruction; the above translation only applies if \textit{label} is not sufficiently local. |
---|
144 | This leaves the problem, addressed below, of calculating whether a label is indeed `close enough' for the simpler translation to be used. |
---|
145 | |
---|
146 | Crucially, the above translation demonstrates the difficulty in predicting how many clock cycles a pseudoinstruction will take to execute. |
---|
147 | A conditional jump may be mapped to a single machine instruction or a block of three. |
---|
148 | Perhaps more insidious, the number of cycles needed to execute the instructions in the two branches of a translated conditional jump may be different. |
---|
149 | Depending 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}. |
---|
150 | These issues must also be dealt with in order to prove that the translation pass preserves the concrete complexity of the code, and that the semantics of a program using the MCS-51's I/O facilities does not change. |
---|
151 | We address this problem by parameterizing the semantics over a cost model. |
---|
152 | We prove the preservation of concrete complexity only for the program-dependent cost model induced by the optimisation. |
---|
153 | |
---|
154 | The question remains: how do we decide whether to expand a jump into an \texttt{SJMP} or an \texttt{LJMP}? |
---|
155 | To understand why this problem is not trivial, consider the following snippet of assembly code: |
---|
156 | \begin{displaymath} |
---|
157 | \text{dpm: finish me} |
---|
158 | \end{displaymath} |
---|
159 | |
---|
160 | As our example shows, given an occurence $l$ of an \texttt{LJMP} instruction, it may be possible to shrink $l$ to an occurence of an \texttt{SJMP} providing we can shrink any \texttt{LJMP}s that exist between $l$ and its target location. |
---|
161 | However, shrinking these \texttt{LJMP}s may in turn depend on shrinking $l$ to an \texttt{SJMP}, as it is perfectly possible to jump backwards. |
---|
162 | In short, unless we can somehow break this loop of circularity, and similar knotty configurations of jumps, we are stuck with a suboptimal solution to the expanding jumps problem. |
---|
163 | |
---|
164 | How we went about resolving this problem affected the shape of our proof of correctness for the whole assembler in a rather profound way. |
---|
165 | We first attempted to synthesize a solution bottom up: starting with no solution, we gradually refine a solution using the same functions that implement the jump expansion. |
---|
166 | Using this technique, solutions can fail to exist, and the proof quickly descends into a diabolical quagmire. |
---|
167 | |
---|
168 | Abandoning 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. |
---|
169 | Assuming the existence of a correct policy, we proved the implementation of the assembler correct. |
---|
170 | Further, we proved that the assembler fails to assemble an assembly program if and only if a correct policy does not exist. |
---|
171 | Policies 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. |
---|
172 | The first case would constitute a serious compiler error, and hopefully certifying the rest of the compiler would rule this possibility out. |
---|
173 | The second case is unavoidable---certified compiler or not, trying to load a huge program into a small code memory will break \emph{something}. |
---|
174 | |
---|
175 | The rest of this paper is a detailed description of this proof. |
---|
176 | |
---|
177 | % ---------------------------------------------------------------------------- % |
---|
178 | % SECTION % |
---|
179 | % ---------------------------------------------------------------------------- % |
---|
180 | \subsection{Overview of the paper} |
---|
181 | \label{subsect.overview.of.the.paper} |
---|
182 | In Section~\ref{sect.matita} we provide a brief overview of the Matita proof assistant for the unfamiliar reader. |
---|
183 | In Section~\ref{sect.the.proof} we discuss the design and implementation of the proof proper. |
---|
184 | In Section~\ref{sect.conclusions} we conclude. |
---|
185 | |
---|
186 | % ---------------------------------------------------------------------------- % |
---|
187 | % SECTION % |
---|
188 | % ---------------------------------------------------------------------------- % |
---|
189 | \section{Matita} |
---|
190 | \label{sect.matita} |
---|
191 | |
---|
192 | Matita is a proof assistant based on the Calculus of (Co)inductive Constructions~\cite{asperti:user:2007}. |
---|
193 | For those familiar with Coq, Matita's syntax and mode of operation should be entirely familiar. |
---|
194 | However, we take time here to explain one of Matita's syntactic idiosyncrasies. |
---|
195 | The use of `$\mathtt{?}$' or `$\mathtt{\ldots}$' in an argument position denotes a term or terms to be inferred automatically by unification, respectively. |
---|
196 | The use of `$\mathtt{?}$' in the body of a definition, lemma or axiom denotes an incomplete term that is to be closed, by hand, using tactics. |
---|
197 | |
---|
198 | % ---------------------------------------------------------------------------- % |
---|
199 | % SECTION % |
---|
200 | % ---------------------------------------------------------------------------- % |
---|
201 | \section{The proof} |
---|
202 | \label{sect.the.proof} |
---|
203 | |
---|
204 | \subsection{The assembler and semantics of machine code} |
---|
205 | \label{subsect.the.assembler.and.semantics.of.machine.code} |
---|
206 | |
---|
207 | The formalisation in Matita of the semantics of MCS-51 machine code is described in~\cite{mulligan:executable:2011}. |
---|
208 | We merely describe enough here to understand the rest of the proof. |
---|
209 | |
---|
210 | At heart, the MCS-51 emulator centres around a \texttt{Status} record, describing the current state of the microprocessor. |
---|
211 | This record contains fields corresponding to the microprocessor's program counter, special function registers, and so on. |
---|
212 | At the machine code level, code memory is implemented as a trie of bytes, addressed by the program counter. |
---|
213 | Machine code programs are loaded into \texttt{Status} using the \texttt{load\_code\_memory} function. |
---|
214 | |
---|
215 | We may execut a single step of a machine code program using the \texttt{execute\_1} function, which returns an updated \texttt{Status}: |
---|
216 | \begin{lstlisting} |
---|
217 | definition execute_1: Status $\rightarrow$ Status := $\ldots$ |
---|
218 | \end{lstlisting} |
---|
219 | The function \texttt{execute} allows one to execute an arbitrary, but fixed (due to Matita's normalisation requirement!) number of steps of a program. |
---|
220 | |
---|
221 | Naturally, assembly programs have analogues. |
---|
222 | The counterpart of the \texttt{Status} record is \texttt{PseudoStatus}. |
---|
223 | Instead 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. |
---|
224 | Our analogue of \texttt{execute\_1} is \texttt{execute\_1\_pseudo\_instruction}: |
---|
225 | \begin{lstlisting} |
---|
226 | definition execute_1_pseudo_instruction: (Word $\rightarrow$ nat $\times$ nat) $\rightarrow$ |
---|
227 | PseudoStatus $\rightarrow$ PseudoStatus := $\ldots$ |
---|
228 | \end{lstlisting} |
---|
229 | Notice, here, that the emulation function for assembly programs takes an additional argument. |
---|
230 | This 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. |
---|
231 | We call this function a \emph{costing}, and note that the costing is induced by the particular strategy we use to expand pseudoinstructions. |
---|
232 | If 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. |
---|
233 | |
---|
234 | The 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 the number of clock ticks needed for execution. |
---|
235 | This timing information is used inside \texttt{execute\_1\_pseudo\_instruction} to update the clock of the \texttt{PseudoStatus}. |
---|
236 | During the proof of correctness of the assembler we relate the clocks of \texttt{Status}es and \texttt{PseudoStatus}es. |
---|
237 | |
---|
238 | The assembler, mapping programs consisting of lists of pseudoinstructions to lists of bytes, operates in a mostly straightforward manner. |
---|
239 | To 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: |
---|
240 | \begin{displaymath} |
---|
241 | [\mathtt{P_1}, \ldots \mathtt{P_n}] \xrightarrow{\mathtt{flatten}\left(\mathtt{P_i} \xrightarrow{\mbox{\fontsize{7}{9}\selectfont$\mathtt{expand}$}} \mathtt{[I_1^i, \ldots I^q_i]} \xrightarrow{\mbox{\fontsize{7}{9}\selectfont$\mathtt{assembly1}^*$}} \mathtt{[0110]}\right)^{*}} \mathtt{[010101]} |
---|
242 | \end{displaymath} |
---|
243 | Here $\mathtt{I^i_j}$ for $1 \leq j \leq q$ are the $q$ machine code instructions obtained by expanding, with \texttt{expand\_pseudo\_instruction}, a single pseudoinstruction. |
---|
244 | Each machine code instruction $\mathtt{I^i_j}$ is then assembled, using the \texttt{assembly1} function, into a list of bytes. |
---|
245 | This process is iterated for each pseudoinstruction, before the lists are flattened into a single bit list representation of the original assembly program. |
---|
246 | |
---|
247 | By inspecting the above diagram, it would appear that the best way to proceed with a proof that the assembly process does not change the semantics of an assembly program is via a decomposition of the problem into two subproblems. |
---|
248 | Namely, we first expand any and all pseudoinstructions into lists of machine instructions, and provide a proof that this process does not change our program's semantics. |
---|
249 | Finally, we assemble all machine code instructions into machine code---lists of bytes---and prove once more that this process does not have an adverse effect on a program's semantics. |
---|
250 | By composition, we then have that the whole assembly process is semantics preserving. |
---|
251 | |
---|
252 | This is a tempting approach to the proof, but ultimately the wrong approach. |
---|
253 | In particular, it is important that we track how the program counter indexing into the assembly program, and the machine's program counter evolve, so that we can relate them. |
---|
254 | Expanding pseudoinstructions requires that the machine's program counter be incremented by $n$ steps, for $1 \leq n$, for every increment of the assembly program's program counter. |
---|
255 | Keeping track of the correspondence between the two program counters quickly becomes unfeasible using a compositional approach, and hence the proof must be monolithic. |
---|
256 | |
---|
257 | % ---------------------------------------------------------------------------- % |
---|
258 | % SECTION % |
---|
259 | % ---------------------------------------------------------------------------- % |
---|
260 | \subsection{Policies} |
---|
261 | \label{subsect.policies} |
---|
262 | |
---|
263 | Policies exist to dictate how conditional and unconditional jumps at the assembly level should be expanded into machine code instructions. |
---|
264 | Using policies, we are able to completely decouple the decision over how jumps are expanded with the act of expansion, simplifying our proofs. |
---|
265 | As 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: |
---|
266 | \begin{lstlisting} |
---|
267 | inductive jump_length: Type[0] := |
---|
268 | | short_jump: jump_length |
---|
269 | | medium_jump: jump_length |
---|
270 | | long_jump: jump_length. |
---|
271 | \end{lstlisting} |
---|
272 | A \texttt{jump\_expansion\_policy} is a map from \texttt{Word}s to \texttt{jump\_length}s, implemented as a trie. |
---|
273 | Intuitively, a policy maps positions in a program (indexed using program counters implemented as \texttt{Word}s) to a particular variety of jump. |
---|
274 | \begin{lstlisting} |
---|
275 | definition jump_expansion_policy := BitVectorTrie jump_length 16. |
---|
276 | \end{lstlisting} |
---|
277 | Next, we require a series of `sigma' functions. |
---|
278 | These 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. |
---|
279 | At the heart of this process is \texttt{sigma0} which traverses an assembly program building maps from program counter to program counter. |
---|
280 | This function fails if and only if an internal call to \texttt{assembly\_1\_pseudoinstruction} fails: |
---|
281 | \begin{lstlisting} |
---|
282 | definition sigma0: pseudo_assembly_program |
---|
283 | $\rightarrow$ option (nat $\times$ (nat $\times$ (BitVectorTrie Word 16))) := $\ldots$ |
---|
284 | \end{lstlisting} |
---|
285 | We eventually lift this to functions from program counters to program counters: |
---|
286 | \begin{lstlisting} |
---|
287 | definition sigma_safe: |
---|
288 | pseudo_assembly_program $\rightarrow$ option (Word $\rightarrow$ Word) := $\ldots$ |
---|
289 | \end{lstlisting} |
---|
290 | Now, it's possible to define what a `good policy' is i.e. one that does not cause \texttt{sigma\_safe} to fail. |
---|
291 | As mentioned, \texttt{sigma\_safe} can only fail if an assembly program fails to be assembled: |
---|
292 | \begin{lstlisting} |
---|
293 | definition policy_ok := $\lambda$p. sigma_safe p $\neq$ None $\ldots$. |
---|
294 | \end{lstlisting} |
---|
295 | Finally, we obtain \texttt{sigma}, a map from program counters to program counters, which is guranteed not to fail as we internally provide a that |
---|
296 | \begin{lstlisting} |
---|
297 | definition sigma: pseudo_assembly_program $\rightarrow$ Word $\rightarrow$ Word := $\ldots$ |
---|
298 | \end{lstlisting} |
---|
299 | |
---|
300 | % ---------------------------------------------------------------------------- % |
---|
301 | % SECTION % |
---|
302 | % ---------------------------------------------------------------------------- % |
---|
303 | \subsection{Total correctness of the assembler} |
---|
304 | \label{subsect.total.correctness.of.the.assembler} |
---|
305 | |
---|
306 | Using our policies, we now work toward proving the total correctness of the assembler. |
---|
307 | By total correctness, we mean that the assembly process does not change the semantics of an assembly program. |
---|
308 | Naturally, this necessitates keeping some sort of correspondence between program counters at the assembly level, and program counters at the machine code level. |
---|
309 | For this, we use the \texttt{sigma} machinery defined at the end of Subsection~\ref{subsect.policies}. |
---|
310 | |
---|
311 | We expand pseudoinstructions using the function \texttt{expand\_pseudo\_instruction}. |
---|
312 | This function accepts a `policy decision'---an element of type \texttt{jump\_length}---that is used when expanding a \texttt{Call}, \texttt{Jmp} or conditional jump to a label into the correct machine instruction. |
---|
313 | This \texttt{policy\_decision} is asssumed to originate from a policy as defined in Subsection~\ref{subsect.policies}. |
---|
314 | \begin{lstlisting} |
---|
315 | definition expand_pseudo_instruction: |
---|
316 | ∀lookup_labels, lookup_datalabels, pc, policy_decision. |
---|
317 | pseudo_instruction $\rightarrow$ option list instruction := $\ldots$ |
---|
318 | \end{lstlisting} |
---|
319 | Under the assumption that a correct policy exists, \texttt{expand\_pseudo\_instruction} should never fail, and therefore the option type may be dispensed with. |
---|
320 | This is because the only failure conditions for \texttt{expand\_pseudo\_instruction} result from trying to expand a pseudoinstruction into an `impossible' combination of machine code instructions. |
---|
321 | For instance, if the policy decision dictates that we should expand a \texttt{Call} pseudoinstruction into a `short jump', then we fail, as the MCS-51's instruction set only features instructions \texttt{ACALL} and \texttt{LCALL}. |
---|
322 | |
---|
323 | % dpm todo |
---|
324 | \begin{lstlisting} |
---|
325 | axiom assembly_ok: ∀program,assembled,costs,labels. |
---|
326 | Some $\ldots$ $\langle$labels, costs$\rangle$ = build_maps program $\rightarrow$ |
---|
327 | Some $\ldots$ $\langle$assembled, costs$\rangle$ = assembly program $\rightarrow$ |
---|
328 | let code_memory := load_code_memory assembled in |
---|
329 | let preamble := $\pi_1$ program in |
---|
330 | let datalabels := construct_datalabels preamble in |
---|
331 | let lk_labels := |
---|
332 | $\lambda$x. sigma program (address_of_word_labels_code_mem ($\pi_2$ program) x) in |
---|
333 | let lk_dlabels := $\lambda$x. lookup ? ? x datalabels (zero ?) in |
---|
334 | ∀ppc,len,assembledi. |
---|
335 | let $\langle$pi, newppc$\rangle$ := fetch_pseudo_instruction ($\pi_2$ program) ppc in |
---|
336 | let assembly' := assembly_1_pseudoinstruction program ppc |
---|
337 | (sigma program ppc) lk_labels lk_dlabels pi in |
---|
338 | let newpc := (sigma program ppc) + len in |
---|
339 | let echeck := |
---|
340 | encoding_check code_memory (sigma program ppc) slen assembledi in |
---|
341 | Some $\ldots$ $\langle$len, assembledi$\rangle$ = assembly' $\rightarrow$ |
---|
342 | echeck $\wedge$ sigma program newppc = newpc. |
---|
343 | \end{lstlisting} |
---|
344 | |
---|
345 | % dpm todo |
---|
346 | \begin{lstlisting} |
---|
347 | theorem fetch_assembly: $\forall$pc, i, cmem, assembled. |
---|
348 | assembled = assembly1 i $\rightarrow$ |
---|
349 | let len := length $\ldots$ assembled in |
---|
350 | encoding_check cmem pc (pc + len) assembled $\rightarrow$ |
---|
351 | let fetched := fetch code_memory (bitvector_of_nat $\ldots$ pc) in |
---|
352 | let $\langle$instr_pc, ticks$\rangle$ := fetched in |
---|
353 | let $\langle$instr, pc'$\rangle$ := instr_pc in |
---|
354 | (eq_instruction instr i $\wedge$ |
---|
355 | eqb ticks (ticks_of_instruction instr) $\wedge$ |
---|
356 | eq_bv $\ldots$ pc' (pc + len)) = true. |
---|
357 | \end{lstlisting} |
---|
358 | |
---|
359 | Lemma \texttt{fetch\_assembly\_pseudo} establishes a basic relationship between \texttt{expand\_pseudo\_instruction} and \texttt{assembly\_1\_pseudoinstruction}: |
---|
360 | \begin{lstlisting} |
---|
361 | lemma fetch_assembly_pseudo: $\forall$program, ppc, lk_labels, lk_dlabels. |
---|
362 | $\forall$pi, code_memory, len, assembled, instructions, pc. |
---|
363 | let jexp := jump_expansion ppc program in |
---|
364 | let exp := |
---|
365 | expand_pseudo_instruction lk_labels lk_dlabels pc jexp pi |
---|
366 | let ass := |
---|
367 | assembly_1_pseudoinstruction program ppc pc lk_labels lk_dlabels pi in |
---|
368 | Some ? instructions = exp $\rightarrow$ |
---|
369 | Some $\ldots$ $\langle$len, assembled$\rangle$ = ass $\rightarrow$ |
---|
370 | encoding_check code_memory pc (pc + len) assembled $\rightarrow$ |
---|
371 | fetch_many code_memory (pc + len) pc instructions. |
---|
372 | \end{lstlisting} |
---|
373 | Here, \texttt{len} is the number of machine code instructions the pseudoinstruction at hand has been expanded into, \texttt{encoding\_check} is a recursive function that checks for any possible corruption of the code memory, resulting from expanding the pseudoinstruction. |
---|
374 | We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{jump\_expansion} and \texttt{expand\_pseudo\_instruction}. |
---|
375 | The function \texttt{fetch\_many} fetches multiple machine code instructions from code memory and performs some routine checks. |
---|
376 | |
---|
377 | Intuitively, Lemma \texttt{fetch\_assembly\_pseudo} can be read as follows. |
---|
378 | Suppose our policy \texttt{jump\_expansion} dictates that the pseudoinstruction indexed by the pseudo program counter \texttt{ppc} in assembly program \texttt{program} gives us the policy decision \texttt{jexp}. |
---|
379 | Further, suppose we expand the pseudoinstruction at \texttt{ppc} with the policy decision \texttt{jexp}, obtaining an (optional) list of machine code instructions \texttt{exp}. |
---|
380 | Suppose we also assemble the pseudoinstruction at \texttt{ppc} to obtain \texttt{ass}, a list of bytes. |
---|
381 | Then, under the assumption that neither the expansion of the pseudoinstruction to obtain \texttt{exp}, nor the assembly of the pseudoinstruction to obtain \texttt{ass}, failed, 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. |
---|
382 | |
---|
383 | At first sight, Lemma \texttt{fetch\_assembly\_pseudo2} appears to nearly establish the correctness of the assembler: |
---|
384 | \begin{lstlisting} |
---|
385 | lemma fetch_assembly_pseudo2: $\forall$program, assembled, costs, labels. |
---|
386 | Some $\ldots$ $\langle$labels, costs$\rangle$ = build_maps program $\rightarrow$ |
---|
387 | Some $\ldots$ $\langle$assembled, costs$\rangle$ = assembly program $\rightarrow$ $\forall$ppc. |
---|
388 | let code_memory := load_code_memory assembled in |
---|
389 | let preamble := $\pi_1$ program in |
---|
390 | let data_labels := construct_datalabels preamble in |
---|
391 | let lk_labels := |
---|
392 | λx. sigma program (address_of_word_labels_code_mem ($\pi_2$ program) x) in |
---|
393 | let lk_dlabels := λx. lookup ? ? x data_labels (zero ?) in |
---|
394 | let expansion := jump_expansion ppc program in |
---|
395 | let $\langle$pi, newppc$\rangle$ := fetch_pseudo_instruction ($\pi_2$ program) ppc in |
---|
396 | let ppc' := sigma program ppc in |
---|
397 | let newppc' := sigma program newppc in |
---|
398 | let instructions' := |
---|
399 | expand_pseudo_instruction lk_labels lk_dlabels ppc' expansion pi in |
---|
400 | let fetched := $\lambda$instr. fetch_many code_memory newppc' ppc' instr in |
---|
401 | $\exists$instrs. Some ? instrs = instructions' $\wedge$ fetched instrs. |
---|
402 | \end{lstlisting} |
---|
403 | Intuitively, we may read \texttt{fetch\_assembly\_pseudo2} as follows. |
---|
404 | Suppose we are able to successfully assemble an assembly program using \texttt{assembly} and produce a code memory, \texttt{code\_memory}. |
---|
405 | Then there exists some list of machine instructions equal to the expansion of a pseudoinstruction and the number of machine instructions that need to be fetched is equal to the number of machine instructions that the pseudoinstruction was expanded into. |
---|
406 | |
---|
407 | However, this property is \emph{not} strong enough to establish that the semantics of an assembly program has been preserved by the assembly process. |
---|
408 | In particular, \texttt{fetch\_assembly\_pseudo2} says nothing about how memory addresses evolve during assembly. |
---|
409 | Memory addresses in one memory space may be mapped to memory addresses in a completely different memory space during assembly. |
---|
410 | To handle this problem, we need some more machinery. |
---|
411 | |
---|
412 | We use an \texttt{internal\_pseudo\_address\_map} for this purpose. |
---|
413 | An \texttt{internal\_pseudo\_address\_map} associates positions in the memory of a \texttt{PseudoStatus} with a physical memory address: |
---|
414 | \begin{lstlisting} |
---|
415 | definition internal_pseudo_address_map := list (BitVector 8). |
---|
416 | \end{lstlisting} |
---|
417 | We use \texttt{internal\_pseudo\_address\_map}s to convert the lower internal RAM of a \texttt{PseudoStatus} into the lower internal RAM of a \texttt{Status}. |
---|
418 | The actual conversion process is performed by \texttt{low\_internal\_ram\_of\_pseudo\_low\_internal\_ram}:\footnote{An associated set of axioms describe how \texttt{low\_internal\_ram\_of\_pseudo\_low\_internal\_ram} behaves. This is a form of parametricity. We don't care about the particulars of the conversion functions, as long as they behave in accordance with our axioms.} |
---|
419 | |
---|
420 | \begin{lstlisting} |
---|
421 | axiom low_internal_ram_of_pseudo_low_internal_ram: |
---|
422 | internal_pseudo_address_map $\rightarrow$ BitVectorTrie Byte 7 $\rightarrow$ BitVectorTrie Byte 7. |
---|
423 | \end{lstlisting} |
---|
424 | A similar axiom exists for high internal RAM. |
---|
425 | |
---|
426 | Notice, the MCS-51's internal RAM is addressed with a 7-bit `byte'. |
---|
427 | % dpm: ugly English, fix |
---|
428 | The whole of the internal RAM space is addressed with bytes: the first bit is used to distinguish between the programmer addressing low and high internal memory. |
---|
429 | |
---|
430 | Next, we are able to translate \texttt{PseudoStatus} records into \texttt{Status} records using \texttt{status\_of\_pseudo\_status}. |
---|
431 | Translating a \texttt{PseudoStatus}'s code memory requires we expand pseudoinstructions and then assemble to obtain a trie of bytes. |
---|
432 | This can fail, as mentioned, in a limited number of situations, related to improper use of labels in an assembly program. |
---|
433 | However, it is possible to `tighten' the type of \texttt{status\_of\_pseudo\_status}, removing the option type, by using the fact that if any `good policy' exists, assembly will never fail. |
---|
434 | \begin{lstlisting} |
---|
435 | definition status_of_pseudo_status: |
---|
436 | internal_pseudo_address_map → PseudoStatus → option Status |
---|
437 | \end{lstlisting} |
---|
438 | After fetching an assembly instruction we must update any \texttt{internal\_pseudo\hyp{}\_address\_map}s that may be laying around. |
---|
439 | This is done with the following function: |
---|
440 | \begin{lstlisting} |
---|
441 | definition next_internal_pseudo_address_map: internal_pseudo_address_map |
---|
442 | $\rightarrow$ PseudoStatus $\rightarrow$ option internal_pseudo_address_map |
---|
443 | \end{lstlisting} |
---|
444 | Finally, we are able to state and prove our main theorem. |
---|
445 | This relates the execution of a single assembly instruction and the execution of (possibly) many machine code instructions. |
---|
446 | That is, the assembly process preserves the semantics of an assembly program, as it is translated into machine code: |
---|
447 | \begin{lstlisting} |
---|
448 | theorem main_thm: |
---|
449 | ∀M,M',ps,s,s''. |
---|
450 | next_internal_pseudo_address_map M ps = Some $\ldots$ M' $\rightarrow$ |
---|
451 | status_of_pseudo_status M ps = Some $\ldots$ s $\rightarrow$ |
---|
452 | status_of_pseudo_status M' |
---|
453 | (execute_1_pseudo_instruction |
---|
454 | (ticks_of (code_memory $\ldots$ ps)) ps) = Some $\ldots$ s'' $\rightarrow$ |
---|
455 | $\exists$n. execute n s = s''. |
---|
456 | \end{lstlisting} |
---|
457 | The statement can be given an intuitive reading as follows. |
---|
458 | Suppose our \texttt{PseudoStatus}, \texttt{ps}, can be successfully converted into a \texttt{Status}, \texttt{s}. |
---|
459 | Suppose further that, after executing a single assembly instruction and converting the resulting \texttt{PseudoStatus} into a \texttt{Status}, we obtain \texttt{s''}, being careful to track the number of ticks executed. |
---|
460 | Then, there exists some number \texttt{n}, so that executing \texttt{n} machine code instructions in \texttt{Status} \texttt{s} gives us \texttt{Status} \texttt{s''}. |
---|
461 | Theorem \texttt{main\_thm} establishes the correctness of the assembly process. |
---|
462 | |
---|
463 | % ---------------------------------------------------------------------------- % |
---|
464 | % SECTION % |
---|
465 | % ---------------------------------------------------------------------------- % |
---|
466 | \section{Conclusions} |
---|
467 | \label{sect.conclusions} |
---|
468 | |
---|
469 | We have proved the total correctness of an assembler for MCS-51 assembly language. |
---|
470 | In 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. |
---|
471 | Expanding these pseudoinstructions into machine code instructions is not trivial, and the proof that the assembly process is `correct', in that the semantics of an assembly program are not changed is complex. |
---|
472 | |
---|
473 | The 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. |
---|
474 | The 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. |
---|
475 | |
---|
476 | Aside from their application in verified compiler projects such as CerCo, verified assemblers such as ours could also be applied to the verification of operating system kernels. |
---|
477 | Of particular note is the verified seL4 kernel~\cite{klein:sel4:2009,klein:sel4:2010}. |
---|
478 | This verification explicitly assumes the existence of, amongst other things, a trustworthy assembler and compiler. |
---|
479 | |
---|
480 | \paragraph{Use of dependent types and Russell} |
---|
481 | Our formalisation makes sparing use of dependent types. |
---|
482 | In certain datastructures, such as tries and vectors, they are used to guarantee invariants. |
---|
483 | However, we have currently shyed away from making extensive use of dependent types and inductive predicates in the proof of correctness for the assembler itself. |
---|
484 | This is because complex dependent types and inductive predicates tend not to co\"operate particularly well with tactics such as inversion. |
---|
485 | |
---|
486 | However, there are certain cases where the use of dependent types is unavoidable. |
---|
487 | For instance, when proving that the \texttt{build\_maps} function is correct, a function that collates the cost and data labels of an assembly program into map datastructures. |
---|
488 | In cases such as these we make use of Matita's implementation of Russell~\cite{sozeau:subset:2006}. |
---|
489 | In Matita, Russell may be implemented with two coercions and some notational sugaring. |
---|
490 | |
---|
491 | \subsection{Related work} |
---|
492 | \label{subsect.related.work} |
---|
493 | |
---|
494 | % piton |
---|
495 | We are not the first to consider the total correctness of an assembler for a non-trivial assembly language. |
---|
496 | Perhaps the most impressive piece of work in this domain is the Piton stack~\cite{moore:piton:1996,moore:grand:2005}. |
---|
497 | This 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}. |
---|
498 | %dpm more: weirich paper? |
---|
499 | |
---|
500 | % jinja |
---|
501 | Klein and Nipkow consider a Java-like programming language, Jinja~\cite{klein:machine:2006,klein:machine:2010}. |
---|
502 | They 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. |
---|
503 | |
---|
504 | Finally, mention should be made of CompCert~\cite{compcert:2011,blazy:formal:2006,leroy:formal:2009,leroy:formally:2009}, another verified compiler project related to CerCo. |
---|
505 | As previously mentioned, CompCert considers only extensional correctness of the compiler, and not intensional correctness, which CerCo focusses on. |
---|
506 | However, CerCo also extends CompCert in other ways. |
---|
507 | Namely, the CompCert verified compilation chain terminates at the PowerPC or ARM assembly level, and takes for granted the existence of a trustworthy assembler. |
---|
508 | CerCo chooses to go further, by considering a verified compilation chain all the way down to the machine code level. |
---|
509 | In essence, the work presented in this publication is one part of CerCo's extension over CompCert. |
---|
510 | |
---|
511 | \bibliography{cpp-2011.bib} |
---|
512 | |
---|
513 | \end{document}\renewcommand{\verb}{\lstinline} |
---|
514 | \def\lstlanguagefiles{lst-grafite.tex} |
---|
515 | \lstset{language=Grafite} |
---|