[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. |
---|
[2052] | 49 | |
---|
[2327] | 50 | The efficient expansion of pseudoinstructions---namely jumps---into MCS-51 machine instructions is complex. |
---|
[2053] | 51 | We isolate the decision making over how jumps should be expanded from the expansion process itself as much as possible using `policies'. |
---|
| 52 | This makes the proof of correctness for the assembler significantly more straightforward. |
---|
[2052] | 53 | |
---|
[2053] | 54 | We observe that it is impossible for an optimising assembler to preserve the semantics of every assembly program. |
---|
| 55 | Assembly language programs can manipulate concrete addresses in arbitrary ways. |
---|
[2083] | 56 | Our proof strategy contains a tracking facility for `good addresses' and only programs that use good addresses have their semantics preserved under assembly. |
---|
[2087] | 57 | 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] | 58 | In particular, we may experiment with allowing the benign manipulation of addresses. |
---|
[2088] | 59 | \keywords{Verified software, CerCo (Certified Complexity), MCS-51 microcontroller, Matita proof assistant} |
---|
[2052] | 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}. |
---|
[2053] | 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. |
---|
[2052] | 70 | |
---|
| 71 | The MCS-51 dates from the early 1980s and is commonly called the 8051/8052. |
---|
[2083] | 72 | 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] | 73 | |
---|
[2083] | 74 | 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. |
---|
| 75 | 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] | 76 | In particular, the MCS-51 features a relatively minuscule series of memory spaces by modern standards. |
---|
[2052] | 77 | 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. |
---|
| 78 | |
---|
[2340] | 79 | 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 |
---|
| 80 | in different ways to real machine instructions, but the different expansions |
---|
| 81 | are not equivalent (e.g. do not have the same size or speed) and not always |
---|
| 82 | correct (e.g. correctness is only up to global constraints over the compiled |
---|
| 83 | code). For instance, some jump instructions (short jumps) are very small |
---|
| 84 | and fast, but they can only reach destinations within a |
---|
| 85 | certain distance from the current instruction. When the destinations are |
---|
| 86 | too far away, larger and slower long jumps must be used. The use of a long jump may |
---|
| 87 | augment the distance between another pseudojump and its target, forcing |
---|
[2343] | 88 | another long jump use, in a cascading effect. The job of the optimising |
---|
[2340] | 89 | compiler (assembler) is to individually expand every pseudo-instruction in such a way |
---|
| 90 | that all global constraints are satisfied and that the compiled program size |
---|
[2357] | 91 | is minimal in size and faster in time. |
---|
| 92 | This problem is known to be complex for most CISC architectures (see~\cite{hyde:branch:2006}). |
---|
[2083] | 93 | |
---|
[2358] | 94 | To free CerCo's 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] | 95 | 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] | 96 | 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] | 97 | |
---|
[2340] | 98 | Another complication we have addressed is that of the cost model. |
---|
| 99 | CerCo imposes a cost model on C programs or, more specifically, on simple blocks of instructions. |
---|
[2344] | 100 | This cost model is induced by the compilation process itself, and its non-compositional nature allows us to assign different costs to identical C statements depending on how they are compiled. |
---|
[2052] | 101 | In short, we aim to obtain a very precise costing for a program by embracing the compilation process, not ignoring it. |
---|
[2340] | 102 | At the assembler level, this is reflected by our need to induce a cost |
---|
| 103 | model on the assembly code as a function of the assembly program and the |
---|
| 104 | strategy used to solve the branch displacement problem. In particular, the |
---|
[2343] | 105 | optimising compiler should also return a map that assigns a cost (in clock |
---|
[2340] | 106 | cycles) to every instruction in the source program. We expect the induced cost |
---|
| 107 | to be preserved by the compiler: we will prove that the compiled code |
---|
| 108 | tightly simulates the source code by taking exactly the predicted amount of |
---|
| 109 | time. |
---|
[2052] | 110 | |
---|
[2340] | 111 | Note that the temporal tightness of the simulation is a fundamental prerequisite |
---|
[2357] | 112 | of the correctness of the simulation because some functions of the MCS-51---timers and I/O---depend on the microprocessor's clock. |
---|
[2346] | 113 | If the pseudo- and concrete clock differ the result of an I/O operation may not be preserved. |
---|
[2052] | 114 | |
---|
[2340] | 115 | Branch displacement algorithms must have a deep knowledge of the way |
---|
| 116 | the rest of the assembler works in order to build globally correct solutions. |
---|
| 117 | Proving their correctness is quite a complex task (see, for instance, |
---|
| 118 | the compaion paper~\cite{boender:correctness:2012}). |
---|
| 119 | Nevertheless, the correctness of the whole assembler only depends on the |
---|
| 120 | correctness of the branch displacement algorithm. |
---|
[2346] | 121 | Therefore, in the rest of the paper, we presuppose the |
---|
[2340] | 122 | existence of a correct policy, to be computed by a branch displacement |
---|
| 123 | algorithm if it exists. A policy is the decision over how |
---|
| 124 | any particular jump should be expanded; it is correct when the global |
---|
| 125 | constraints are satisfied. |
---|
[2346] | 126 | The assembler fails to assemble an assembly program if and only if a correct policy does not exist. |
---|
| 127 | 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] | 128 | |
---|
[2343] | 129 | The final complication in the proof of correctness of our optimising assembler |
---|
[2346] | 130 | is due to the kind of semantics associated to pseudo-assembly programs. |
---|
[2341] | 131 | Should assembly programs be allowed to freely manipulate addresses? The |
---|
| 132 | answer to the question deeply affects the proof of correctness. |
---|
| 133 | The traditional answer is no: values stored in memory or registers are either |
---|
| 134 | concrete data or symbolic addresses. The latters can be manipulated only |
---|
| 135 | in very restrictive ways and many programs that do not do so, for malign or |
---|
| 136 | benign reasons, are not assigned a semantics and cannot be reasoned about. |
---|
| 137 | All programs that have a semantics have it preserved by the compiler. |
---|
| 138 | Instead we took a different, novel approach: we allow programs to freely |
---|
| 139 | manipulate |
---|
| 140 | addresses non symbolically, but we only grant preservation of the semantics |
---|
| 141 | for those programs that do behave in a correct, anticipated way. At least |
---|
| 142 | in principle, this should allow some reasoning on the actual semantics of |
---|
| 143 | malign programs. In practice, we note how the alternative approach allows |
---|
| 144 | more code reusal between the semantics of assembly code and object code, |
---|
[2346] | 145 | with benefits on the size of the formalisation. |
---|
[2052] | 146 | |
---|
[2357] | 147 | The rest of this paper is a detailed description of our proof that is marginally still a work in progress. |
---|
[2052] | 148 | In Section~\ref{sect.matita} we provide a brief overview of the Matita proof assistant for the unfamiliar reader. |
---|
| 149 | In Section~\ref{sect.the.proof} we discuss the design and implementation of the proof proper. |
---|
| 150 | In Section~\ref{sect.conclusions} we conclude. |
---|
| 151 | |
---|
| 152 | % ---------------------------------------------------------------------------- % |
---|
| 153 | % SECTION % |
---|
| 154 | % ---------------------------------------------------------------------------- % |
---|
| 155 | \section{Matita} |
---|
| 156 | \label{sect.matita} |
---|
| 157 | |
---|
| 158 | Matita is a proof assistant based on a variant of the Calculus of (Co)inductive Constructions~\cite{asperti:user:2007}. |
---|
[2358] | 159 | It features dependent types that we exploit in the formalisation. |
---|
| 160 | The (simplified) syntax of the statements and definitions in the paper should be self-explanatory. |
---|
[2052] | 161 | Pairs are denoted with angular brackets, $\langle-, -\rangle$. |
---|
| 162 | |
---|
| 163 | Matita features a liberal system of coercions. |
---|
| 164 | 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$. |
---|
| 165 | The coercion opens a proof obligation that asks the user to prove that $P$ holds for $x$. |
---|
| 166 | 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 |
---|
| 167 | 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$. |
---|
| 168 | 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. |
---|
[2346] | 169 | 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. |
---|
[2052] | 170 | |
---|
[2349] | 171 | Throughout this paper we simplify the statements of lemmas and types of definitions in order to emphasise readability. |
---|
| 172 | |
---|
[2052] | 173 | % ---------------------------------------------------------------------------- % |
---|
| 174 | % SECTION % |
---|
| 175 | % ---------------------------------------------------------------------------- % |
---|
| 176 | \section{The proof} |
---|
| 177 | \label{sect.the.proof} |
---|
| 178 | |
---|
[2345] | 179 | The aim of the section is to explain the main ideas and steps of the certified |
---|
[2347] | 180 | proof of correctness for an optimizing assembler for the MCS-51. The |
---|
[2346] | 181 | formalisation is available at~\url{http://cerco.cs.unibo.it}. |
---|
[2345] | 182 | |
---|
[2348] | 183 | In Section~\ref{subsect.machine.code.semantics} we sketch an operational semantics (a realistic and efficient emulator) for the MCS-51. |
---|
| 184 | We also introduce a syntax for decoded instructions that will be reused for the assembly language. |
---|
[2345] | 185 | |
---|
[2348] | 186 | In Section~\ref{subsect.assembly.code.semantics} we describe the assembly language and its operational semantics. |
---|
| 187 | The latter is parametric in the cost model that will be induced by the assembler. |
---|
| 188 | It reuses the semantics of the machine code on all `real' (i.e. non-pseudo-) instructions. |
---|
[2345] | 189 | |
---|
[2346] | 190 | Branch displacement policies are introduced in Section~\ref{subsect.the.assembler} where we also describe the assembler as a function over policies as previously described. |
---|
[2345] | 191 | |
---|
[2348] | 192 | The proof of correctness of the assembler consists in showing that the object code given in output, together with a cost model for the source program, simulates the source program executed using that cost model. |
---|
| 193 | The proof can be divided into two main lemmas. |
---|
| 194 | The first is correctness with respect to fetching, described in Section~\ref{subsect.total.correctness.of.the.assembler}. |
---|
| 195 | It roughly states that one step of fetching at the assembly level that returns the decoded instruction $I$ is simulated by $n$ steps of fetching at the object level that returns instructions $J_1,\ldots,J_n$, where $J_1,\ldots,J_n$ is, amongst the possible expansions of $I$, the one picked by the policy. |
---|
| 196 | The second lemma shows that $J_1,\ldots,J_n$ simulates $I$ but only if $I$ is well-behaved, i.e. it manipulates addresses in ways that are anticipated in the correctness proof. |
---|
| 197 | To keep track of well-behaved address manipulations, we couple the assembly status with a map that records where addresses are currently stored in memory or in the processor's accumulators. |
---|
[2356] | 198 | We then introduce a dynamic checking function that inspects the assembly status and this map to determine if the operation is well-behaved. |
---|
[2348] | 199 | An affirmative answer is the pre-condition of the lemma. |
---|
[2356] | 200 | The second lemma is detailed in Section~\ref{subsect.total.correctness.for.well.behaved.assembly.programs} where we also establish correctness of our assembler as a composition of the two lemmas: programs that are well-behaved when executed under the cost model induced by the compiler are correctly simulated by the compiled code. |
---|
[2345] | 201 | |
---|
[2066] | 202 | % ---------------------------------------------------------------------------- % |
---|
| 203 | % SECTION % |
---|
| 204 | % ---------------------------------------------------------------------------- % |
---|
[2052] | 205 | |
---|
[2354] | 206 | \subsection{Machine code and its semantics} |
---|
[2066] | 207 | \label{subsect.machine.code.semantics} |
---|
| 208 | |
---|
[2354] | 209 | We implemented a realistic and efficient emulator for the MCS-51 microprocessor. |
---|
| 210 | An MCS-51 program is just a sequence of bytes stored in the read-only code |
---|
| 211 | memory of the processor, represented as a compact trie of bytes addressed |
---|
| 212 | by the program counter. |
---|
| 213 | The \texttt{Status} of the emulator is described as |
---|
| 214 | a record that contains the microprocessor's program counter, registers, stack |
---|
| 215 | pointer, clock, special function registers, code memory, and so on. |
---|
| 216 | The value of the code memory is a parameter of the record since it is not |
---|
| 217 | changed during execution. |
---|
[2052] | 218 | |
---|
[2354] | 219 | The \texttt{Status} records is itself an instance of a more general |
---|
| 220 | datatype \texttt{PreStatus} that abstracts over the implementation of code |
---|
| 221 | memory in order to reuse the same datatype for the semantics of the assembly |
---|
| 222 | language in the next section. |
---|
| 223 | |
---|
| 224 | The execution of a single instruction is performed by the \texttt{execute\_1} |
---|
| 225 | function, parametric over the content \texttt{cm} of the code memory: |
---|
[2052] | 226 | \begin{lstlisting} |
---|
[2346] | 227 | definition execute_1: $\forall$cm. Status cm $\rightarrow$ Status cm |
---|
[2052] | 228 | \end{lstlisting} |
---|
[2354] | 229 | |
---|
| 230 | The function \texttt{execute\_1} closely matches the fetch-decode-execute |
---|
| 231 | cycle of the MCS-51 hardware, as described by a Siemen's manufacturer's data sheet~\cite{siemens:2011}. |
---|
| 232 | Fetching and decoding are performed simultaneously: |
---|
| 233 | 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 to decode the arguments. |
---|
| 234 | Decoded instructions are represented by the \texttt{instruction} data type |
---|
| 235 | which extends a data type of \texttt{preinstruction}s that will be reused |
---|
| 236 | for the assembly language. |
---|
[2066] | 237 | \begin{lstlisting} |
---|
| 238 | inductive preinstruction (A: Type[0]): Type[0] := |
---|
[2083] | 239 | | ADD: $\llbracket$acc_a$\rrbracket$ → $\llbracket$registr; direct; indirect; data$\rrbracket$ $\rightarrow$ preinstruction A |
---|
[2339] | 240 | | DEC: $\llbracket$acc_a; registr; direct; indirect$\rrbracket$ $\rightarrow$ preinstruction A |
---|
[2083] | 241 | | JB: $\llbracket$bit_addr$\rrbracket$ $\rightarrow$ A $\rightarrow$ preinstruction A |
---|
[2066] | 242 | | ... |
---|
| 243 | |
---|
[2083] | 244 | inductive instruction: Type[0] := |
---|
| 245 | | LCALL: $\llbracket$addr16$\rrbracket$ $\rightarrow$ instruction |
---|
| 246 | | AJMP: $\llbracket$addr11$\rrbracket$ $\rightarrow$ instruction |
---|
| 247 | | RealInstruction: preinstruction $\llbracket$relative$\rrbracket$ $\rightarrow$ instruction. |
---|
| 248 | | ... |
---|
[2066] | 249 | \end{lstlisting} |
---|
[2354] | 250 | The MCS-51 has many operand modes, but an unorthogonal instruction set: every |
---|
| 251 | opcode is only enable for a finite subset of the possible operand modes. |
---|
| 252 | Here we exploit dependent types and an implicit coercion to synthesize |
---|
| 253 | the type of arguments of opcodes from a vector of names of operand modes. |
---|
| 254 | For example, \texttt{ACC} has two operands, the first one constrained to be |
---|
| 255 | the \texttt{A} accumulator, and the second one to be a disjoint union of |
---|
| 256 | register, direct, indirect and data operand modes. |
---|
[2066] | 257 | |
---|
[2354] | 258 | The parameterised type $A$ of \texttt{preinstruction} represents the addressing mode allowed for conditional jumps; in the \texttt{RealInstruction} constructor |
---|
| 259 | we constraint it to be a relative offset. A different instantiation will be |
---|
| 260 | used in the next Section for assembly programs. |
---|
| 261 | |
---|
[2066] | 262 | Once decoded, execution proceeds by a case analysis on the decoded instruction, following the operation of the hardware. |
---|
[2354] | 263 | For example, the \texttt{DEC} preinstruction (`decrement') is executed as follows: |
---|
[2066] | 264 | \begin{lstlisting} |
---|
[2083] | 265 | | DEC addr $\Rightarrow$ |
---|
| 266 | let s := add_ticks1 s in |
---|
[2346] | 267 | let $\langle$result, flags$\rangle$ := sub_8_with_carry (get_arg_8 s true addr) |
---|
[2083] | 268 | (bitvector_of_nat 8 1) false in |
---|
[2346] | 269 | set_arg_8 s addr result |
---|
[2066] | 270 | \end{lstlisting} |
---|
| 271 | |
---|
[2354] | 272 | Here, \texttt{add\_ticks1} models the incrementing of the internal clock of the microprocessor; it is a parameter of the semantics of \texttt{preinstruction}s |
---|
| 273 | that is fixed in the semantics of \texttt{instruction}s according to the |
---|
| 274 | manufacturer datasheet. |
---|
[2066] | 275 | |
---|
| 276 | % ---------------------------------------------------------------------------- % |
---|
| 277 | % SECTION % |
---|
| 278 | % ---------------------------------------------------------------------------- % |
---|
| 279 | |
---|
[2354] | 280 | \subsection{Assembly code and its semantics} |
---|
[2066] | 281 | \label{subsect.assembly.code.semantics} |
---|
| 282 | |
---|
[2087] | 283 | 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). |
---|
[2354] | 284 | All preinstructions are pseudoinstructions, but conditional jumps are now |
---|
| 285 | only allowed to use \texttt{Identifiers} (labels) as their target. |
---|
[2066] | 286 | \begin{lstlisting} |
---|
[2083] | 287 | inductive pseudo_instruction: Type[0] := |
---|
| 288 | | Instruction: preinstruction Identifier $\rightarrow$ pseudo_instruction |
---|
[2066] | 289 | ... |
---|
[2083] | 290 | | Jmp: Identifier $\rightarrow$ pseudo_instruction |
---|
| 291 | | Call: Identifier $\rightarrow$ pseudo_instruction |
---|
| 292 | | Mov: $\llbracket$dptr$\rrbracket$ $\rightarrow$ Identifier $\rightarrow$ pseudo_instruction. |
---|
[2066] | 293 | \end{lstlisting} |
---|
| 294 | 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. |
---|
[2354] | 295 | The object code calls and jumps that act on concrete memory addresses are ruled |
---|
[2359] | 296 | out of assembly programs not being included in the preinstructions (see previous |
---|
[2354] | 297 | Section). |
---|
[2066] | 298 | |
---|
[2348] | 299 | Execution of pseudoinstructions is an endofunction on \texttt{PseudoStatus}. |
---|
[2354] | 300 | A \texttt{PseudoStatus} is an instance of \texttt{PreStatus} that differs |
---|
| 301 | from a \texttt{Status} only in the datatype used for code memory: a list |
---|
| 302 | of optionally labelled pseudoinstructions versus a trie of bytes. |
---|
| 303 | The \texttt{PreStatus} type is crucial for sharing the majority of the |
---|
| 304 | semantics of the two languages. |
---|
[2052] | 305 | |
---|
[2066] | 306 | Emulation for pseudoinstructions is handled by \texttt{execute\_1\_pseudo\_instruction}: |
---|
[2052] | 307 | \begin{lstlisting} |
---|
[2058] | 308 | definition execute_1_pseudo_instruction: |
---|
[2359] | 309 | $\forall$cm. $\forall$costing:($\forall$ppc: Word. ppc < $\mid$snd cm$\mid$ $\rightarrow$ nat $\times$ nat). |
---|
| 310 | $\forall$s:PseudoStatus cm. program_counter s < $\mid$snd cm$\mid$ $\rightarrow$ PseudoStatus cm |
---|
[2052] | 311 | \end{lstlisting} |
---|
[2354] | 312 | The type of \texttt{execute\_1\_pseudo\_instruction} is more involved than |
---|
| 313 | that of \texttt{execute\_1}. The first difference is that execution is only |
---|
| 314 | defined when the program counter points to a valid instruction, i.e. |
---|
| 315 | it is smaller than the length $\mid$\texttt{snd cm}$\mid$ of the program. |
---|
| 316 | The second difference is the abstraction over the cost model, abbreviated |
---|
| 317 | here as \emph{costing}. |
---|
| 318 | The costing is a function that maps valid program counters to pairs of natural numbers representing the number of clock ticks used by the pseudoinstructions stored at those program counters. For conditional jumps the two numbers differ |
---|
| 319 | to represent different costs for the `true branch' and the `false branch'. |
---|
| 320 | In the next Section we will see how the optimizing |
---|
| 321 | assembler induces the only costing that is preserved by compilation. |
---|
| 322 | Obviously the induced costing is determined by the branch displacement policy |
---|
| 323 | that decides how to expand every pseudojump to a label into concrete |
---|
| 324 | instructions. |
---|
[2052] | 325 | |
---|
[2066] | 326 | Execution proceeds by first fetching from pseudo-code memory using the program counter---treated as an index into the pseudoinstruction list. |
---|
[2339] | 327 | This index is always guaranteed to be within the bounds of the pseudoinstruction list due to the dependent type placed on the function. |
---|
[2066] | 328 | No decoding is required. |
---|
| 329 | 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. |
---|
| 330 | For all newly introduced pseudoinstructions, we simply translate labels to concrete addresses before behaving as a `real' instruction. |
---|
| 331 | |
---|
| 332 | 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. |
---|
| 333 | Labels are immediately translated to concrete addresses, and registers and memory locations only ever contain bytes, never labels. |
---|
| 334 | 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. |
---|
[2359] | 335 | The only limitation introduced by this approach is that the size of |
---|
| 336 | assembly programs is bounded by $2^16$. |
---|
[2066] | 337 | This will be further discussed in Subsection~\ref{subsect.total.correctness.for.well.behaved.assembly.programs}. |
---|
| 338 | |
---|
| 339 | % ---------------------------------------------------------------------------- % |
---|
| 340 | % SECTION % |
---|
| 341 | % ---------------------------------------------------------------------------- % |
---|
| 342 | |
---|
| 343 | \subsection{The assembler} |
---|
| 344 | \label{subsect.the.assembler} |
---|
| 345 | |
---|
| 346 | Conceptually the assembler works in two passes. |
---|
[2359] | 347 | The first pass expands every pseudoinstruction into a list of machine code instructions using the function \texttt{expand\_pseudo\_instruction}. |
---|
[2066] | 348 | 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. |
---|
[2359] | 349 | The program obtained as a list of bytes is ready to be loaded in code memory |
---|
| 350 | for execution. |
---|
[2052] | 351 | \begin{displaymath} |
---|
[2359] | 352 | \hspace{-0.5cm} |
---|
| 353 | \mbox{\fontsize{7}{9}\selectfont$[\mathtt{P_1}, \ldots \mathtt{P_n}]$} \underset{\mbox{\fontsize{7}{9}\selectfont$\mathtt{assembly}$}}{\xrightarrow{\left(P_i \underset{\mbox{\fontsize{7}{9}\selectfont$\mathtt{assembly\_1\_pseudo\_instruction}$}}{\xrightarrow{\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]}}} \mathtt{[0110]}\right)^{*}}} \mbox{\fontsize{7}{9}\selectfont$\mathtt{[\ldots0110\ldots]}$} |
---|
[2052] | 354 | \end{displaymath} |
---|
[2092] | 355 | 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] | 356 | The function \texttt{assembly\_1\_pseudo\_instruction} used in the body of the paper is essentially the composition of the two passes. |
---|
[2052] | 357 | |
---|
[2327] | 358 | The branch displacement problem refers to the task of expanding pseudojumps into their concrete counterparts, preferably as efficiently as possible. |
---|
[2066] | 359 | 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}. |
---|
| 360 | 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. |
---|
| 361 | 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. |
---|
| 362 | |
---|
| 363 | Similarly, a conditional pseudojump must be translated potentially into a configuration of machine code instructions, depending on the distance to the jump's target. |
---|
| 364 | 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'): |
---|
| 365 | {\small{ |
---|
| 366 | \begin{displaymath} |
---|
| 367 | \begin{array}{r@{\quad}l@{\;\;}l@{\qquad}c@{\qquad}l@{\;\;}l} |
---|
| 368 | & \mathtt{JZ} & \mathtt{label} & & \mathtt{JZ} & \text{size of \texttt{SJMP} instruction} \\ |
---|
| 369 | & \ldots & & \text{translates to} & \mathtt{SJMP} & \text{size of \texttt{LJMP} instruction} \\ |
---|
| 370 | \mathtt{label:} & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} & \Longrightarrow & \mathtt{LJMP} & \text{address of \textit{label}} \\ |
---|
| 371 | & & & & \ldots & \\ |
---|
| 372 | & & & & \mathtt{MOV} & \mathtt{A}\;\;\mathtt{B} |
---|
| 373 | \end{array} |
---|
| 374 | \end{displaymath}}} |
---|
| 375 | Here, if \texttt{JZ} fails, we fall through to the \texttt{SJMP} which jumps over the \texttt{LJMP}. |
---|
| 376 | 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. |
---|
| 377 | |
---|
| 378 | In order to implement branch displacement it is impossible to really make the \texttt{expand\_pseudo\_instruction} function completely independent of the encoding function. |
---|
| 379 | This is due to branch displacement requiring the distance in bytes of the target of the jump. |
---|
| 380 | 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. |
---|
| 381 | 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. |
---|
| 382 | 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'. |
---|
| 383 | |
---|
| 384 | \begin{lstlisting} |
---|
| 385 | definition expand_pseudo_instruction: |
---|
| 386 | $\forall$lookup_labels: Identifier $\rightarrow$ Word. |
---|
[2349] | 387 | $\forall$policy. |
---|
[2066] | 388 | $\forall$ppc: Word. |
---|
| 389 | $\forall$lookup_datalabels: Identifier $\rightarrow$ Word. |
---|
| 390 | $\forall$pi: pseudo_instruction. |
---|
| 391 | list instruction := ... |
---|
| 392 | \end{lstlisting} |
---|
| 393 | 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. |
---|
| 394 | The input \texttt{pi} is the pseudoinstruction to be expanded and is found at address \texttt{ppc} in the assembly program. |
---|
[2349] | 395 | The function takes \texttt{policy} as an input. |
---|
| 396 | In reality, this is a pair of functions, but for the purposes of this paper we simplify. |
---|
| 397 | The \texttt{policy} 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{policy(a)}. |
---|
[2066] | 398 | 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. |
---|
| 399 | \begin{displaymath} |
---|
[2349] | 400 | \texttt{policy}(\texttt{ppc} + 1) = \texttt{pc} + \texttt{current\_instruction\_size} |
---|
[2066] | 401 | \end{displaymath} |
---|
| 402 | Here, \texttt{current\_instruction\_size} is the size in bytes of the encoding of the expanded pseudoinstruction found at \texttt{ppc}. |
---|
[2083] | 403 | 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; |
---|
| 404 | 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] | 405 | 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] | 406 | |
---|
[2349] | 407 | The \texttt{expand\_pseudo\_instruction} function uses the \texttt{policy} 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. |
---|
| 408 | 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 = policy(a) - policy(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}. |
---|
[2083] | 409 | A global best solution to the branch displacement problem, however, is not always made of locally best solutions. |
---|
| 410 | Therefore, in some circumstances, it is necessary to force the assembler to expand jumps into larger ones. |
---|
[2349] | 411 | This is achieved by another boolean-valued function such that if the function applied to \texttt{ppc} returns true then a \texttt{Jmp l} at address \texttt{ppc} is always translated to a long jump. |
---|
[2083] | 412 | An essentially identical mechanism exists for call instructions. |
---|
[2066] | 413 | |
---|
[2052] | 414 | % ---------------------------------------------------------------------------- % |
---|
| 415 | % SECTION % |
---|
| 416 | % ---------------------------------------------------------------------------- % |
---|
| 417 | \subsection{Correctness of the assembler with respect to fetching} |
---|
| 418 | \label{subsect.total.correctness.of.the.assembler} |
---|
[2355] | 419 | Using our policies, we now work toward proving the correctness of the assembler. |
---|
[2356] | 420 | Correctness means 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] | 421 | |
---|
[2351] | 422 | 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{policy ppc} in the code memory obtained by loading the assembled object code. |
---|
[2083] | 423 | 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] | 424 | |
---|
[2083] | 425 | The \texttt{assembly} function is given a Russell type (slightly simplified here): |
---|
[2052] | 426 | \begin{lstlisting} |
---|
[2083] | 427 | definition assembly: |
---|
[2339] | 428 | $\forall$program: pseudo_assembly_program. |
---|
| 429 | $\forall$policy. |
---|
| 430 | $\Sigma$assembled: list Byte $\times$ (BitVectorTrie costlabel 16). |
---|
| 431 | policy is correct for program $\rightarrow$ |
---|
[2342] | 432 | $\mid$program$\mid$ < $2^{16}$ $\rightarrow$ $\mid$fst assembled$\mid$ < $2^{16}$ $\wedge$ |
---|
| 433 | (policy ($\mid$program$\mid$) = $\mid$fst assembled$\mid$ $\vee$ |
---|
| 434 | (policy ($\mid$program$\mid$) = 0 $\wedge$ $\mid$fst assembled$\mid$ = $2^{16}$)) $\wedge$ |
---|
| 435 | $\forall$ppc: pseudo_program_counter. ppc < $2^{16}$ $\rightarrow$ |
---|
[2339] | 436 | let pseudo_instr := fetch from program at ppc in |
---|
| 437 | let assembled_i := assemble pseudo_instr in |
---|
| 438 | $\mid$assembled_i$\mid$ $\leq$ $2^{16}$ $\wedge$ |
---|
[2342] | 439 | $\forall$n: nat. n < $\mid$assembled_i$\mid$ $\rightarrow$ $\exists$k: nat. |
---|
[2339] | 440 | nth assembled_i n = nth assembled (policy ppc + k). |
---|
[2052] | 441 | \end{lstlisting} |
---|
[2327] | 442 | In plain words, the type of \texttt{assembly} states the following. |
---|
[2349] | 443 | Suppose we are given a policy that is correct for the program we are assembling. |
---|
| 444 | Then we return a list of assembled bytes, complete with a map from program counters to cost labels, such that the following properties hold for the list of bytes. |
---|
| 445 | Under the condition that the policy is `correct' for the program and the program is fully addressable by a 16-bit word, the assembled list is also fully addressable by a 16-bit word, the policy maps the last program counter that can address the program to the last instruction of the assemble pseudoinstruction or overflows, and if we fetch from the pseudo-program counter \texttt{ppc} we get a pseudoinstruction \texttt{pi} and a new pseudo-program counter \texttt{ppc}. |
---|
| 446 | Further, assembling the pseudoinstruction \texttt{pseudo\_instr} results in a list of bytes, \texttt{assembled\_i}. |
---|
| 447 | Then, indexing into this list with any natural number \texttt{n} less than the length of \texttt{assembled\_i} gives the same result as indexing into \texttt{assembled} with \texttt{policy ppc} (the program counter pointing to the start of the expansion in \texttt{assembled}) plus \texttt{k}. |
---|
[2052] | 448 | |
---|
[2087] | 449 | Essentially the lemma above states that the \texttt{assembly} function correctly expands pseudoinstructions, and that the expanded instruction reside consecutively in memory. |
---|
[2083] | 450 | 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}. |
---|
| 451 | |
---|
[2058] | 452 | Lemma \texttt{fetch\_assembly} establishes that the \texttt{fetch} and \texttt{assembly1} functions interact correctly. |
---|
[2052] | 453 | 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: |
---|
| 454 | \begin{lstlisting} |
---|
[2058] | 455 | lemma fetch_assembly: |
---|
| 456 | $\forall$pc: Word. |
---|
| 457 | $\forall$i: instruction. |
---|
| 458 | $\forall$code_memory: BitVectorTrie Byte 16. |
---|
| 459 | $\forall$assembled: list Byte. |
---|
[2342] | 460 | assembled = assemble i $\rightarrow$ |
---|
| 461 | let len := $\mid$assembled$\mid$ in |
---|
| 462 | let pc_plus_len := pc + len in |
---|
| 463 | encoding_check pc pc_plus_len assembled $\rightarrow$ |
---|
| 464 | let $\langle$instr, pc', ticks$\rangle$ := fetch pc in |
---|
[2083] | 465 | instr = i $\wedge$ ticks = (ticks_of_instruction instr) $\wedge$ pc' = pc_plus_len. |
---|
[2052] | 466 | \end{lstlisting} |
---|
[2358] | 467 | We read \texttt{fetch\_assembly} as follows. |
---|
[2052] | 468 | 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] | 469 | 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. |
---|
| 470 | 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] | 471 | Or, in plainer words, assembling and then immediately fetching again gets you back to where you started. |
---|
| 472 | |
---|
[2349] | 473 | Lemma \texttt{fetch\_assembly\_pseudo} is obtained by composition of \texttt{expand\_pseudo\_instruction} and \texttt{assembly\_1\_pseudoinstruction}: |
---|
[2052] | 474 | \begin{lstlisting} |
---|
| 475 | lemma fetch_assembly_pseudo: |
---|
[2058] | 476 | $\forall$program: pseudo_assembly_program. |
---|
[2342] | 477 | $\forall$policy. |
---|
[2058] | 478 | $\forall$ppc. |
---|
| 479 | $\forall$code_memory. |
---|
| 480 | let $\langle$preamble, instr_list$\rangle$ := program in |
---|
| 481 | let pi := $\pi_1$ (fetch_pseudo_instruction instr_list ppc) in |
---|
[2342] | 482 | let pc := policy ppc in |
---|
[2349] | 483 | let instrs := expand_pseudo_instructio policy ppc pi in |
---|
| 484 | let $\langle$l, a$\rangle$ := assembly_1_pseudoinstruction policy ppc pi in |
---|
[2342] | 485 | let pc_plus_len := pc + l in |
---|
[2058] | 486 | encoding_check code_memory pc pc_plus_len a $\rightarrow$ |
---|
| 487 | fetch_many code_memory pc_plus_len pc instructions. |
---|
[2052] | 488 | \end{lstlisting} |
---|
[2058] | 489 | Here, \texttt{l} is the number of machine code instructions the pseudoinstruction at hand has been expanded into. |
---|
[2087] | 490 | We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{expand\_pseudo\_instruction}. |
---|
[2052] | 491 | The function \texttt{fetch\_many} fetches multiple machine code instructions from code memory and performs some routine checks. |
---|
| 492 | |
---|
| 493 | Intuitively, Lemma \texttt{fetch\_assembly\_pseudo} can be read as follows. |
---|
[2349] | 494 | Suppose we expand the pseudoinstruction at \texttt{ppc} with the policy, obtaining the list of machine code instructions \texttt{instrs}. |
---|
[2058] | 495 | Suppose we also assemble the pseudoinstruction at \texttt{ppc} to obtain \texttt{a}, a list of bytes. |
---|
[2052] | 496 | 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. |
---|
| 497 | |
---|
[2349] | 498 | 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: |
---|
[2052] | 499 | \begin{lstlisting} |
---|
| 500 | lemma fetch_assembly_pseudo2: |
---|
[2058] | 501 | $\forall$program. |
---|
[2342] | 502 | $\mid$snd program$\mid$ $\leq$ $2^{16}$ $\rightarrow$ |
---|
[2058] | 503 | $\forall$policy. |
---|
[2342] | 504 | policy is correct for program $\rightarrow$ |
---|
| 505 | $\forall$ppc. ppc < $\mid$snd program$\mid$ $\rightarrow$ |
---|
[2349] | 506 | let $\langle$labels, costs$\rangle$ := create_label_cost_map program in |
---|
[2351] | 507 | let $\langle$assembled, costs'$\rangle$ := $\pi_1$ (assembly program policy) in |
---|
[2058] | 508 | let cmem := load_code_memory assembled in |
---|
[2349] | 509 | let $\langle$pi, newppc$\rangle$ := fetch_pseudo_instruction program ppc in |
---|
[2342] | 510 | let instructions := expand_pseudo_instruction policy ppc pi in |
---|
| 511 | fetch_many cmem (policy newppc) (policy ppc) instructions. |
---|
[2052] | 512 | \end{lstlisting} |
---|
| 513 | |
---|
[2346] | 514 | Here we use $\pi_1$ to project the existential witness from the Russell-typed function \texttt{assembly}. |
---|
[2058] | 515 | |
---|
[2052] | 516 | We read \texttt{fetch\_assembly\_pseudo2} as follows. |
---|
[2349] | 517 | Suppose we are given an assembly program which can be addressed by a 16-bit word and a policy that is correct for this program. |
---|
[2058] | 518 | Suppose we are able to successfully assemble an assembly program using \texttt{assembly} and produce a code memory, \texttt{cmem}. |
---|
[2349] | 519 | 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{policy} to expand pseudoinstructions. |
---|
| 520 | The fetched sequence corresponds to the expansion, according to the policy, of the pseudoinstruction. |
---|
[2052] | 521 | |
---|
[2358] | 522 | At first, the lemma appears to immediately imply the correctness of the assembler, but 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] | 523 | In particular, the two semantics differ on instructions that \emph{could} directly manipulate program addresses. |
---|
| 524 | |
---|
| 525 | % ---------------------------------------------------------------------------- % |
---|
| 526 | % SECTION % |
---|
| 527 | % ---------------------------------------------------------------------------- % |
---|
[2356] | 528 | \subsection{Correctness for `well-behaved' assembly programs} |
---|
[2052] | 529 | \label{subsect.total.correctness.for.well.behaved.assembly.programs} |
---|
| 530 | |
---|
[2058] | 531 | The traditional approach to verifying the correctness of an assembler is to treat memory addresses as opaque structures that cannot be modified. |
---|
[2083] | 532 | 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: |
---|
| 533 | \begin{displaymath} |
---|
| 534 | \mathtt{Mem} : \mathtt{Addr} \rightarrow \mathtt{Bytes} + \mathtt{Addr} \qquad \llbracket - \rrbracket : \mathtt{Instr} \rightarrow \mathtt{Mem} \rightarrow \mathtt{option\ Mem} |
---|
| 535 | \end{displaymath} |
---|
| 536 | The semantics of a pseudoinstruction, $\llbracket - \rrbracket$, is given as a possibly failing function from pseudoinstructions and memory spaces to new memory spaces. |
---|
| 537 | 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. |
---|
| 538 | \begin{gather*} |
---|
| 539 | \llbracket \mathtt{ADD\ @A1\ @A2} \rrbracket^\mathtt{M} = \begin{cases} |
---|
| 540 | \mathtt{Byte\ b1},\ \mathtt{Byte\ b2} & \rightarrow \mathtt{Some}(\mathtt{M}\ \text{with}\ \mathtt{b1} + \mathtt{b2}) \\ |
---|
| 541 | -,\ \mathtt{Addr\ a} & \rightarrow \mathtt{None} \\ |
---|
| 542 | \mathtt{Addr\ a},\ - & \rightarrow \mathtt{None} |
---|
| 543 | \end{cases} |
---|
| 544 | \end{gather*} |
---|
| 545 | In contrast, in this paper we take a different approach. |
---|
| 546 | We trace memory locations (and, potentially, registers) that contain memory addresses. |
---|
[2087] | 547 | 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] | 548 | |
---|
[2058] | 549 | 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] | 550 | 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] | 551 | |
---|
[2358] | 552 | Our analogue of the semantic function above is merely a wrapper around the function that implements the semantics of machine code, paired with a function that keeps track of addresses. |
---|
| 553 | The semantics of pseudo- and machine code are then essentially shared. |
---|
[2087] | 554 | The only thing that changes at the assembly level is the presence of the new tracking function. |
---|
[2083] | 555 | |
---|
[2356] | 556 | 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] | 557 | We use an \texttt{internal\_pseudo\_address\_map} to trace addresses of code memory addresses in internal RAM: |
---|
[2052] | 558 | \begin{lstlisting} |
---|
[2342] | 559 | definition address_entry := upper_lower $\times$ Byte. |
---|
| 560 | |
---|
[2060] | 561 | definition internal_pseudo_address_map := |
---|
[2342] | 562 | (BitVectorTrie address_entry 7) $\times$ (BitVectorTrie address_entry 7) |
---|
| 563 | $\times$ (option address_entry). |
---|
[2052] | 564 | \end{lstlisting} |
---|
[2350] | 565 | Here, \texttt{upper\_lower} is a type isomorphic to the booleans denoting whether a byte value is the upper or lower byte of some 16-bit address. |
---|
| 566 | |
---|
[2060] | 567 | The implementation of \texttt{internal\_pseudo\_address\_map} is complicated by some peculiarities of the MCS-51's instruction set. |
---|
| 568 | Note here that all addresses are 16 bit words, but are stored (and manipulated) as 8 bit bytes. |
---|
| 569 | All \texttt{MOV} instructions in the MCS-51 must use the accumulator \texttt{A} as an intermediary, moving a byte at a time. |
---|
[2350] | 570 | The third 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 \texttt{upper\_lower} flag) complete with the corresponding source address in full. |
---|
| 571 | The first and second components, on the other hand, performs a similar task for the higher and lower external RAM. |
---|
| 572 | Again, we use our \texttt{upper\_lower} flag to describe whether a byte is the upper or lower component of a 16-bit address. |
---|
[2052] | 573 | |
---|
| 574 | 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] | 575 | A similar function exists for high internal RAM. |
---|
[2350] | 576 | Note that both RAM segments are indexed using addresses 7-bits long: |
---|
[2052] | 577 | \begin{lstlisting} |
---|
[2342] | 578 | definition low_internal_ram_of_pseudo_low_internal_ram: |
---|
| 579 | internal_pseudo_address_map $\rightarrow$ policy $\rightarrow$ BitVectorTrie Byte 7 |
---|
| 580 | $\rightarrow$ BitVectorTrie Byte 7. |
---|
[2052] | 581 | \end{lstlisting} |
---|
| 582 | |
---|
| 583 | Next, we are able to translate \texttt{PseudoStatus} records into \texttt{Status} records using \texttt{status\_of\_pseudo\_status}. |
---|
| 584 | Translating a \texttt{PseudoStatus}'s code memory requires we expand pseudoinstructions and then assemble to obtain a trie of bytes. |
---|
[2063] | 585 | This never fails, provided that our policy is correct: |
---|
[2052] | 586 | \begin{lstlisting} |
---|
[2058] | 587 | definition status_of_pseudo_status: |
---|
| 588 | internal_pseudo_address_map $\rightarrow$ $\forall$pap. $\forall$ps: PseudoStatus pap. |
---|
[2351] | 589 | $\forall$policy. Status (code_memory_of_pseudo_assembly_program pap policy) |
---|
[2052] | 590 | \end{lstlisting} |
---|
| 591 | |
---|
[2356] | 592 | 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. |
---|
[2052] | 593 | 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. |
---|
[2356] | 594 | It thus decides the membership of a strict subset of the set of well-behaved programs. |
---|
[2052] | 595 | \begin{lstlisting} |
---|
[2342] | 596 | definition next_internal_pseudo_address_map: internal_pseudo_address_map $\rightarrow$ |
---|
| 597 | $\forall$cm. (Identifier $\rightarrow$ PseudoStatus cm $\rightarrow$ Word) $\rightarrow$ $\forall$s: PseudoStatus cm. |
---|
| 598 | program_counter s < $2^{16}$ $\rightarrow$ option internal_pseudo_address_map |
---|
[2052] | 599 | \end{lstlisting} |
---|
[2350] | 600 | If we wished to allow `benign manipulations' of addresses, it would be this function that needs to be changed. |
---|
| 601 | Note we once again use dependent types to ensure that program counters are properly within bounds. |
---|
| 602 | The third argument is a function that resolves the concrete address of a label. |
---|
[2052] | 603 | |
---|
[2083] | 604 | 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] | 605 | The function returns a pair of natural numbers, needed for recording the execution times of each branch of a conditional jump. |
---|
| 606 | \begin{lstlisting} |
---|
[2083] | 607 | definition ticks_of0: |
---|
[2342] | 608 | pseudo_assembly_program $\rightarrow$ (Identifier $\rightarrow$ Word) $\rightarrow$ $\forall$policy. Word $\rightarrow$ |
---|
| 609 | pseudo_instruction $\rightarrow$ nat $\times$ nat |
---|
[2052] | 610 | \end{lstlisting} |
---|
[2083] | 611 | An additional function, \texttt{ticks\_of}, is merely a wrapper around this function. |
---|
[2052] | 612 | |
---|
| 613 | Finally, we are able to state and prove our main theorem. |
---|
[2058] | 614 | 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] | 615 | \begin{lstlisting} |
---|
| 616 | theorem main_thm: |
---|
[2058] | 617 | $\forall$M, M': internal_pseudo_address_map. |
---|
| 618 | $\forall$program: pseudo_assembly_program. |
---|
[2342] | 619 | $\forall$program_in_bounds: $\mid$program$\mid$ $\leq$ $2^{16}$. |
---|
| 620 | let maps := create_label_cost_map program in |
---|
| 621 | let addr_of := ... in |
---|
| 622 | program is well labelled $\rightarrow$ |
---|
| 623 | $\forall$policy. policy is correct for program. |
---|
| 624 | $\forall$ps: PseudoStatus program. ps < $\mid$program$\mid$. |
---|
| 625 | next_internal_pseudo_address_map M program ... = Some M' $\rightarrow$ |
---|
| 626 | $\exists$n. execute n (status_of_pseudo_status M ps policy) = |
---|
| 627 | status_of_pseudo_status M' |
---|
| 628 | (execute_1_pseudo_instruction program |
---|
| 629 | (ticks_of program ($\lambda$id. addr_of id ps) policy) ps) policy. |
---|
[2052] | 630 | \end{lstlisting} |
---|
| 631 | 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}. |
---|
[2358] | 632 | We explicitly require proof that the policy is correct, the program is well-labelled (i.e. no repeated labels, etc.) and the pseudo-program counter is in the program's bounds. |
---|
| 633 | Theorem \texttt{main\_thm} establishes the correctness of the assembly process and can be lifted to the forward simulation of an arbitrary number of well-behaved steps on the assembly program. |
---|
[2052] | 634 | |
---|
| 635 | % ---------------------------------------------------------------------------- % |
---|
| 636 | % SECTION % |
---|
| 637 | % ---------------------------------------------------------------------------- % |
---|
| 638 | \section{Conclusions} |
---|
| 639 | \label{sect.conclusions} |
---|
| 640 | |
---|
[2355] | 641 | We are proving the correctness of an assembler for MCS-51 assembly language. |
---|
[2358] | 642 | 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] | 643 | 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. |
---|
| 644 | |
---|
[2358] | 645 | The formalisation is a component of CerCo which aims to produce a verified concrete complexity preserving compiler for a large subset of the C language. |
---|
| 646 | 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 CerCo will build its verified compiler platform. |
---|
[2052] | 647 | |
---|
| 648 | It is interesting to compare our work to an `industrial grade' assembler for the MCS-51: SDCC~\cite{sdcc:2011}. |
---|
| 649 | SDCC is the only open source C compiler that targets the MCS-51 instruction set. |
---|
| 650 | 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. |
---|
| 651 | 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. |
---|
| 652 | However, this comes at the expense of assembler completeness: the generated program may be too large to fit into code memory. |
---|
| 653 | In this respect, there is a trade-off between the completeness of the assembler and the efficiency of the assembled program. |
---|
[2087] | 654 | 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] | 655 | |
---|
[2095] | 656 | 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. |
---|
[2352] | 657 | Of particular note is the verified seL4 kernel~\cite{klein:sel4:2009}. |
---|
[2052] | 658 | This verification explicitly assumes the existence of, amongst other things, a trustworthy assembler and compiler. |
---|
| 659 | |
---|
[2095] | 660 | Note that both CompCert, CompCertTSO and the seL4 formalisation assume the existence of `trustworthy' assemblers. |
---|
| 661 | For instance, the CompCert C compiler's backend stops at the PowerPC assembly language, in the default backend. |
---|
| 662 | 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] | 663 | 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. |
---|
| 664 | |
---|
[2060] | 665 | Our formalisation exploits dependent types in different ways and for multiple purposes. |
---|
| 666 | The first purpose is to reduce potential errors in the formalisation of the microprocessor. |
---|
[2358] | 667 | Dependent types are used to constrain the size of bitvectors and tries that represent memory quantities and memory areas respectively. |
---|
[2327] | 668 | 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] | 669 | 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] | 670 | |
---|
[2357] | 671 | The second purpose is to single out sources of incompleteness. |
---|
[2060] | 672 | 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] | 673 | 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] | 674 | |
---|
[2357] | 675 | 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}. |
---|
| 676 | 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. |
---|
| 677 | It would not be natural to see the proof that fetch and assembly commute as the specification of one of the two functions. |
---|
[2358] | 678 | \paragraph{Related work} |
---|
[2052] | 679 | % piton |
---|
[2355] | 680 | We are not the first to consider the correctness of an assembler for a non-trivial assembly language. |
---|
[2358] | 681 | The most impressive piece of work in this domain is Piton~\cite{moore:piton:1996}, 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---Lisp and $\mu$Gypsy~\cite{moore:grand:2005}. |
---|
[2052] | 682 | |
---|
| 683 | % jinja |
---|
[2352] | 684 | Klein and Nipkow consider a Java-like programming language, Jinja~\cite{klein:machine:2006}. |
---|
[2052] | 685 | 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. |
---|
| 686 | |
---|
| 687 | We believe some other verified assemblers exist in the literature. |
---|
| 688 | However, what sets our work apart from that above is our attempt to optimise the machine code generated by our assembler. |
---|
[2083] | 689 | 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] | 690 | 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. |
---|
| 691 | This is only possible by inducing a cost model on the source code from the optimisation strategy and input program. |
---|
| 692 | This will be a \emph{leit motif} of CerCo. |
---|
[2358] | 693 | \paragraph{Resources} |
---|
| 694 | Our source files are available at~\url{http://cerco.cs.unibo.it}. |
---|
| 695 | We assumed several properties of `library functions', e.g. modular arithmetic and datastructure manipulation. |
---|
| 696 | We axiomatised various small functions needed to complete the main theorems, as well as some `routine' proof obligations of the theorems themselves, in focussing on the main meat of the theorems. |
---|
| 697 | We believe that the proof strategy is sound and that we will be able to close all axioms, up to minor bugs that should have local fixes that do not affect the global proof strategy. |
---|
[2052] | 698 | |
---|
[2358] | 699 | The development, including the definition of the executable semantics of the MCS-51, is spread across 29 files, with around 18,500 lines of Matita source. |
---|
| 700 | The bulk of the proof is contained in a series of files, \texttt{AssemblyProof.ma}, \texttt{AssemblyProofSplit.ma} and \texttt{AssemblyProofSplitSplit.ma} consisting of approximately 4500 lines of Matita source. |
---|
[2060] | 701 | 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. |
---|
[2358] | 702 | The low ratio between source lines and the number of lines of proof is unusual, but justified by the fact that the pseudo-assembly and the assembly language share most constructs and large swathes of the semantics are shared. |
---|
| 703 | 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] | 704 | |
---|
[2053] | 705 | \bibliography{cpp-2012-asm.bib} |
---|
[2052] | 706 | |
---|
| 707 | \end{document}\renewcommand{\verb}{\lstinline} |
---|
| 708 | \def\lstlanguagefiles{lst-grafite.tex} |
---|
| 709 | \lstset{language=Grafite} |
---|