[2052] | 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 | |
---|
[2088] | 37 | \title{On the correctness of an optimising 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.}} |
---|
[2052] | 38 | \author{Dominic P. Mulligan \and Claudio Sacerdoti Coen} |
---|
[2089] | 39 | \institute{Dipartimento di Scienze dell'Informazione,\\ Universit\'a degli Studi di Bologna} |
---|
[2052] | 40 | |
---|
| 41 | \bibliographystyle{splncs03} |
---|
| 42 | |
---|
| 43 | \begin{document} |
---|
| 44 | |
---|
| 45 | \maketitle |
---|
| 46 | |
---|
| 47 | \begin{abstract} |
---|
[2083] | 48 | We present a proof of correctness, in Matita, for an optimising assembler for the MCS-51 microcontroller. |
---|
| 49 | This assembler constitutes a major component of the EU's CerCo project. |
---|
[2052] | 50 | |
---|
[2327] | 51 | The efficient expansion of pseudoinstructions---namely jumps---into MCS-51 machine instructions is complex. |
---|
[2053] | 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. |
---|
[2052] | 54 | |
---|
[2053] | 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. |
---|
[2083] | 57 | Our proof strategy contains a tracking facility for `good addresses' and only programs that use good addresses have their semantics preserved under assembly. |
---|
[2087] | 58 | Our strategy offers increased flexibility over the traditional approach to proving the correctness of assemblers, wherein addresses in assembly are kept opaque and immutable. |
---|
[2053] | 59 | In particular, we may experiment with allowing the benign manipulation of addresses. |
---|
[2088] | 60 | \keywords{Verified software, CerCo (Certified Complexity), MCS-51 microcontroller, Matita proof assistant} |
---|
[2052] | 61 | \end{abstract} |
---|
| 62 | |
---|
| 63 | % ---------------------------------------------------------------------------- % |
---|
| 64 | % SECTION % |
---|
| 65 | % ---------------------------------------------------------------------------- % |
---|
| 66 | \section{Introduction} |
---|
| 67 | \label{sect.introduction} |
---|
| 68 | |
---|
| 69 | We consider the formalisation of an assembler for the Intel MCS-51 8-bit microprocessor in the Matita proof assistant~\cite{asperti:user:2007}. |
---|
[2053] | 70 | 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. |
---|
[2052] | 71 | |
---|
| 72 | The MCS-51 dates from the early 1980s and is commonly called the 8051/8052. |
---|
[2083] | 73 | Despite the microprocessor's age, derivatives are still widely manufactured by a number of semiconductor foundries, with the processor being used especially in embedded systems development, where well-tested, cheap, predictable microprocessors find their niche. |
---|
[2052] | 74 | |
---|
[2083] | 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 meaning that timing of execution is predictable, making the MCS-51 very attractive for CerCo's ends. |
---|
| 76 | Yet---as with many 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. |
---|
[2053] | 77 | In particular, the MCS-51 features a relatively minuscule series of memory spaces by modern standards. |
---|
[2052] | 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 | |
---|
[2340] | 80 | In order to do this, we must solve the `branch displacement' problem---deciding how best to expand pseudojumps to labels in assembly language to machine code jumps. The branch displacement problem happears when pseudojumps can be expanded |
---|
| 81 | in different ways to real machine instructions, but the different expansions |
---|
| 82 | are not equivalent (e.g. do not have the same size or speed) and not always |
---|
| 83 | correct (e.g. correctness is only up to global constraints over the compiled |
---|
| 84 | code). For instance, some jump instructions (short jumps) are very small |
---|
| 85 | and fast, but they can only reach destinations within a |
---|
| 86 | certain distance from the current instruction. When the destinations are |
---|
| 87 | too far away, larger and slower long jumps must be used. The use of a long jump may |
---|
| 88 | augment the distance between another pseudojump and its target, forcing |
---|
| 89 | another long jump use, in a cascading effect. The job of the optimizing |
---|
| 90 | compiler (assembler) is to individually expand every pseudo-instruction in such a way |
---|
| 91 | that all global constraints are satisfied and that the compiled program size |
---|
| 92 | is minimal in size and faster in time. The problem is known to be particularly |
---|
| 93 | complex for most CICS architectures (for instance, see~\cite{hyde:branch:2006}). |
---|
[2083] | 94 | |
---|
[2087] | 95 | To free the CerCo C compiler from having to consider complications relating to branch displacement, we have chosen to implement an optimising assembler, whose input language the compiler will target. |
---|
[2053] | 96 | 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. |
---|
[2087] | 97 | We simplify the proof by assuming that all our assembly programs are pre-linked (i.e. we do not formalise a linker---this is left for future work). |
---|
[2052] | 98 | |
---|
[2340] | 99 | Another complication we have addressed is that of the cost model. |
---|
| 100 | CerCo imposes a cost model on C programs or, more specifically, on simple blocks of instructions. |
---|
[2052] | 101 | 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. |
---|
| 102 | In short, we aim to obtain a very precise costing for a program by embracing the compilation process, not ignoring it. |
---|
[2340] | 103 | At the assembler level, this is reflected by our need to induce a cost |
---|
| 104 | model on the assembly code as a function of the assembly program and the |
---|
| 105 | strategy used to solve the branch displacement problem. In particular, the |
---|
| 106 | optimizing compiler should also return a map that assigns a cost (in clock |
---|
| 107 | cycles) to every instruction in the source program. We expect the induced cost |
---|
| 108 | to be preserved by the compiler: we will prove that the compiled code |
---|
| 109 | tightly simulates the source code by taking exactly the predicted amount of |
---|
| 110 | time. |
---|
[2052] | 111 | |
---|
[2340] | 112 | Note that the temporal tightness of the simulation is a fundamental prerequisite |
---|
| 113 | of the correctness of the simulation because some functions of the MCS-51, |
---|
| 114 | notably timers and I/O, depend on the microprocessor's clock. If the |
---|
| 115 | pseudo and concrete clock differs, the result of an I/O operation may not be |
---|
| 116 | preserved. |
---|
[2052] | 117 | |
---|
[2340] | 118 | Branch displacement algorithms must have a deep knowledge of the way |
---|
| 119 | the rest of the assembler works in order to build globally correct solutions. |
---|
| 120 | Proving their correctness is quite a complex task (see, for instance, |
---|
| 121 | the compaion paper~\cite{boender:correctness:2012}). |
---|
| 122 | Nevertheless, the correctness of the whole assembler only depends on the |
---|
| 123 | correctness of the branch displacement algorithm. |
---|
| 124 | Therefore, in the rest of the paper, we abstract the assembler on the |
---|
| 125 | existence of a correct policy, to be computed by a branch displacement |
---|
| 126 | algorithm if it exists. A policy is the decision over how |
---|
| 127 | any particular jump should be expanded; it is correct when the global |
---|
| 128 | constraints are satisfied. |
---|
| 129 | The assembler fails to assemble an assembly program if and only if a correct policy does not exist. This is stated in an elegant way in the dependent type of the assembler: the assembly function is total over a program, a policy and the proof that the policy is correct for that program. |
---|
[2052] | 130 | |
---|
[2341] | 131 | The final complication in the proof of correctness of our optimizing assembler |
---|
| 132 | is due to the kind of semantics associated to pseudo assembly programs. |
---|
| 133 | Should assembly programs be allowed to freely manipulate addresses? The |
---|
| 134 | answer to the question deeply affects the proof of correctness. |
---|
| 135 | The traditional answer is no: values stored in memory or registers are either |
---|
| 136 | concrete data or symbolic addresses. The latters can be manipulated only |
---|
| 137 | in very restrictive ways and many programs that do not do so, for malign or |
---|
| 138 | benign reasons, are not assigned a semantics and cannot be reasoned about. |
---|
| 139 | All programs that have a semantics have it preserved by the compiler. |
---|
| 140 | Instead we took a different, novel approach: we allow programs to freely |
---|
| 141 | manipulate |
---|
| 142 | addresses non symbolically, but we only grant preservation of the semantics |
---|
| 143 | for those programs that do behave in a correct, anticipated way. At least |
---|
| 144 | in principle, this should allow some reasoning on the actual semantics of |
---|
| 145 | malign programs. In practice, we note how the alternative approach allows |
---|
| 146 | more code reusal between the semantics of assembly code and object code, |
---|
| 147 | with benefits on the size of the formalization. |
---|
[2052] | 148 | |
---|
[2341] | 149 | The rest of this paper is a detailed description of our proof that is, in |
---|
| 150 | minimal part, still a work in progress. |
---|
| 151 | |
---|
[2327] | 152 | We provide the reader with a brief `roadmap' for the rest of the paper. |
---|
[2052] | 153 | In Section~\ref{sect.matita} we provide a brief overview of the Matita proof assistant for the unfamiliar reader. |
---|
| 154 | In Section~\ref{sect.the.proof} we discuss the design and implementation of the proof proper. |
---|
| 155 | In Section~\ref{sect.conclusions} we conclude. |
---|
| 156 | |
---|
| 157 | % ---------------------------------------------------------------------------- % |
---|
| 158 | % SECTION % |
---|
| 159 | % ---------------------------------------------------------------------------- % |
---|
| 160 | \section{Matita} |
---|
| 161 | \label{sect.matita} |
---|
| 162 | |
---|
| 163 | Matita is a proof assistant based on a variant of the Calculus of (Co)inductive Constructions~\cite{asperti:user:2007}. |
---|
[2327] | 164 | In particular, it features dependent types that we exploit in the formalisation. |
---|
[2052] | 165 | The syntax of the statements and definitions in the paper should be self-explanatory, at least to those exposed to dependent type theory. |
---|
[2327] | 166 | We only remark that the use of `$\mathtt{?}$' or `$\mathtt{\ldots}$' for omitting single terms or sequences of terms to be inferred automatically by the system, respectively. |
---|
[2052] | 167 | Those that are not inferred are left to the user as proof obligations. |
---|
| 168 | Pairs are denoted with angular brackets, $\langle-, -\rangle$. |
---|
| 169 | |
---|
| 170 | Matita features a liberal system of coercions. |
---|
| 171 | 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$. |
---|
| 172 | The coercion opens a proof obligation that asks the user to prove that $P$ holds for $x$. |
---|
| 173 | 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 |
---|
| 174 | 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$. |
---|
| 175 | 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. |
---|
| 176 | 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. |
---|
| 177 | |
---|
| 178 | % ---------------------------------------------------------------------------- % |
---|
| 179 | % SECTION % |
---|
| 180 | % ---------------------------------------------------------------------------- % |
---|
| 181 | \section{The proof} |
---|
| 182 | \label{sect.the.proof} |
---|
| 183 | |
---|
[2066] | 184 | % ---------------------------------------------------------------------------- % |
---|
| 185 | % SECTION % |
---|
| 186 | % ---------------------------------------------------------------------------- % |
---|
[2052] | 187 | |
---|
[2066] | 188 | \subsection{Machine code semantics} |
---|
| 189 | \label{subsect.machine.code.semantics} |
---|
| 190 | |
---|
[2058] | 191 | Our emulator centres around a \texttt{Status} record, describing the microprocessor's state. |
---|
[2327] | 192 | This record contains fields corresponding to the microprocessor's program counter, registers, stack pointer, special function registers, and so on. |
---|
[2087] | 193 | At the machine code level, code memory is implemented as a compact trie of bytes addressed by the program counter. |
---|
[2058] | 194 | 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. |
---|
[2052] | 195 | |
---|
| 196 | We may execute a single step of a machine code program using the \texttt{execute\_1} function, which returns an updated \texttt{Status}: |
---|
| 197 | \begin{lstlisting} |
---|
[2058] | 198 | definition execute_1: $\forall$cm. Status cm $\rightarrow$ Status cm := $\ldots$ |
---|
[2052] | 199 | \end{lstlisting} |
---|
[2339] | 200 | Here \texttt{Status} is parameterised by \texttt{cm}, a code memory represented as a trie. |
---|
[2067] | 201 | %The function \texttt{execute} allows one to execute an arbitrary, but fixed (due to Matita's normalisation requirement) number of steps of a program. |
---|
[2087] | 202 | The function \texttt{execute\_1} closely matches the operation of the MCS-51 hardware, as described by a Siemen's manufacturer's data sheet (specifically, this one~\cite{siemens:2011}). |
---|
[2066] | 203 | 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. |
---|
[2087] | 204 | Decoded instructions are represented as an inductive type, where $\llbracket - \rrbracket$ denotes a fixed-length vector: |
---|
[2066] | 205 | \begin{lstlisting} |
---|
| 206 | inductive preinstruction (A: Type[0]): Type[0] := |
---|
[2083] | 207 | | ADD: $\llbracket$acc_a$\rrbracket$ → $\llbracket$registr; direct; indirect; data$\rrbracket$ $\rightarrow$ preinstruction A |
---|
[2339] | 208 | | DEC: $\llbracket$acc_a; registr; direct; indirect$\rrbracket$ $\rightarrow$ preinstruction A |
---|
[2083] | 209 | | JB: $\llbracket$bit_addr$\rrbracket$ $\rightarrow$ A $\rightarrow$ preinstruction A |
---|
[2066] | 210 | | ... |
---|
| 211 | |
---|
[2083] | 212 | inductive instruction: Type[0] := |
---|
| 213 | | LCALL: $\llbracket$addr16$\rrbracket$ $\rightarrow$ instruction |
---|
| 214 | | AJMP: $\llbracket$addr11$\rrbracket$ $\rightarrow$ instruction |
---|
| 215 | | RealInstruction: preinstruction $\llbracket$relative$\rrbracket$ $\rightarrow$ instruction. |
---|
| 216 | | ... |
---|
[2066] | 217 | \end{lstlisting} |
---|
| 218 | 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. |
---|
| 219 | 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}. |
---|
| 220 | |
---|
| 221 | Once decoded, execution proceeds by a case analysis on the decoded instruction, following the operation of the hardware. |
---|
[2087] | 222 | For example, the \texttt{DEC} instruction (`decrement') is implemented as follows: |
---|
[2066] | 223 | \begin{lstlisting} |
---|
[2083] | 224 | | DEC addr $\Rightarrow$ |
---|
| 225 | let s := add_ticks1 s in |
---|
| 226 | let $\langle$result, flags$\rangle$ := sub_8_with_carry (get_arg_8 $\ldots$ s true addr) |
---|
| 227 | (bitvector_of_nat 8 1) false in |
---|
| 228 | set_arg_8 $\ldots$ s addr result |
---|
[2066] | 229 | \end{lstlisting} |
---|
| 230 | |
---|
| 231 | Here, \texttt{add\_ticks1} models the incrementing of the internal clock of the microprocessor. |
---|
| 232 | |
---|
| 233 | % ---------------------------------------------------------------------------- % |
---|
| 234 | % SECTION % |
---|
| 235 | % ---------------------------------------------------------------------------- % |
---|
| 236 | |
---|
| 237 | \subsection{Assembly code semantics} |
---|
| 238 | \label{subsect.assembly.code.semantics} |
---|
| 239 | |
---|
[2087] | 240 | 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 (i.e. global variables). |
---|
[2066] | 241 | Pseudoinstructions are implemented as an inductive type: |
---|
| 242 | \begin{lstlisting} |
---|
[2083] | 243 | inductive pseudo_instruction: Type[0] := |
---|
| 244 | | Instruction: preinstruction Identifier $\rightarrow$ pseudo_instruction |
---|
[2066] | 245 | ... |
---|
[2083] | 246 | | Jmp: Identifier $\rightarrow$ pseudo_instruction |
---|
| 247 | | Call: Identifier $\rightarrow$ pseudo_instruction |
---|
| 248 | | Mov: $\llbracket$dptr$\rrbracket$ $\rightarrow$ Identifier $\rightarrow$ pseudo_instruction. |
---|
[2066] | 249 | \end{lstlisting} |
---|
| 250 | 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. |
---|
| 251 | Similarly, conditional jumps can now only jump to labels, as is implied by the first constructor of the type above. |
---|
| 252 | 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}. |
---|
| 253 | These are jumps and calls to absolute addresses, which we do not wish to allow at the assembly level. |
---|
| 254 | |
---|
| 255 | Execution of pseudoinstructions is a function from \texttt{PseudoStatus} to \texttt{PseudoStatus}. |
---|
| 256 | Both \texttt{Status} and \texttt{PseudoStatus} are instances of a more general type parameterised over the representation of code memory. |
---|
[2087] | 257 | The more general type is crucial for sharing the majority of the semantics of the two languages. |
---|
[2052] | 258 | |
---|
[2066] | 259 | Emulation for pseudoinstructions is handled by \texttt{execute\_1\_pseudo\_instruction}: |
---|
[2052] | 260 | \begin{lstlisting} |
---|
[2058] | 261 | definition execute_1_pseudo_instruction: |
---|
[2339] | 262 | $\forall$cm. ($\forall$ppc: Word. ppc < $\mid$snd cm$\mid$ $\rightarrow$ nat $\times$ nat) $\rightarrow$ $\forall$s:PseudoStatus cm. |
---|
| 263 | program_counter $\ldots$ s < $\mid$snd cm$\mid$ $\rightarrow$ PseudoStatus cm := $\ldots$ |
---|
[2052] | 264 | \end{lstlisting} |
---|
[2339] | 265 | The type of \texttt{execute\_1\_pseudo\_instruction} is interesting. |
---|
| 266 | Note here that our representation of code memory \texttt{cm} is no longer a bitvector trie of bytes, but a list of pseudoinstructions. |
---|
| 267 | Further, we take in a function that maps program counters (at the assembly level) to pairs of natural numbers representing the number of clock ticks that the pseudoinstructions needs to execute, post expansion. |
---|
[2052] | 268 | We call this function a \emph{costing}, and note that the costing is induced by the particular strategy we use to expand pseudoinstructions. |
---|
| 269 | 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. |
---|
[2339] | 270 | This costing function expects a proof, at its second argument, stating that the program counter falls within the bounds of the pseudoprogram. |
---|
| 271 | A similar invariant holds of the pseudoprogram counter passed to the \texttt{execute\_1\_pseudo\_instruction} function. |
---|
[2052] | 272 | |
---|
| 273 | 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. |
---|
[2087] | 274 | The \texttt{add\_ticks1} function, which we have already seen used to increment the machine clock above, is determined for the assembly language from the costing function. |
---|
[2052] | 275 | |
---|
[2066] | 276 | Execution proceeds by first fetching from pseudo-code memory using the program counter---treated as an index into the pseudoinstruction list. |
---|
[2339] | 277 | This index is always guaranteed to be within the bounds of the pseudoinstruction list due to the dependent type placed on the function. |
---|
[2066] | 278 | No decoding is required. |
---|
| 279 | 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. |
---|
| 280 | For all newly introduced pseudoinstructions, we simply translate labels to concrete addresses before behaving as a `real' instruction. |
---|
| 281 | |
---|
| 282 | 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. |
---|
| 283 | Labels are immediately translated to concrete addresses, and registers and memory locations only ever contain bytes, never labels. |
---|
| 284 | 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. |
---|
| 285 | This will be further discussed in Subsection~\ref{subsect.total.correctness.for.well.behaved.assembly.programs}. |
---|
| 286 | |
---|
| 287 | % ---------------------------------------------------------------------------- % |
---|
| 288 | % SECTION % |
---|
| 289 | % ---------------------------------------------------------------------------- % |
---|
| 290 | |
---|
| 291 | \subsection{The assembler} |
---|
| 292 | \label{subsect.the.assembler} |
---|
| 293 | |
---|
| 294 | Conceptually the assembler works in two passes. |
---|
| 295 | The first pass expands pseudoinstructions into a list of machine code instructions using the function \texttt{expand\_pseudo\_instruction}. |
---|
| 296 | 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. |
---|
[2052] | 297 | \begin{displaymath} |
---|
| 298 | [\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]} |
---|
| 299 | \end{displaymath} |
---|
[2092] | 300 | The most complex of the two passes is the first, which expands pseudoinstructions and must perform the task of branch displacement~\cite{hyde:branch:2006}. |
---|
[2083] | 301 | The function \texttt{assembly\_1\_pseudo\_instruction} used in the body of the paper is essentially the composition of the two passes. |
---|
[2052] | 302 | |
---|
[2327] | 303 | The branch displacement problem refers to the task of expanding pseudojumps into their concrete counterparts, preferably as efficiently as possible. |
---|
[2066] | 304 | 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}. |
---|
| 305 | 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. |
---|
| 306 | 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. |
---|
| 307 | |
---|
| 308 | Similarly, a conditional pseudojump must be translated potentially into a configuration of machine code instructions, depending on the distance to the jump's target. |
---|
| 309 | 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'): |
---|
| 310 | {\small{ |
---|
| 311 | \begin{displaymath} |
---|
| 312 | \begin{array}{r@{\quad}l@{\;\;}l@{\qquad}c@{\qquad}l@{\;\;}l} |
---|
| 313 | & \mathtt{JZ} & \mathtt{label} & & \mathtt{JZ} & \text{size of \texttt{SJMP} instruction} \\ |
---|
| 314 | & \ldots & & \text{translates to} & \mathtt{SJMP} & \text{size of \texttt{LJMP} instruction} \\ |
---|
| 315 | \mathtt{label:} & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} & \Longrightarrow & \mathtt{LJMP} & \text{address of \textit{label}} \\ |
---|
| 316 | & & & & \ldots & \\ |
---|
| 317 | & & & & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} |
---|
| 318 | \end{array} |
---|
| 319 | \end{displaymath}}} |
---|
| 320 | Here, if \texttt{JZ} fails, we fall through to the \texttt{SJMP} which jumps over the \texttt{LJMP}. |
---|
| 321 | 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. |
---|
| 322 | |
---|
| 323 | In order to implement branch displacement it is impossible to really make the \texttt{expand\_pseudo\_instruction} function completely independent of the encoding function. |
---|
| 324 | This is due to branch displacement requiring the distance in bytes of the target of the jump. |
---|
| 325 | 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. |
---|
| 326 | 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. |
---|
| 327 | 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'. |
---|
| 328 | |
---|
| 329 | \begin{lstlisting} |
---|
| 330 | definition expand_pseudo_instruction: |
---|
| 331 | $\forall$lookup_labels: Identifier $\rightarrow$ Word. |
---|
| 332 | $\forall$sigma: Word $\rightarrow$ Word. |
---|
| 333 | $\forall$policy: Word $\rightarrow$ bool. |
---|
| 334 | $\forall$ppc: Word. |
---|
| 335 | $\forall$lookup_datalabels: Identifier $\rightarrow$ Word. |
---|
| 336 | $\forall$pi: pseudo_instruction. |
---|
| 337 | list instruction := ... |
---|
| 338 | \end{lstlisting} |
---|
| 339 | 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. |
---|
| 340 | The input \texttt{pi} is the pseudoinstruction to be expanded and is found at address \texttt{ppc} in the assembly program. |
---|
| 341 | The policy is defined using the two functions \texttt{sigma} and \texttt{policy}, of which \texttt{sigma} is the most interesting. |
---|
[2087] | 342 | The function \texttt{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)}. |
---|
[2066] | 343 | 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. |
---|
| 344 | \begin{displaymath} |
---|
| 345 | \texttt{sigma}(\texttt{ppc} + 1) = \texttt{pc} + \texttt{current\_instruction\_size} |
---|
| 346 | \end{displaymath} |
---|
| 347 | Here, \texttt{current\_instruction\_size} is the size in bytes of the encoding of the expanded pseudoinstruction found at \texttt{ppc}. |
---|
[2083] | 348 | Note that the entanglement we hinted at is only partially solved in this way: the assembler code can ignore the implementation details of the algorithm that finds a policy; |
---|
| 349 | however, the algorithm that finds a policy must know the exact behaviour of the assembly program because it needs to predict the way the assembly will expand and encode pseudoinstructions, once fed with a policy. |
---|
[2087] | 350 | A companion submission to this one~\cite{boender:correctness:2012} certifies an algorithm that finds branch displacement policies for the assembler described in this paper. |
---|
[2067] | 351 | |
---|
[2066] | 352 | 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. |
---|
[2083] | 353 | For instance, if at address \texttt{ppc} in the assembly program we found \texttt{Jmp l} such that \texttt{lookup\_labels l = a}, if the offset \texttt{d = sigma(a) - sigma(ppc + 1)} is such that \texttt{d} $< 128$ then \texttt{Jmp l} is normally translated to the best local solution, the short jump \texttt{SJMP d}. |
---|
| 354 | A global best solution to the branch displacement problem, however, is not always made of locally best solutions. |
---|
| 355 | Therefore, in some circumstances, it is necessary to force the assembler to expand jumps into larger ones. |
---|
| 356 | This is achieved by the \texttt{policy} function: if \texttt{policy ppc = true} then a \texttt{Jmp l} at address \texttt{ppc} is always translated to a long jump. |
---|
| 357 | An essentially identical mechanism exists for call instructions. |
---|
[2066] | 358 | |
---|
[2052] | 359 | % ---------------------------------------------------------------------------- % |
---|
| 360 | % SECTION % |
---|
| 361 | % ---------------------------------------------------------------------------- % |
---|
| 362 | \subsection{Correctness of the assembler with respect to fetching} |
---|
| 363 | \label{subsect.total.correctness.of.the.assembler} |
---|
| 364 | Using our policies, we now work toward proving the total correctness of the assembler. |
---|
[2068] | 365 | 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. |
---|
[2052] | 366 | |
---|
[2087] | 367 | The aim of this section is to prove the following informal statement: when we fetch an assembly pseudoinstruction \texttt{I} at address \texttt{ppc}, then we can fetch the expanded pseudoinstruction(s) \texttt{[J1, \ldots, Jn] = fetch\_pseudo\_instruction \ldots\ I\ ppc} from \texttt{sigma(ppc)} in the code memory obtained by loading the assembled object code. |
---|
[2083] | 368 | This constitutes the first major step in the proof of correctness of the assembler, the next one being the simulation of \texttt{I} by \texttt{[J1, \ldots, Jn]} (see Subsection~\ref{subsect.total.correctness.for.well.behaved.assembly.programs}). |
---|
[2069] | 369 | |
---|
[2083] | 370 | The \texttt{assembly} function is given a Russell type (slightly simplified here): |
---|
[2052] | 371 | \begin{lstlisting} |
---|
[2083] | 372 | definition assembly: |
---|
[2339] | 373 | $\forall$program: pseudo_assembly_program. |
---|
| 374 | $\forall$policy. |
---|
| 375 | $\Sigma$assembled: list Byte $\times$ (BitVectorTrie costlabel 16). |
---|
| 376 | policy is correct for program $\rightarrow$ |
---|
[2342] | 377 | $\mid$program$\mid$ < $2^{16}$ $\rightarrow$ $\mid$fst assembled$\mid$ < $2^{16}$ $\wedge$ |
---|
| 378 | (policy ($\mid$program$\mid$) = $\mid$fst assembled$\mid$ $\vee$ |
---|
| 379 | (policy ($\mid$program$\mid$) = 0 $\wedge$ $\mid$fst assembled$\mid$ = $2^{16}$)) $\wedge$ |
---|
| 380 | $\forall$ppc: pseudo_program_counter. ppc < $2^{16}$ $\rightarrow$ |
---|
[2339] | 381 | let pseudo_instr := fetch from program at ppc in |
---|
| 382 | let assembled_i := assemble pseudo_instr in |
---|
| 383 | $\mid$assembled_i$\mid$ $\leq$ $2^{16}$ $\wedge$ |
---|
[2342] | 384 | $\forall$n: nat. n < $\mid$assembled_i$\mid$ $\rightarrow$ $\exists$k: nat. |
---|
[2339] | 385 | nth assembled_i n = nth assembled (policy ppc + k). |
---|
[2052] | 386 | \end{lstlisting} |
---|
[2342] | 387 | [dpm: update] |
---|
[2327] | 388 | In plain words, the type of \texttt{assembly} states the following. |
---|
[2083] | 389 | Suppose we are given a policy that is correct for the program we are assembling, and suppose the program to be assembled is fully addressable by a 16-bit word. |
---|
| 390 | Then if we fetch from the pseudo program counter \texttt{ppc} we get a pseudoinstruction \texttt{pi} and a new pseudo program counter \texttt{ppc}. |
---|
| 391 | Further, assembling the pseudoinstruction \texttt{pi} results in a list of bytes, \texttt{a}. |
---|
| 392 | Then, indexing into this list with any natural number \texttt{j} less than the length of \texttt{a} gives the same result as indexing into \texttt{assembled} with \texttt{sigma(ppc)} (the program counter pointing to the start of the expansion in \texttt{assembled}) plus \texttt{j}. |
---|
[2052] | 393 | |
---|
[2087] | 394 | Essentially the lemma above states that the \texttt{assembly} function correctly expands pseudoinstructions, and that the expanded instruction reside consecutively in memory. |
---|
[2083] | 395 | This result is lifted from lists of bytes into a result on tries of bytes (i.e. code memories), using an additional lemma: \texttt{assembly\_ok}. |
---|
| 396 | |
---|
[2058] | 397 | Lemma \texttt{fetch\_assembly} establishes that the \texttt{fetch} and \texttt{assembly1} functions interact correctly. |
---|
[2052] | 398 | 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: |
---|
| 399 | \begin{lstlisting} |
---|
[2058] | 400 | lemma fetch_assembly: |
---|
| 401 | $\forall$pc: Word. |
---|
| 402 | $\forall$i: instruction. |
---|
| 403 | $\forall$code_memory: BitVectorTrie Byte 16. |
---|
| 404 | $\forall$assembled: list Byte. |
---|
[2342] | 405 | assembled = assemble i $\rightarrow$ |
---|
| 406 | let len := $\mid$assembled$\mid$ in |
---|
| 407 | let pc_plus_len := pc + len in |
---|
| 408 | encoding_check pc pc_plus_len assembled $\rightarrow$ |
---|
| 409 | let $\langle$instr, pc', ticks$\rangle$ := fetch pc in |
---|
[2083] | 410 | instr = i $\wedge$ ticks = (ticks_of_instruction instr) $\wedge$ pc' = pc_plus_len. |
---|
[2052] | 411 | \end{lstlisting} |
---|
| 412 | In particular, we read \texttt{fetch\_assembly} as follows. |
---|
| 413 | 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. |
---|
[2058] | 414 | 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. |
---|
| 415 | 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. |
---|
[2052] | 416 | Or, in plainer words, assembling and then immediately fetching again gets you back to where you started. |
---|
| 417 | |
---|
| 418 | Lemma \texttt{fetch\_assembly\_pseudo} (slightly simplified, here) is obtained by composition of \texttt{expand\_pseudo\_instruction} and \texttt{assembly\_1\_pseudoinstruction}: |
---|
| 419 | \begin{lstlisting} |
---|
| 420 | lemma fetch_assembly_pseudo: |
---|
[2058] | 421 | $\forall$program: pseudo_assembly_program. |
---|
[2342] | 422 | $\forall$policy. |
---|
[2058] | 423 | $\forall$ppc. |
---|
| 424 | $\forall$code_memory. |
---|
| 425 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
| 426 | let pi := $\pi_1$ (fetch_pseudo_instruction instr_list ppc) in |
---|
[2342] | 427 | let pc := policy ppc in |
---|
| 428 | let instrs := expand_pseudo_instructio sigma policy ppc pi in |
---|
| 429 | let $\langle$l, a$\rangle$ := assembly_1_pseudoinstruction sigma policy ppc pi in |
---|
| 430 | let pc_plus_len := pc + l in |
---|
[2058] | 431 | encoding_check code_memory pc pc_plus_len a $\rightarrow$ |
---|
| 432 | fetch_many code_memory pc_plus_len pc instructions. |
---|
[2052] | 433 | \end{lstlisting} |
---|
[2058] | 434 | Here, \texttt{l} is the number of machine code instructions the pseudoinstruction at hand has been expanded into. |
---|
[2087] | 435 | We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{expand\_pseudo\_instruction}. |
---|
[2052] | 436 | The function \texttt{fetch\_many} fetches multiple machine code instructions from code memory and performs some routine checks. |
---|
| 437 | |
---|
| 438 | Intuitively, Lemma \texttt{fetch\_assembly\_pseudo} can be read as follows. |
---|
[2058] | 439 | Suppose we expand the pseudoinstruction at \texttt{ppc} with the policy decision \texttt{sigma}, obtaining the list of machine code instructions \texttt{instrs}. |
---|
| 440 | Suppose we also assemble the pseudoinstruction at \texttt{ppc} to obtain \texttt{a}, a list of bytes. |
---|
[2052] | 441 | 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. |
---|
| 442 | |
---|
| 443 | 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. |
---|
[2058] | 444 | Again, we slightly simplify: |
---|
[2052] | 445 | \begin{lstlisting} |
---|
| 446 | lemma fetch_assembly_pseudo2: |
---|
[2058] | 447 | $\forall$program. |
---|
[2342] | 448 | $\mid$snd program$\mid$ $\leq$ $2^{16}$ $\rightarrow$ |
---|
[2058] | 449 | $\forall$policy. |
---|
[2342] | 450 | policy is correct for program $\rightarrow$ |
---|
| 451 | $\forall$ppc. ppc < $\mid$snd program$\mid$ $\rightarrow$ |
---|
[2058] | 452 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
| 453 | let $\langle$labels, costs$\rangle$ := create_label_cost_map instr_list in |
---|
[2342] | 454 | let $\langle$assembled, costs'$\rangle$ := $\pi_1$ (assembly program sigma policy) in |
---|
[2058] | 455 | let cmem := load_code_memory assembled in |
---|
| 456 | let $\langle$pi, newppc$\rangle$ := fetch_pseudo_instruction instr_list ppc in |
---|
[2342] | 457 | let instructions := expand_pseudo_instruction policy ppc pi in |
---|
| 458 | fetch_many cmem (policy newppc) (policy ppc) instructions. |
---|
[2052] | 459 | \end{lstlisting} |
---|
| 460 | |
---|
[2327] | 461 | Here we use $\pi_1 \ldots$ to project the existential witness from the Russell-typed function \texttt{assembly}. |
---|
[2058] | 462 | |
---|
[2052] | 463 | We read \texttt{fetch\_assembly\_pseudo2} as follows. |
---|
[2058] | 464 | Suppose we are able to successfully assemble an assembly program using \texttt{assembly} and produce a code memory, \texttt{cmem}. |
---|
[2087] | 465 | 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 \texttt{sigma} to expand pseudoinstructions. |
---|
[2058] | 466 | The fetched sequence corresponds to the expansion, according to \texttt{sigma}, of the pseudoinstruction. |
---|
[2052] | 467 | |
---|
[2327] | 468 | At first, the lemma appears to immediately imply the correctness of the assembler. |
---|
[2083] | 469 | 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 pseudoinstruction and that of its expansion. |
---|
[2052] | 470 | In particular, the two semantics differ on instructions that \emph{could} directly manipulate program addresses. |
---|
| 471 | |
---|
| 472 | % ---------------------------------------------------------------------------- % |
---|
| 473 | % SECTION % |
---|
| 474 | % ---------------------------------------------------------------------------- % |
---|
| 475 | \subsection{Total correctness for `well behaved' assembly programs} |
---|
| 476 | \label{subsect.total.correctness.for.well.behaved.assembly.programs} |
---|
| 477 | |
---|
[2058] | 478 | The traditional approach to verifying the correctness of an assembler is to treat memory addresses as opaque structures that cannot be modified. |
---|
[2083] | 479 | Memory is represented as a map from opaque addresses to the disjoint union of data and opaque addresses---addresses are kept opaque to prevent their possible `semantics breaking' manipulation by assembly programs: |
---|
| 480 | \begin{displaymath} |
---|
| 481 | \mathtt{Mem} : \mathtt{Addr} \rightarrow \mathtt{Bytes} + \mathtt{Addr} \qquad \llbracket - \rrbracket : \mathtt{Instr} \rightarrow \mathtt{Mem} \rightarrow \mathtt{option\ Mem} |
---|
| 482 | \end{displaymath} |
---|
| 483 | The semantics of a pseudoinstruction, $\llbracket - \rrbracket$, is given as a possibly failing function from pseudoinstructions and memory spaces to new memory spaces. |
---|
| 484 | The semantic function proceeds by case analysis over the operands of a given instruction, failing if either operand is an opaque address, or otherwise succeeding, updating memory. |
---|
| 485 | \begin{gather*} |
---|
| 486 | \llbracket \mathtt{ADD\ @A1\ @A2} \rrbracket^\mathtt{M} = \begin{cases} |
---|
| 487 | \mathtt{Byte\ b1},\ \mathtt{Byte\ b2} & \rightarrow \mathtt{Some}(\mathtt{M}\ \text{with}\ \mathtt{b1} + \mathtt{b2}) \\ |
---|
| 488 | -,\ \mathtt{Addr\ a} & \rightarrow \mathtt{None} \\ |
---|
| 489 | \mathtt{Addr\ a},\ - & \rightarrow \mathtt{None} |
---|
| 490 | \end{cases} |
---|
| 491 | \end{gather*} |
---|
| 492 | In contrast, in this paper we take a different approach. |
---|
| 493 | We trace memory locations (and, potentially, registers) that contain memory addresses. |
---|
[2087] | 494 | We then prove that only those assembly programs that use addresses in `safe' ways have their semantics preserved by the assembly process---a sort of dynamic type system sitting atop memory. |
---|
[2052] | 495 | |
---|
[2058] | 496 | 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. |
---|
[2327] | 497 | This approach, of using real addresses coupled with a weak, dynamic typing system sitting atop of memory, is similar to one taken by Tuch \emph{et al}~\cite{tuch:types:2007}, for reasoning about low-level C code. |
---|
[2052] | 498 | |
---|
[2083] | 499 | Our analogue of the semantic function above is then merely a wrapper around the function that implements the semantics of machine code, paired with a function that keeps track of addresses. |
---|
[2087] | 500 | This permits a large amount of code reuse, as the semantics of pseudo- and machine code are essentially shared. |
---|
| 501 | The only thing that changes at the assembly level is the presence of the new tracking function. |
---|
[2083] | 502 | |
---|
[2058] | 503 | 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. |
---|
[2060] | 504 | We use an \texttt{internal\_pseudo\_address\_map} to trace addresses of code memory addresses in internal RAM: |
---|
[2052] | 505 | \begin{lstlisting} |
---|
[2342] | 506 | definition address_entry := upper_lower $\times$ Byte. |
---|
| 507 | |
---|
[2060] | 508 | definition internal_pseudo_address_map := |
---|
[2342] | 509 | (BitVectorTrie address_entry 7) $\times$ (BitVectorTrie address_entry 7) |
---|
| 510 | $\times$ (option address_entry). |
---|
[2052] | 511 | \end{lstlisting} |
---|
[2342] | 512 | [dpm update] |
---|
[2060] | 513 | The implementation of \texttt{internal\_pseudo\_address\_map} is complicated by some peculiarities of the MCS-51's instruction set. |
---|
| 514 | Note here that all addresses are 16 bit words, but are stored (and manipulated) as 8 bit bytes. |
---|
| 515 | All \texttt{MOV} instructions in the MCS-51 must use the accumulator \texttt{A} as an intermediary, moving a byte at a time. |
---|
[2327] | 516 | 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. |
---|
[2060] | 517 | The first component, on the other hand, performs a similar task for the rest of external RAM. |
---|
| 518 | Again, we use a boolean flag to describe whether a byte is the upper or lower component of a 16-bit address. |
---|
[2052] | 519 | |
---|
| 520 | 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}. |
---|
[2087] | 521 | A similar function exists for high internal RAM. |
---|
[2052] | 522 | Note that both RAM segments are indexed using addresses 7-bits long. |
---|
| 523 | The function is currently axiomatised, and an associated set of axioms prescribe the behaviour of the function: |
---|
| 524 | \begin{lstlisting} |
---|
[2342] | 525 | definition low_internal_ram_of_pseudo_low_internal_ram: |
---|
| 526 | internal_pseudo_address_map $\rightarrow$ policy $\rightarrow$ BitVectorTrie Byte 7 |
---|
| 527 | $\rightarrow$ BitVectorTrie Byte 7. |
---|
[2052] | 528 | \end{lstlisting} |
---|
| 529 | |
---|
| 530 | Next, we are able to translate \texttt{PseudoStatus} records into \texttt{Status} records using \texttt{status\_of\_pseudo\_status}. |
---|
| 531 | Translating a \texttt{PseudoStatus}'s code memory requires we expand pseudoinstructions and then assemble to obtain a trie of bytes. |
---|
[2063] | 532 | This never fails, provided that our policy is correct: |
---|
[2052] | 533 | \begin{lstlisting} |
---|
[2058] | 534 | definition status_of_pseudo_status: |
---|
| 535 | internal_pseudo_address_map $\rightarrow$ $\forall$pap. $\forall$ps: PseudoStatus pap. |
---|
[2342] | 536 | $\forall$policy. Status (code_memory_of_pseudo_assembly_program pap sigma policy) |
---|
[2052] | 537 | \end{lstlisting} |
---|
| 538 | |
---|
| 539 | 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. |
---|
| 540 | 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. |
---|
| 541 | It thus decides the membership of a strict subset of the set of well behaved programs. |
---|
| 542 | \begin{lstlisting} |
---|
[2342] | 543 | definition next_internal_pseudo_address_map: internal_pseudo_address_map $\rightarrow$ |
---|
| 544 | $\forall$cm. (Identifier $\rightarrow$ PseudoStatus cm $\rightarrow$ Word) $\rightarrow$ $\forall$s: PseudoStatus cm. |
---|
| 545 | program_counter s < $2^{16}$ $\rightarrow$ option internal_pseudo_address_map |
---|
[2052] | 546 | \end{lstlisting} |
---|
[2342] | 547 | [dpm change] |
---|
[2058] | 548 | Note, if we wished to allow `benign manipulations' of addresses, it would be this function that needs to be changed. |
---|
[2052] | 549 | |
---|
[2083] | 550 | The function \texttt{ticks\_of0} computes how long---in clock cycles---a pseudoinstruction will take to execute when expanded in accordance with a given policy. |
---|
[2052] | 551 | The function returns a pair of natural numbers, needed for recording the execution times of each branch of a conditional jump. |
---|
| 552 | \begin{lstlisting} |
---|
[2083] | 553 | definition ticks_of0: |
---|
[2342] | 554 | pseudo_assembly_program $\rightarrow$ (Identifier $\rightarrow$ Word) $\rightarrow$ $\forall$policy. Word $\rightarrow$ |
---|
| 555 | pseudo_instruction $\rightarrow$ nat $\times$ nat |
---|
[2052] | 556 | \end{lstlisting} |
---|
[2083] | 557 | An additional function, \texttt{ticks\_of}, is merely a wrapper around this function. |
---|
[2052] | 558 | |
---|
| 559 | Finally, we are able to state and prove our main theorem. |
---|
[2058] | 560 | 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: |
---|
[2052] | 561 | \begin{lstlisting} |
---|
| 562 | theorem main_thm: |
---|
[2058] | 563 | $\forall$M, M': internal_pseudo_address_map. |
---|
| 564 | $\forall$program: pseudo_assembly_program. |
---|
[2342] | 565 | $\forall$program_in_bounds: $\mid$program$\mid$ $\leq$ $2^{16}$. |
---|
| 566 | let maps := create_label_cost_map program in |
---|
| 567 | let addr_of := ... in |
---|
| 568 | program is well labelled $\rightarrow$ |
---|
| 569 | $\forall$policy. policy is correct for program. |
---|
| 570 | $\forall$ps: PseudoStatus program. ps < $\mid$program$\mid$. |
---|
| 571 | next_internal_pseudo_address_map M program ... = Some M' $\rightarrow$ |
---|
| 572 | $\exists$n. execute n (status_of_pseudo_status M ps policy) = |
---|
| 573 | status_of_pseudo_status M' |
---|
| 574 | (execute_1_pseudo_instruction program |
---|
| 575 | (ticks_of program ($\lambda$id. addr_of id ps) policy) ps) policy. |
---|
[2052] | 576 | \end{lstlisting} |
---|
[2342] | 577 | [dpm change] |
---|
[2052] | 578 | 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}. |
---|
[2087] | 579 | Further, we explicitly require proof that our policy is correct and the pseudo program counter lies within the bounds of the program. |
---|
[2052] | 580 | 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. |
---|
| 581 | |
---|
| 582 | % ---------------------------------------------------------------------------- % |
---|
| 583 | % SECTION % |
---|
| 584 | % ---------------------------------------------------------------------------- % |
---|
| 585 | \section{Conclusions} |
---|
| 586 | \label{sect.conclusions} |
---|
| 587 | |
---|
| 588 | We are proving the total correctness of an assembler for MCS-51 assembly language. |
---|
[2087] | 589 | In particular, our assembly language features 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. |
---|
[2052] | 590 | 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. |
---|
| 591 | |
---|
| 592 | 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. |
---|
[2087] | 593 | The verified assembler, complete with the underlying formalisation of the semantics of MCS-51 machine code, will form the bedrock layer upon which the rest of the CerCo project will build its verified compiler platform. |
---|
[2052] | 594 | |
---|
| 595 | It is interesting to compare our work to an `industrial grade' assembler for the MCS-51: SDCC~\cite{sdcc:2011}. |
---|
| 596 | SDCC is the only open source C compiler that targets the MCS-51 instruction set. |
---|
| 597 | 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. |
---|
| 598 | 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. |
---|
| 599 | However, this comes at the expense of assembler completeness: the generated program may be too large to fit into code memory. |
---|
| 600 | In this respect, there is a trade-off between the completeness of the assembler and the efficiency of the assembled program. |
---|
[2087] | 601 | The definition and proof of a terminating, correct jump expansion policy is described in a companion publication to this one~\cite{boender:correctness:2012}. |
---|
[2052] | 602 | |
---|
[2095] | 603 | Aside from their application in verified compiler projects such as CerCo, CompCert~\cite{leroy:formally:2009} and CompCertTSO~\cite{sevcik:relaxed-memory:2011}, verified assemblers such as ours could also be applied to the verification of operating system kernels. |
---|
[2052] | 604 | Of particular note is the verified seL4 kernel~\cite{klein:sel4:2009,klein:sel4:2010}. |
---|
| 605 | This verification explicitly assumes the existence of, amongst other things, a trustworthy assembler and compiler. |
---|
| 606 | |
---|
[2095] | 607 | Note that both CompCert, CompCertTSO and the seL4 formalisation assume the existence of `trustworthy' assemblers. |
---|
| 608 | For instance, the CompCert C compiler's backend stops at the PowerPC assembly language, in the default backend. |
---|
| 609 | The observation that an optimising assembler cannot preserve the semantics of every assembly program may have important consequences for these projects (though in the case of CompCertTSO, targetting a multiprocessor, what exactly constitutes the subset of `good programs' may not be entirely clear). |
---|
[2052] | 610 | 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. |
---|
| 611 | |
---|
[2060] | 612 | Our formalisation exploits dependent types in different ways and for multiple purposes. |
---|
| 613 | The first purpose is to reduce potential errors in the formalisation of the microprocessor. |
---|
[2327] | 614 | In particular, dependent types are used to constrain the size of bitvectors and tries that represent memory quantities and memory areas respectively. |
---|
| 615 | 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 that the MCS-51 offers. |
---|
[2060] | 616 | 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. |
---|
[2052] | 617 | |
---|
[2060] | 618 | The second purpose is to single out the sources of incompleteness. |
---|
| 619 | 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. |
---|
[2087] | 620 | This also allowed to simplify the initial proof by dropping lemmas establishing that one function fails if and only if some previous function does so. |
---|
[2052] | 621 | |
---|
[2087] | 622 | Finally, dependent types, together with Matita's liberal system of coercions, allow us to simulate almost entirely---in user space---the proof methodology ``Russell'' of Sozeau~\cite{sozeau:subset:2006}. |
---|
| 623 | However, not every proof has been carried out in this way: we only used this style to prove that a function satisfies a specification that only involves that function in a significant way. |
---|
[2060] | 624 | For example, it would be unnatural to see the proof that fetch and assembly commute as the specification of one of the two functions. |
---|
[2052] | 625 | |
---|
| 626 | \subsection{Related work} |
---|
| 627 | \label{subsect.related.work} |
---|
| 628 | |
---|
| 629 | % piton |
---|
| 630 | We are not the first to consider the total correctness of an assembler for a non-trivial assembly language. |
---|
| 631 | Perhaps the most impressive piece of work in this domain is the Piton stack~\cite{moore:piton:1996,moore:grand:2005}. |
---|
| 632 | 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}. |
---|
| 633 | |
---|
| 634 | % jinja |
---|
| 635 | Klein and Nipkow consider a Java-like programming language, Jinja~\cite{klein:machine:2006,klein:machine:2010}. |
---|
| 636 | 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. |
---|
| 637 | |
---|
| 638 | We believe some other verified assemblers exist in the literature. |
---|
| 639 | However, what sets our work apart from that above is our attempt to optimise the machine code generated by our assembler. |
---|
[2083] | 640 | 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 minuscule code memory. |
---|
[2052] | 641 | 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. |
---|
| 642 | This is only possible by inducing a cost model on the source code from the optimisation strategy and input program. |
---|
| 643 | This will be a \emph{leit motif} of CerCo. |
---|
| 644 | |
---|
| 645 | \subsection{Resources} |
---|
| 646 | \label{subsect.resources} |
---|
| 647 | |
---|
[2060] | 648 | All files relating to our formalisation effort can be found online at~\url{http://cerco.cs.unibo.it}. |
---|
| 649 | In particular, we have assumed several properties of ``library functions'' related in particular to modular arithmetic and datastructure manipulation. |
---|
| 650 | 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. |
---|
| 651 | 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. |
---|
[2052] | 652 | |
---|
[2060] | 653 | 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. |
---|
| 654 | 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. |
---|
| 655 | 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. |
---|
| 656 | The low ratio between the number of lines of code and the number of lines of proof is unusual. |
---|
| 657 | 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. |
---|
[2087] | 658 | Therefore 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. |
---|
[2052] | 659 | |
---|
[2053] | 660 | \bibliography{cpp-2012-asm.bib} |
---|
[2052] | 661 | |
---|
| 662 | \end{document}\renewcommand{\verb}{\lstinline} |
---|
| 663 | \def\lstlanguagefiles{lst-grafite.tex} |
---|
| 664 | \lstset{language=Grafite} |
---|