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 present a proof of correctness, in the Matita proof assistant, for an optimising assembler for the MCS-51 8-bit microcontroller. |
---|
49 | This assembler constitutes a major component of the EU's CerCo (`Certified Complexity') project. |
---|
50 | |
---|
51 | The efficient expansion of pseudoinstructions---particularly jumps---into MCS-51 machine instructions is complex. |
---|
52 | We isolate the decision making over how jumps should be expanded from the expansion process itself as much as possible using `policies'. |
---|
53 | This makes the proof of correctness for the assembler significantly more straightforward. |
---|
54 | |
---|
55 | We observe that it is impossible for an optimising assembler to preserve the semantics of every assembly program. |
---|
56 | Assembly language programs can manipulate concrete addresses in arbitrary ways. |
---|
57 | Our proof strategy contains a notion of `good addresses' and only assembly programs that use good addresses have their semantics preserved under assembly. |
---|
58 | Our strategy offers increased flexibility over the traditional approach of keeping addresses in assembly opaque. |
---|
59 | In 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 | |
---|
68 | We consider the formalisation of an assembler for the Intel MCS-51 8-bit microprocessor in the Matita proof assistant~\cite{asperti:user:2007}. |
---|
69 | This 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 | |
---|
71 | The MCS-51 dates from the early 1980s and is commonly called the 8051/8052. |
---|
72 | Despite the microprocessor's age, derivatives are still widely manufactured by a number of semiconductor foundries. |
---|
73 | As a result the processor is widely used, especially in embedded systems development, where well-tested, cheap, predictable microprocessors find their niche. |
---|
74 | |
---|
75 | The 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. |
---|
76 | Yet, 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 becomes a hindrance. |
---|
77 | In particular, the MCS-51 features a relatively minuscule series of memory spaces by modern standards. |
---|
78 | As 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 | |
---|
80 | Branch displacement is not a simple problem to solve and requires the implementation of an optimising assembler. |
---|
81 | 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 all feature in our assembly language. |
---|
82 | We simplify the process by assuming that all assembly programs are pre-linked (i.e. we do not formalise a linker). |
---|
83 | The assembler expands pseudoinstructions into MCS-51 machine code, but this assembly process is not trivial, for numerous reasons. |
---|
84 | For example, our conditional jumps to labels behave differently from their machine code counterparts. |
---|
85 | At the machine code level, all conditional jumps are `short', limiting their range. |
---|
86 | 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. |
---|
87 | |
---|
88 | Yet, the situation is even more complex than having to expand pseudoinstructions correctly. |
---|
89 | 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. |
---|
90 | |
---|
91 | First, the semantics of some functions of the MCS-51, notably I/O, depend on the microprocessor's clock. |
---|
92 | Changing how long a particular program takes to execute can affect the semantics of a program. |
---|
93 | This is undesirable. |
---|
94 | |
---|
95 | Second, CerCo imposes a cost model on C programs or, more specifically, on simple blocks of instructions. |
---|
96 | 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. |
---|
97 | In short, we aim to obtain a very precise costing for a program by embracing the compilation process, not ignoring it. |
---|
98 | This, however, complicates the proof of correctness for the compiler proper. |
---|
99 | In 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. |
---|
100 | This also applies for the translation from assembly language to machine code. |
---|
101 | |
---|
102 | Yet one more question remains: how do we decide whether to expand a jump into an \texttt{SJMP} or an \texttt{LJMP}? |
---|
103 | To understand, again, why this problem is not trivial, consider the following snippet of assembly code: |
---|
104 | {\small{ |
---|
105 | \begin{displaymath} |
---|
106 | \begin{array}{r@{\qquad}r@{\quad}l@{\;\;}l@{\qquad}l} |
---|
107 | \text{1:} & \mathtt{(0x000)} & \texttt{LJMP} & \texttt{0x100} & \text{\texttt{;; Jump forward 256.}} \\ |
---|
108 | \text{2:} & \mathtt{...} & \mathtt{...} & & \\ |
---|
109 | \text{3:} & \mathtt{(0x0FA)} & \texttt{LJMP} & \texttt{0x100} & \text{\texttt{;; Jump forward 256.}} \\ |
---|
110 | \text{4:} & \mathtt{...} & \mathtt{...} & & \\ |
---|
111 | \text{5:} & \mathtt{(0x100)} & \texttt{LJMP} & \texttt{-0x100} & \text{\texttt{;; Jump backward 256.}} \\ |
---|
112 | \end{array} |
---|
113 | \end{displaymath}}} |
---|
114 | We observe that $100_{16} = 256_{10}$, and lies \emph{just} outside the range expressible in an 8-bit byte (0--255). |
---|
115 | |
---|
116 | As 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. |
---|
117 | In particular, if we wish to shrink the \texttt{LJMP} occurring at line 1, then we must shrink the \texttt{LJMP} occurring at line 3. |
---|
118 | However, to shrink the \texttt{LJMP} occurring at line 3 we must also shrink the \texttt{LJMP} occurring at line 5, and \emph{vice versa}. |
---|
119 | |
---|
120 | Further, consider what happens if, instead of appearing at memory address \texttt{0x100}, the instruction at line 5 appeared \emph{just} beyond the size of code memory, and all other memory addresses were shifted accordingly. |
---|
121 | Now, 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. |
---|
122 | That is, the shrinking process is not just related to the optimisation of generated machine code but also the completeness of the assembler itself. |
---|
123 | |
---|
124 | How we went about resolving this problem affected the shape of our proof of correctness for the whole assembler in a rather profound way. |
---|
125 | We 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. |
---|
126 | Using this technique, solutions can fail to exist, and the proof of correctness for the assembler quickly descends into a diabolical quagmire. |
---|
127 | |
---|
128 | 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. |
---|
129 | Assuming the existence of a correct policy, we proved the implementation of the assembler correct. |
---|
130 | Further, we proved that the assembler fails to assemble an assembly program if and only if a correct policy does not exist. |
---|
131 | This 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. |
---|
132 | |
---|
133 | 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, even after shrinking jumps according to the best policy. |
---|
134 | The 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. |
---|
135 | |
---|
136 | The rest of this paper is a detailed description of our proof that is, in part, still a work in progress. |
---|
137 | |
---|
138 | % ---------------------------------------------------------------------------- % |
---|
139 | % SECTION % |
---|
140 | % ---------------------------------------------------------------------------- % |
---|
141 | \subsection{Overview of the paper} |
---|
142 | \label{subsect.overview.of.the.paper} |
---|
143 | In Section~\ref{sect.matita} we provide a brief overview of the Matita proof assistant for the unfamiliar reader. |
---|
144 | In Section~\ref{sect.the.proof} we discuss the design and implementation of the proof proper. |
---|
145 | In Section~\ref{sect.conclusions} we conclude. |
---|
146 | |
---|
147 | % ---------------------------------------------------------------------------- % |
---|
148 | % SECTION % |
---|
149 | % ---------------------------------------------------------------------------- % |
---|
150 | \section{Matita} |
---|
151 | \label{sect.matita} |
---|
152 | |
---|
153 | Matita is a proof assistant based on a variant of the Calculus of (Co)inductive Constructions~\cite{asperti:user:2007}. |
---|
154 | In particular, it features dependent types that we heavily exploit in the formalisation. |
---|
155 | The syntax of the statements and definitions in the paper should be self-explanatory, at least to those exposed to dependent type theory. |
---|
156 | We 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. |
---|
157 | Those that are not inferred are left to the user as proof obligations. |
---|
158 | Pairs are denoted with angular brackets, $\langle-, -\rangle$. |
---|
159 | |
---|
160 | Matita features a liberal system of coercions. |
---|
161 | It 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$. |
---|
162 | The coercion opens a proof obligation that asks the user to prove that $P$ holds for $x$. |
---|
163 | When 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 |
---|
164 | 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$. |
---|
165 | This 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. |
---|
166 | In 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. |
---|
167 | |
---|
168 | % ---------------------------------------------------------------------------- % |
---|
169 | % SECTION % |
---|
170 | % ---------------------------------------------------------------------------- % |
---|
171 | \section{The proof} |
---|
172 | \label{sect.the.proof} |
---|
173 | |
---|
174 | % ---------------------------------------------------------------------------- % |
---|
175 | % SECTION % |
---|
176 | % ---------------------------------------------------------------------------- % |
---|
177 | |
---|
178 | \subsection{Machine code semantics} |
---|
179 | \label{subsect.machine.code.semantics} |
---|
180 | |
---|
181 | Our emulator centres around a \texttt{Status} record, describing the microprocessor's state. |
---|
182 | This record contains fields corresponding to the microprocessor's program counter, registers, and so on. |
---|
183 | At the machine code level, code memory is implemented as a compact trie of bytes, addressed by the program counter. |
---|
184 | We parameterise \texttt{Status} records by this representation as a few technical tasks manipulating statuses are made simpler using this approach, as well as permitting a modicum of abstraction. |
---|
185 | |
---|
186 | We may execute a single step of a machine code program using the \texttt{execute\_1} function, which returns an updated \texttt{Status}: |
---|
187 | \begin{lstlisting} |
---|
188 | definition execute_1: $\forall$cm. Status cm $\rightarrow$ Status cm := $\ldots$ |
---|
189 | \end{lstlisting} |
---|
190 | %The function \texttt{execute} allows one to execute an arbitrary, but fixed (due to Matita's normalisation requirement) number of steps of a program. |
---|
191 | The function \texttt{execute\_1} closely matches the operation of the MCS-51 hardware, as described by a Siemen's manufacturer's data sheet. |
---|
192 | We first fetch, using the program counter, from code memory the first byte of the instruction to be executed, decoding the resulting opcode, fetching more bytes as is necessary. |
---|
193 | Decoded instructions are represented as an inductive type: |
---|
194 | |
---|
195 | \begin{lstlisting} |
---|
196 | inductive preinstruction (A: Type[0]): Type[0] := |
---|
197 | | ADD: [[acc_a]] → [[ registr; direct; indirect; data ]] → preinstruction A |
---|
198 | | INC: [[ acc_a; registr; direct ; indirect ; dptr ]] → preinstruction A |
---|
199 | | JB: [[bit_addr]] → A → preinstruction A |
---|
200 | | ... |
---|
201 | |
---|
202 | inductive instruction: Type[0] ≝ |
---|
203 | | LCALL: [[addr16]] → instruction |
---|
204 | | AJMP: [[addr11]] → instruction |
---|
205 | | RealInstruction: preinstruction [[ relative ]] → instruction. |
---|
206 | \end{lstlisting} |
---|
207 | Here, we use dependent types to provide a precise typing for instructions, specifying in their type the permitted addressing modes that their arguments can belong to. |
---|
208 | The parameterised type $A$ of \texttt{preinstruction} represents the addressing mode for conditional jumps; in \texttt{instruction} we fix this type to be a relative offset in the constructor \texttt{RealInstruction}. |
---|
209 | |
---|
210 | Once decoded, execution proceeds by a case analysis on the decoded instruction, following the operation of the hardware. |
---|
211 | For example: |
---|
212 | |
---|
213 | \begin{lstlisting} |
---|
214 | | DEC addr $\Rightarrow$ |
---|
215 | let s := add_ticks1 s in |
---|
216 | let $\langle$result, flags$\rangle$ := sub_8_with_carry (get_arg_8 $\ldots$ s true addr) |
---|
217 | (bitvector_of_nat 8 1) false in |
---|
218 | set_arg_8 $\ldots$ s addr result |
---|
219 | \end{lstlisting} |
---|
220 | |
---|
221 | Here, \texttt{add\_ticks1} models the incrementing of the internal clock of the microprocessor. |
---|
222 | |
---|
223 | % ---------------------------------------------------------------------------- % |
---|
224 | % SECTION % |
---|
225 | % ---------------------------------------------------------------------------- % |
---|
226 | |
---|
227 | \subsection{Assembly code semantics} |
---|
228 | \label{subsect.assembly.code.semantics} |
---|
229 | |
---|
230 | An assembly program is a list of potentially labelled pseudoinstructions, bundled with a preamble consisting of a list of symbolic names for locations in data memory. |
---|
231 | Pseudoinstructions are implemented as an inductive type: |
---|
232 | \begin{lstlisting} |
---|
233 | inductive pseudo_instruction: Type[0] ≝ |
---|
234 | | Instruction: preinstruction Identifier → pseudo_instruction |
---|
235 | ... |
---|
236 | | Jmp: Identifier → pseudo_instruction |
---|
237 | | Call: Identifier → pseudo_instruction |
---|
238 | | Mov: [[dptr]] → Identifier → pseudo_instruction. |
---|
239 | \end{lstlisting} |
---|
240 | The pseudoinstructions \texttt{Jmp}, \texttt{Call} and \texttt{Mov} are generalisations of machine code unconditional jumps, calls and move instructions respectively, all of whom act on labels, as opposed to concrete memory addresses. |
---|
241 | Similarly, conditional jumps can now only jump to labels, as is implied by the first constructor of the type above. |
---|
242 | All other object code instructions are available at the assembly level, with the exception of those that appeared in the \texttt{instruction} type, such as \texttt{ACALL} and \texttt{LJMP}. |
---|
243 | These are jumps and calls to absolute addresses, which we do not wish to allow at the assembly level. |
---|
244 | |
---|
245 | Execution of pseudoinstructions is a function from \texttt{PseudoStatus} to \texttt{PseudoStatus}. |
---|
246 | Both \texttt{Status} and \texttt{PseudoStatus} are instances of a more general type parameterised over the representation of code memory. |
---|
247 | The more general type will be crucial to share most of the semantics of the |
---|
248 | two languages. |
---|
249 | |
---|
250 | Emulation for pseudoinstructions is handled by \texttt{execute\_1\_pseudo\_instruction}: |
---|
251 | \begin{lstlisting} |
---|
252 | definition execute_1_pseudo_instruction: |
---|
253 | (Word $\rightarrow$ nat $\times$ nat) $\rightarrow$ $\forall$cm. PseudoStatus cm $\rightarrow$ PseudoStatus cm := $\ldots$ |
---|
254 | \end{lstlisting} |
---|
255 | Notice, here, that the emulation function for assembly programs takes an additional argument over \texttt{execute\_1}. |
---|
256 | 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. |
---|
257 | We call this function a \emph{costing}, and note that the costing is induced by the particular strategy we use to expand pseudoinstructions. |
---|
258 | 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. |
---|
259 | |
---|
260 | 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 execution time. |
---|
261 | The \texttt{ticks1} function we already seen used to increment the machine |
---|
262 | clock is determined, for the assembly language, from the costing function. |
---|
263 | It is instead fixed and precomputed for machine code. |
---|
264 | |
---|
265 | Execution proceeds by first fetching from pseudo-code memory using the program counter---treated as an index into the pseudoinstruction list. |
---|
266 | No decoding is required. |
---|
267 | We then proceed by case analysis over the pseudoinstruction, reusing the code for object code for all instructions present in the MCS-51's instruction set. |
---|
268 | For all newly introduced pseudoinstructions, we simply translate labels to concrete addresses before behaving as a `real' instruction. |
---|
269 | |
---|
270 | In contrast to other approaches, we do not perform any kind of symbolic execution, wherein data is the disjoint union of bytes and addresses, with addresses kept opaque and immutable. |
---|
271 | Labels are immediately translated to concrete addresses, and registers and memory locations only ever contain bytes, never labels. |
---|
272 | As a consequence, we allow the programmer to mangle, change and generally adjust addresses as they want, under the proviso that the translation process may not be able to preserve the semantics of programs that do this. |
---|
273 | This will be further discussed in Subsection~\ref{subsect.total.correctness.for.well.behaved.assembly.programs}. |
---|
274 | |
---|
275 | % ---------------------------------------------------------------------------- % |
---|
276 | % SECTION % |
---|
277 | % ---------------------------------------------------------------------------- % |
---|
278 | |
---|
279 | \subsection{The assembler} |
---|
280 | \label{subsect.the.assembler} |
---|
281 | |
---|
282 | Conceptually the assembler works in two passes. |
---|
283 | The first pass expands pseudoinstructions into a list of machine code instructions using the function \texttt{expand\_pseudo\_instruction}. |
---|
284 | The second pass encodes as a list of bytes the expanded instruction list by mapping the function \texttt{assembly1} across the list, and then flattening. |
---|
285 | \begin{displaymath} |
---|
286 | [\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]} |
---|
287 | \end{displaymath} |
---|
288 | The most complex of the two passes is the first, which expands pseudoinstructions and must perform the task of branch displacement~\cite{holmes:branch:2006}. |
---|
289 | |
---|
290 | The branch displacement problems consists of the problem of expanding pseudojumps into their concrete counterparts, preferably as efficiently as possible. |
---|
291 | For instance, 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}. |
---|
292 | Each 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. |
---|
293 | 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 that will suffice should be selected. |
---|
294 | This is a well known problem to assembler writers who target RISC architectures. |
---|
295 | |
---|
296 | Similarly, a conditional pseudojump must be translated potentially into a configuration of machine code instructions, depending on the distance to the jump's target. |
---|
297 | For example, 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'): |
---|
298 | {\small{ |
---|
299 | \begin{displaymath} |
---|
300 | \begin{array}{r@{\quad}l@{\;\;}l@{\qquad}c@{\qquad}l@{\;\;}l} |
---|
301 | & \mathtt{JZ} & \mathtt{label} & & \mathtt{JZ} & \text{size of \texttt{SJMP} instruction} \\ |
---|
302 | & \ldots & & \text{translates to} & \mathtt{SJMP} & \text{size of \texttt{LJMP} instruction} \\ |
---|
303 | \mathtt{label:} & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} & \Longrightarrow & \mathtt{LJMP} & \text{address of \textit{label}} \\ |
---|
304 | & & & & \ldots & \\ |
---|
305 | & & & & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} |
---|
306 | \end{array} |
---|
307 | \end{displaymath}}} |
---|
308 | Here, if \texttt{JZ} fails, we fall through to the \texttt{SJMP} which jumps over the \texttt{LJMP}. |
---|
309 | Naturally, 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. |
---|
310 | |
---|
311 | In order to implement branch displacement it is impossible to really make the \texttt{expand\_pseudo\_instruction} function completely independent of the encoding function. |
---|
312 | This is due to branch displacement requiring the distance in bytes of the target of the jump. |
---|
313 | Moreover the standard solutions for solving the branch displacement problem find their solutions iteratively, by either starting from a solution where all jumps are long, and shrinking them when possible, or starting from a state where all jumps are short and increasing their length as needed. |
---|
314 | Proving the correctness of such algorithms is already quite involved and the correctness of the assembler as a whole does not depend on the `quality' of the solution found to a branch displacement problem. |
---|
315 | For this reason, we try to isolate the computation of a branch displacement problem from the proof of correctness for the assembler by parameterising our \texttt{expand\_pseudo\_instruction} by a `policy'. |
---|
316 | |
---|
317 | \begin{lstlisting} |
---|
318 | definition expand_pseudo_instruction: |
---|
319 | $\forall$lookup_labels: Identifier $\rightarrow$ Word. |
---|
320 | $\forall$sigma: Word $\rightarrow$ Word. |
---|
321 | $\forall$policy: Word $\rightarrow$ bool. |
---|
322 | $\forall$ppc: Word. |
---|
323 | $\forall$lookup_datalabels: Identifier $\rightarrow$ Word. |
---|
324 | $\forall$pi: pseudo_instruction. |
---|
325 | list instruction := ... |
---|
326 | \end{lstlisting} |
---|
327 | Here, the functions \texttt{lookup\_labels} and \texttt{lookup\_datalabels} are the functions that map labels and datalabels to program counters respectively, both of them used in the semantics of assembly. |
---|
328 | The input \texttt{pi} is the pseudoinstruction to be expanded and is found at address \texttt{ppc} in the assembly program. |
---|
329 | The policy is defined using the two functions \texttt{sigma} and \texttt{policy}, of which \texttt{sigma} is the most interesting. |
---|
330 | The function $\sigma$ maps pseudo program counters to program counters: the encoding of the expansion of the pseudoinstruction found at address \texttt{a} in the assembly code should be placed into code memory at address \texttt{sigma(a)}. |
---|
331 | Of course this is possible only if the policy is correct, which means that the encoding of consecutive assembly instructions must be consecutive in code memory. |
---|
332 | \begin{displaymath} |
---|
333 | \texttt{sigma}(\texttt{ppc} + 1) = \texttt{pc} + \texttt{current\_instruction\_size} |
---|
334 | \end{displaymath} |
---|
335 | Here, \texttt{current\_instruction\_size} is the size in bytes of the encoding of the expanded pseudoinstruction found at \texttt{ppc}. |
---|
336 | Note that the entanglement we hinted at is only partially solved in this |
---|
337 | way: the assembler code can ignore the implementative details of the |
---|
338 | algorithm that finds a policy; however, the algorithm that finds a policy |
---|
339 | must know the exact behaviour of the assembly because it needs to predict |
---|
340 | the way the assembly will expand and encode pseudoinstructions, once feeded |
---|
341 | with a policy. The companion paper~\cite{jaap} certifies an algorithm that |
---|
342 | finds branch displacement policies for the assembler described in this paper. |
---|
343 | |
---|
344 | The \texttt{expand\_pseudo\_instruction} function uses the \texttt{sigma} map to determine the size of jump required when expanding pseudojumps, computing the jump size by examining the size of the differences between program counters. |
---|
345 | For instance, if at address $ppc$ in the assembly program we found |
---|
346 | $Jmp~l$ such that \texttt{lookup\_labels~l} $= a$, if the |
---|
347 | offset $ d = \sigma(a) - \sigma(ppc+1)$ is such that $d < 128$ then $Jmp~l$ is |
---|
348 | normally translated to the best local solution, the short jump $SJMP~d$. |
---|
349 | A global best solution to the branch displacement problem, however, is not |
---|
350 | always made of locally best solutions. Therefore, in some circumstances, |
---|
351 | it is necessary to force the assembler to expand jumps into larger ones. |
---|
352 | This is achieved by the \texttt{policy} function: if \texttt{policy~ppc}$= true$ |
---|
353 | then a $Jmp~l$ at address $ppc$ is always translated to a long jump. |
---|
354 | The mechanism is essentially identical for calls. |
---|
355 | |
---|
356 | % ---------------------------------------------------------------------------- % |
---|
357 | % SECTION % |
---|
358 | % ---------------------------------------------------------------------------- % |
---|
359 | \subsection{Correctness of the assembler with respect to fetching} |
---|
360 | \label{subsect.total.correctness.of.the.assembler} |
---|
361 | Using our policies, we now work toward proving the total correctness of the assembler. |
---|
362 | By `total correctness', we mean that the assembly process never fails when provided with a correct policy and that the process does not change the semantics of a certain class of well behaved assembly programs. |
---|
363 | |
---|
364 | The aim of this section is to prove the following informal statement: |
---|
365 | when we fetch an assembly pseudoinstruction $I$ at address $ppc$, then |
---|
366 | we can fetch the expanded pseudoinstruction(s) $[J^1;\ldots;J^n] = fetch\_pseudo\_instruction \ldots I~ppc$ from |
---|
367 | $\sigma(ppc)$ in the code memory obtained loading the assembled object code. |
---|
368 | |
---|
369 | This constitutes the first major step in the proof of correctness of the |
---|
370 | assembler, the next one being the simulation of $I$ by $[J^1;\ldots;J^n]$ |
---|
371 | (see Section~\ref{???}). |
---|
372 | |
---|
373 | We can express the following lemma, expressing the correctness of the assembly function (slightly simplified): |
---|
374 | \begin{lstlisting} |
---|
375 | lemma assembly_ok: |
---|
376 | $\forall$program: pseudo_assembly_program. |
---|
377 | $\forall$sigma: Word $\rightarrow$ Word. |
---|
378 | $\forall$policy: Word $\rightarrow$ bool. |
---|
379 | $\forall$sigma_policy_witness. |
---|
380 | $\forall$assembled. |
---|
381 | $\forall$costs': BitVectorTrie costlabel 16. |
---|
382 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
383 | let $\langle$labels, costs$\rangle$ := create_label_cost_map instr_list in |
---|
384 | $\langle$assembled,costs'$\rangle$ = assembly program sigma policy $\rightarrow$ |
---|
385 | let cmem := load_code_memory assembled in |
---|
386 | $\forall$ppc. |
---|
387 | let $\langle$pi, newppc$\rangle$ := fetch_pseudo_instruction instr_list ppc in |
---|
388 | let $\langle$len,assembled$\rangle$ := assembly_1_pseudoinstruction $\ldots$ ppc $\ldots$ pi in |
---|
389 | let pc := sigma ppc in |
---|
390 | let pc_plus_len := add $\ldots$ pc (bitvector_of_nat $\ldots$ len) in |
---|
391 | encoding_check cmem pc pc_plus_len assembled $\wedge$ |
---|
392 | sigma newppc = add $\ldots$ pc (bitvector_of_nat $\ldots$ len). |
---|
393 | \end{lstlisting} |
---|
394 | Here, \texttt{encoding\_check} is a recursive function that checks that assembled machine code is correctly stored in code memory. |
---|
395 | Suppose also we assemble our program \texttt{p} in accordance with a policy \texttt{sigma} to obtain \texttt{assembled}, loading the assembled program into code memory \texttt{cmem}. |
---|
396 | Then, 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. |
---|
397 | |
---|
398 | Lemma \texttt{fetch\_assembly} establishes that the \texttt{fetch} and \texttt{assembly1} functions interact correctly. |
---|
399 | The \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: |
---|
400 | \begin{lstlisting} |
---|
401 | lemma fetch_assembly: |
---|
402 | $\forall$pc: Word. |
---|
403 | $\forall$i: instruction. |
---|
404 | $\forall$code_memory: BitVectorTrie Byte 16. |
---|
405 | $\forall$assembled: list Byte. |
---|
406 | assembled = assembly1 i $\rightarrow$ |
---|
407 | let len := length $\ldots$ assembled in |
---|
408 | let pc_plus_len := add $\ldots$ pc (bitvector_of_nat $\ldots$ len) in |
---|
409 | encoding_check code_memory pc pc_plus_len assembled $\rightarrow$ |
---|
410 | let $\langle$instr, pc', ticks$\rangle$ := fetch code_memory pc in |
---|
411 | (eq_instruction instr i $\wedge$ |
---|
412 | eqb ticks (ticks_of_instruction instr) $\wedge$ |
---|
413 | eq_bv $\ldots$ pc' pc_plus_len) = true. |
---|
414 | \end{lstlisting} |
---|
415 | In particular, we read \texttt{fetch\_assembly} as follows. |
---|
416 | Given an instruction, \texttt{i}, we first assemble the instruction to obtain \texttt{assembled}, checking that the assembled instruction was stored in code memory correctly. |
---|
417 | Fetching from code memory, we obtain a tuple consisting of the instruction, new program counter, and the number of ticks this instruction will take to execute. |
---|
418 | 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. |
---|
419 | Or, in plainer words, assembling and then immediately fetching again gets you back to where you started. |
---|
420 | |
---|
421 | Lemma \texttt{fetch\_assembly\_pseudo} (slightly simplified, here) is obtained by composition of \texttt{expand\_pseudo\_instruction} and \texttt{assembly\_1\_pseudoinstruction}: |
---|
422 | \begin{lstlisting} |
---|
423 | lemma fetch_assembly_pseudo: |
---|
424 | $\forall$program: pseudo_assembly_program. |
---|
425 | $\forall$sigma: Word $\rightarrow$ Word. |
---|
426 | $\forall$policy: Word $\rightarrow$ bool. |
---|
427 | $\forall$ppc. |
---|
428 | $\forall$code_memory. |
---|
429 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
430 | let pi := $\pi_1$ (fetch_pseudo_instruction instr_list ppc) in |
---|
431 | let pc := sigma ppc in |
---|
432 | let instrs := expand_pseudo_instruction $\ldots$ sigma policy ppc $\ldots$ pi in |
---|
433 | let $\langle$l, a$\rangle$ := assembly_1_pseudoinstruction $\ldots$ sigma policy ppc $\ldots$ pi in |
---|
434 | let pc_plus_len := add $\ldots$ pc (bitvector_of_nat $\ldots$ l) in |
---|
435 | encoding_check code_memory pc pc_plus_len a $\rightarrow$ |
---|
436 | fetch_many code_memory pc_plus_len pc instructions. |
---|
437 | \end{lstlisting} |
---|
438 | Here, \texttt{l} is the number of machine code instructions the pseudoinstruction at hand has been expanded into. |
---|
439 | We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{jump\_expansion} and \texttt{expand\_pseudo\_instruction}. |
---|
440 | The function \texttt{fetch\_many} fetches multiple machine code instructions from code memory and performs some routine checks. |
---|
441 | |
---|
442 | Intuitively, Lemma \texttt{fetch\_assembly\_pseudo} can be read as follows. |
---|
443 | Suppose we expand the pseudoinstruction at \texttt{ppc} with the policy decision \texttt{sigma}, obtaining the list of machine code instructions \texttt{instrs}. |
---|
444 | Suppose we also assemble the pseudoinstruction at \texttt{ppc} to obtain \texttt{a}, a list of bytes. |
---|
445 | Then, 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. |
---|
446 | |
---|
447 | The 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. |
---|
448 | Again, we slightly simplify: |
---|
449 | \begin{lstlisting} |
---|
450 | lemma fetch_assembly_pseudo2: |
---|
451 | $\forall$program. |
---|
452 | $\forall$sigma. |
---|
453 | $\forall$policy. |
---|
454 | $\forall$sigma_policy_specification_witness. |
---|
455 | $\forall$ppc. |
---|
456 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
457 | let $\langle$labels, costs$\rangle$ := create_label_cost_map instr_list in |
---|
458 | let $\langle$assembled, costs'$\rangle$ := $\pi_1$ $\ldots$ (assembly program sigma policy) in |
---|
459 | let cmem := load_code_memory assembled in |
---|
460 | let $\langle$pi, newppc$\rangle$ := fetch_pseudo_instruction instr_list ppc in |
---|
461 | let instructions := expand_pseudo_instruction $\ldots$ sigma ppc $\ldots$ pi in |
---|
462 | fetch_many cmem (sigma newppc) (sigma ppc) instructions. |
---|
463 | \end{lstlisting} |
---|
464 | |
---|
465 | Here we use $\pi_1 \ldots$ to eject out the existential witness from the Russell-typed function \texttt{assembly}. |
---|
466 | |
---|
467 | We read \texttt{fetch\_assembly\_pseudo2} as follows. |
---|
468 | Suppose we are able to successfully assemble an assembly program using \texttt{assembly} and produce a code memory, \texttt{cmem}. |
---|
469 | Then, fetching a pseudoinstruction from the pseudo code memory at address \texttt{ppc} corresponds to fetching a sequence of instructions from the real code memory using $\sigma$ to expand pseudoinstructions. |
---|
470 | The fetched sequence corresponds to the expansion, according to \texttt{sigma}, of the pseudoinstruction. |
---|
471 | |
---|
472 | At first, the lemmas appears to immediately imply the correctness of the assembler. |
---|
473 | However, 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. |
---|
474 | In particular, the two semantics differ on instructions that \emph{could} directly manipulate program addresses. |
---|
475 | |
---|
476 | % ---------------------------------------------------------------------------- % |
---|
477 | % SECTION % |
---|
478 | % ---------------------------------------------------------------------------- % |
---|
479 | \subsection{Total correctness for `well behaved' assembly programs} |
---|
480 | \label{subsect.total.correctness.for.well.behaved.assembly.programs} |
---|
481 | |
---|
482 | The traditional approach to verifying the correctness of an assembler is to treat memory addresses as opaque structures that cannot be modified. |
---|
483 | This prevents assembly programs from performing any `dangerous', semantics breaking manipulations of memory addresses by making these programs simply unrepresentable in the source language. |
---|
484 | |
---|
485 | Here, we take a different approach to this problem: we trace memory locations (and, potentially, registers) that contain memory addresses. |
---|
486 | We then prove that only those assembly programs that use addresses in `safe' ways have their semantics preserved by the assembly process. |
---|
487 | We believe that this approach is more flexible when compared to the traditional approach, as in principle it allows us to introduce some permitted \emph{benign} manipulations of addresses that the traditional approach, using opaque addresses, cannot handle, therefore expanding the set of input programs that can be assembled correctly. |
---|
488 | |
---|
489 | However, with this approach we must detect (at run time) programs that manipulate addresses in well behaved ways, according to some approximation of well-behavedness. |
---|
490 | Second, we must compute statuses that correspond to pseudo-statuses. |
---|
491 | The contents of the program counter must be translated, as well as the contents of all traced locations, by applying the \texttt{sigma} map. |
---|
492 | Remaining memory cells are copied \emph{verbatim}. |
---|
493 | |
---|
494 | For 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. |
---|
495 | This pseudo internal RAM corresponds to an internal RAM where the stack holds the real addresses after optimisation, and all the other values remain untouched. |
---|
496 | |
---|
497 | We use an \texttt{internal\_pseudo\_address\_map} to trace addresses of code memory addresses in internal RAM: |
---|
498 | \begin{lstlisting} |
---|
499 | definition internal_pseudo_address_map := |
---|
500 | list ((BitVector 8) $\times$ (bool $\times$ Word)) $\times$ (option (bool $\times$ Word)). |
---|
501 | \end{lstlisting} |
---|
502 | The implementation of \texttt{internal\_pseudo\_address\_map} is complicated by some peculiarities of the MCS-51's instruction set. |
---|
503 | Note here that all addresses are 16 bit words, but are stored (and manipulated) as 8 bit bytes. |
---|
504 | All \texttt{MOV} instructions in the MCS-51 must use the accumulator \texttt{A} as an intermediary, moving a byte at a time. |
---|
505 | The second component of \texttt{internal\_pseudo\_address\_map} therefore states whether the accumulator currently holds a piece of an address, and if so, whether it is the upper or lower byte of the address (using the boolean flag) complete with the corresponding, source address in full. |
---|
506 | The first component, on the other hand, performs a similar task for the rest of external RAM. |
---|
507 | Again, we use a boolean flag to describe whether a byte is the upper or lower component of a 16-bit address. |
---|
508 | |
---|
509 | The \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}. |
---|
510 | A similar function exists for higher internal RAM. |
---|
511 | Note that both RAM segments are indexed using addresses 7-bits long. |
---|
512 | The function is currently axiomatised, and an associated set of axioms prescribe the behaviour of the function: |
---|
513 | \begin{lstlisting} |
---|
514 | axiom low_internal_ram_of_pseudo_low_internal_ram: |
---|
515 | internal_pseudo_address_map$\rightarrow$BitVectorTrie Byte 7$\rightarrow$BitVectorTrie Byte 7. |
---|
516 | \end{lstlisting} |
---|
517 | |
---|
518 | Next, we are able to translate \texttt{PseudoStatus} records into \texttt{Status} records using \texttt{status\_of\_pseudo\_status}. |
---|
519 | Translating a \texttt{PseudoStatus}'s code memory requires we expand pseudoinstructions and then assemble to obtain a trie of bytes. |
---|
520 | This never fails, provided that our policy is correct: |
---|
521 | \begin{lstlisting} |
---|
522 | definition status_of_pseudo_status: |
---|
523 | internal_pseudo_address_map $\rightarrow$ $\forall$pap. $\forall$ps: PseudoStatus pap. |
---|
524 | $\forall$sigma: Word $\rightarrow$ Word. $\forall$policy: Word $\rightarrow$ bool. |
---|
525 | Status (code_memory_of_pseudo_assembly_program pap sigma policy) |
---|
526 | \end{lstlisting} |
---|
527 | |
---|
528 | The \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. |
---|
529 | It 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. |
---|
530 | It thus decides the membership of a strict subset of the set of well behaved programs. |
---|
531 | \begin{lstlisting} |
---|
532 | definition next_internal_pseudo_address_map: internal_pseudo_address_map |
---|
533 | $\rightarrow$ PseudoStatus $\rightarrow$ option internal_pseudo_address_map |
---|
534 | \end{lstlisting} |
---|
535 | Note, if we wished to allow `benign manipulations' of addresses, it would be this function that needs to be changed. |
---|
536 | |
---|
537 | The function \texttt{ticks\_of} computes how long---in clock cycles---a pseudoinstruction will take to execute when expanded in accordance with a given policy. |
---|
538 | The function returns a pair of natural numbers, needed for recording the execution times of each branch of a conditional jump. |
---|
539 | \begin{lstlisting} |
---|
540 | axiom ticks_of: |
---|
541 | $\forall$p:pseudo_assembly_program. policy p $\rightarrow$ Word $\rightarrow$ nat $\times$ nat := $\ldots$ |
---|
542 | \end{lstlisting} |
---|
543 | |
---|
544 | Finally, we are able to state and prove our main theorem. |
---|
545 | This relates the execution of a single assembly instruction and the execution of (possibly) many machine code instructions, as long as we are able to track memory addresses properly: |
---|
546 | \begin{lstlisting} |
---|
547 | theorem main_thm: |
---|
548 | $\forall$M, M': internal_pseudo_address_map. |
---|
549 | $\forall$program: pseudo_assembly_program. |
---|
550 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
551 | $\forall$is_well_labelled: is_well_labelled_p instr_list. |
---|
552 | $\forall$sigma: Word $\rightarrow$ Word. |
---|
553 | $\forall$policy: Word $\rightarrow$ bool. |
---|
554 | $\forall$sigma_policy_specification_witness. |
---|
555 | $\forall$ps: PseudoStatus program. |
---|
556 | $\forall$program_counter_in_bounds. |
---|
557 | next_internal_pseudo_address_map M program ps = Some $\ldots$ M' $\rightarrow$ |
---|
558 | $\exists$n. execute n $\ldots$ (status_of_pseudo_status M $\ldots$ ps sigma policy) = |
---|
559 | status_of_pseudo_status M' $\ldots$ (execute_1_pseudo_instruction |
---|
560 | (ticks_of program sigma policy) program ps) sigma policy. |
---|
561 | \end{lstlisting} |
---|
562 | The 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}. |
---|
563 | Further, we explicitly requires proof that our policy is correct and the pseudo program counter lies within the bounds of the program. |
---|
564 | Theorem \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. |
---|
565 | |
---|
566 | % ---------------------------------------------------------------------------- % |
---|
567 | % SECTION % |
---|
568 | % ---------------------------------------------------------------------------- % |
---|
569 | \section{Conclusions} |
---|
570 | \label{sect.conclusions} |
---|
571 | |
---|
572 | We are proving the total correctness of an assembler for MCS-51 assembly language. |
---|
573 | 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. |
---|
574 | Expanding 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. |
---|
575 | |
---|
576 | 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. |
---|
577 | 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. |
---|
578 | |
---|
579 | It is interesting to compare our work to an `industrial grade' assembler for the MCS-51: SDCC~\cite{sdcc:2011}. |
---|
580 | SDCC is the only open source C compiler that targets the MCS-51 instruction set. |
---|
581 | It 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. |
---|
582 | Note that this policy is the only possible policy \emph{in theory} that can preserve the semantics of an assembly program during the assembly process. |
---|
583 | However, this comes at the expense of assembler completeness: the generated program may be too large to fit into code memory. |
---|
584 | In this respect, there is a trade-off between the completeness of the assembler and the efficiency of the assembled program. |
---|
585 | The definition and proof of a terminating, correct jump expansion policy is described in a companion publication to this one. |
---|
586 | |
---|
587 | Aside 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. |
---|
588 | Of particular note is the verified seL4 kernel~\cite{klein:sel4:2009,klein:sel4:2010}. |
---|
589 | This verification explicitly assumes the existence of, amongst other things, a trustworthy assembler and compiler. |
---|
590 | |
---|
591 | Note that both CompCert and the seL4 formalisation assume the existence of `trustworthy' assemblers. |
---|
592 | The observation that an optimising assembler cannot preserve the semantics of every assembly program may have important consequences for these projects. |
---|
593 | If 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. |
---|
594 | |
---|
595 | Our formalisation exploits dependent types in different ways and for multiple purposes. |
---|
596 | The first purpose is to reduce potential errors in the formalisation of the microprocessor. |
---|
597 | In particular, dependent types are used to constraint the size of bitvectors and tries that represent memory quantities and memory areas respectively. |
---|
598 | They are also used to simulate polymorphic variants in Matita, in order to provide precise typings to various functions expecting only a subset of all possible addressing modes than the MCS-51 offers. |
---|
599 | Polymorphic variants nicely capture the absolutely unorthogonal instruction set of the MCS-51 where every opcode must accept its own subset of the 11 addressing mode of the processor. |
---|
600 | |
---|
601 | The second purpose is to single out the sources of incompleteness. |
---|
602 | By abstracting our functions over the dependent type of correct policies, we were able to manifest the fact that the compiler never refuses to compile a program where a correct policy exists. |
---|
603 | This also allowed to simplify the initial proof by dropping lemmas establishing that one function fails if and only if some other one does so. |
---|
604 | |
---|
605 | Finally, dependent types, together with Matita's liberal system of coercions, allow to simulate almost entirely in user space the proof methodology ``Russell'' of Sozeau~\cite{sozeau:subset:2006}. |
---|
606 | However, not every proof has been done this way: we only used this style to prove that a function satisfies a specification that only involves that function in a significant way. |
---|
607 | For example, it would be unnatural to see the proof that fetch and assembly commute as the specification of one of the two functions. |
---|
608 | |
---|
609 | \subsection{Related work} |
---|
610 | \label{subsect.related.work} |
---|
611 | |
---|
612 | % piton |
---|
613 | We are not the first to consider the total correctness of an assembler for a non-trivial assembly language. |
---|
614 | Perhaps the most impressive piece of work in this domain is the Piton stack~\cite{moore:piton:1996,moore:grand:2005}. |
---|
615 | 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}. |
---|
616 | |
---|
617 | % jinja |
---|
618 | Klein and Nipkow consider a Java-like programming language, Jinja~\cite{klein:machine:2006,klein:machine:2010}. |
---|
619 | 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. |
---|
620 | |
---|
621 | We believe some other verified assemblers exist in the literature. |
---|
622 | However, what sets our work apart from that above is our attempt to optimise the machine code generated by our assembler. |
---|
623 | This complicates any formalisation effort, as an attempt at 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. |
---|
624 | Further, 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. |
---|
625 | This is only possible by inducing a cost model on the source code from the optimisation strategy and input program. |
---|
626 | This will be a \emph{leit motif} of CerCo. |
---|
627 | |
---|
628 | \subsection{Resources} |
---|
629 | \label{subsect.resources} |
---|
630 | |
---|
631 | All files relating to our formalisation effort can be found online at~\url{http://cerco.cs.unibo.it}. |
---|
632 | The code of the compiler has been completed, and the proof of correctness described here is still in progress. |
---|
633 | In particular, we have assumed several properties of ``library functions'' related in particular to modular arithmetic and datastructure manipulation. |
---|
634 | Moreover, we have axiomatised various ancillary functions needed to complete the main theorems, as well as some `routine' proof obligations of the theorems themselves, preferring instead to focus on the main meat of the theorems. |
---|
635 | We thus believe that the proof strategy is sound and that we will be able to close soon all axioms, up to possible minor bugs that should have local fixes that do not affect the global proof strategy. |
---|
636 | |
---|
637 | The development, including the definition of the executable semantics of the MCS-51, is spread across 29 files, totalling around 18,500 lines of Matita source. |
---|
638 | The bulk of the proof described herein is contained in a series of files, \texttt{AssemblyProof.ma}, \texttt{AssemblyProofSplit.ma} and \texttt{AssemblyProofSplitSplit.ma} consisting at the moment of approximately 4200 lines of Matita source. |
---|
639 | Numerous other lines of proofs are spread all over the development because of dependent types and the Russell proof style, which does not allow one to separate the code from the proofs. |
---|
640 | The low ratio between the number of lines of code and the number of lines of proof is unusual. |
---|
641 | It is justified by the fact that the pseudo-assembly and the assembly language share most constructs and that large parts of the semantics are also shared. |
---|
642 | Thus many lines of code are required to describe the complex semantics of the processor, but, for the shared cases, the proof of preservation of the semantics is essentially trivial. |
---|
643 | |
---|
644 | \bibliography{cpp-2012-asm.bib} |
---|
645 | |
---|
646 | \end{document}\renewcommand{\verb}{\lstinline} |
---|
647 | \def\lstlanguagefiles{lst-grafite.tex} |
---|
648 | \lstset{language=Grafite} |
---|