| 1 |
From Coq Require Import ZArith. |
| 2 |
From Coq Require Import Derive. |
| 3 |
From Coq Require Import Ascii. |
| 4 |
From Coq Require Import String. |
| 5 |
From Coq Require Import List. |
| 6 |
Require Import Crypto.Assembly.Syntax. |
| 7 |
Require Import Crypto.Assembly.Equality. |
| 8 |
Require Import Crypto.Util.OptionList. |
| 9 |
Require Import Crypto.Util.Strings.Parse.Common. |
| 10 |
Require Import Crypto.Util.Strings.ParseArithmetic. |
| 11 |
Require Import Crypto.Util.Strings.String. |
| 12 |
Require Crypto.Util.Strings.Ascii. |
| 13 |
Require Import Crypto.Util.Strings.Show. |
| 14 |
Require Import Crypto.Util.Strings.Show.Enum. |
| 15 |
Require Import Crypto.Util.Listable. |
| 16 |
Require Import Crypto.Util.ErrorT. |
| 17 |
Require Import Crypto.Util.ListUtil. |
| 18 |
Require Import Crypto.Util.Option. |
| 19 |
Require Import Crypto.Util.Sum. |
| 20 |
Import ListNotations. |
| 21 |
Local Open Scope bool_scope. |
| 22 |
Local Open Scope list_scope. |
| 23 |
Local Open Scope string_scope. |
| 24 |
Local Open Scope parse_scope. |
| 25 |
|
| 26 |
Global Instance show_REG : Show REG. |
| 27 |
Proof. prove_Show_enum (). Defined. |
| 28 |
Global Instance show_lvl_REG : ShowLevel REG := show_REG. |
| 29 |
|
| 30 |
Global Instance show_FLAG : Show FLAG. |
| 31 |
Proof. prove_Show_enum (). Defined. |
| 32 |
Global Instance show_lvl_FLAG : ShowLevel FLAG := show_FLAG. |
| 33 |
|
| 34 |
Global Instance show_OpCode : Show OpCode. |
| 35 |
Proof. prove_Show_enum (). Defined. |
| 36 |
Global Instance show_lvl_OpCode : ShowLevel OpCode := show_OpCode. |
| 37 |
|
| 38 |
Global Instance show_OpPrefix : Show OpPrefix. |
| 39 |
Proof. prove_Show_enum (). Defined. |
| 40 |
Global Instance show_lvl_OpPrefix : ShowLevel OpPrefix := show_OpPrefix. |
| 41 |
|
| 42 |
Definition parse_REG_list : list (string * REG) |
| 43 |
:= Eval vm_compute in |
| 44 |
List.map |
| 45 |
(fun r => (show r, r)) |
| 46 |
(list_all REG). |
| 47 |
|
| 48 |
Definition parse_REG : ParserAction REG |
| 49 |
:= parse_strs parse_REG_list. |
| 50 |
|
| 51 |
Definition parse_FLAG_list : list (string * FLAG) |
| 52 |
:= Eval vm_compute in |
| 53 |
List.map |
| 54 |
(fun r => (show r, r)) |
| 55 |
(list_all FLAG). |
| 56 |
|
| 57 |
Definition parse_FLAG : ParserAction FLAG |
| 58 |
:= parse_strs parse_FLAG_list. |
| 59 |
|
| 60 |
Global Instance show_AccessSize : Show AccessSize. |
| 61 |
Proof. prove_Show_enum (). Defined. |
| 62 |
Global Instance show_lvl_AccessSize : ShowLevel AccessSize := show_AccessSize. |
| 63 |
|
| 64 |
Definition parse_AccessSize_list : list (string * AccessSize) |
| 65 |
:= Eval vm_compute in |
| 66 |
List.map |
| 67 |
(fun r => (show r, r)) |
| 68 |
(list_all AccessSize). |
| 69 |
|
| 70 |
Definition parse_AccessSize : ParserAction AccessSize |
| 71 |
:= (parse_strs_casefold parse_AccessSize_list ;;L (casefold " ptr")?). |
| 72 |
|
| 73 |
|
| 74 |
(* Do we want to support anything else from the printable characters? |
| 75 |
!""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ *) |
| 76 |
(* According to https://www.nasm.us/xdoc/2.15.05/html/nasmdoc3.html: |
| 77 |
Valid characters in labels are letters, numbers, _, $, #, @, ~, ., and ?. The only characters which may be used as the first character of an identifier are letters, . (with special meaning: see section 3.9), _ and ?. An identifier may also be prefixed with a $ to indicate that it is intended to be read as an identifier and not a reserved word; thus, if some other module you are linking with defines a symbol called eax, you can refer to $eax in NASM code to distinguish the symbol from the register. Maximum length of an identifier is 4095 characters. *) |
| 78 |
Definition parse_label : ParserAction string |
| 79 |
:= let parse_any_ascii s := parse_alt_list (List.map parse_ascii (list_ascii_of_string s)) in |
| 80 |
parse_map |
| 81 |
(fun '(char, ls) => string_of_list_ascii (char :: ls)) |
| 82 |
(([a-zA-Z] || parse_any_ascii "._?$") ;; |
| 83 |
(([a-zA-Z] || parse_any_ascii "0123456789_$#@~.?")* )). |
| 84 |
|
| 85 |
Definition parse_non_access_size_label : ParserAction string |
| 86 |
:= parse_lookahead_not parse_AccessSize ;;R parse_label. |
| 87 |
|
| 88 |
Definition parse_rip_relative_kind : ParserAction rip_relative_kind |
| 89 |
:= parse_map (fun _ => explicitly_rip_relative) "rip". |
| 90 |
|
| 91 |
Definition parse_MEM {opts : assembly_program_options} : ParserAction MEM |
| 92 |
:= parse_option_list_map |
| 93 |
(fun '(access_size, (constant_location_label, (br (*base reg*), sr (*scale reg, including z *), offset, base_label, rip_relative))) |
| 94 |
=> match base_label, constant_location_label with |
| 95 |
| Some _, Some _ => (* invalid? *) None |
| 96 |
| Some _ as lbl, None |
| 97 |
| None, Some _ as lbl |
| 98 |
| None, None as lbl => |
| 99 |
Some |
| 100 |
{| mem_bits_access_size := access_size:option AccessSize |
| 101 |
; mem_base_reg := br:option REG |
| 102 |
; mem_base_label := lbl |
| 103 |
; mem_scale_reg := sr:option (Z * REG) |
| 104 |
; mem_offset := offset:option Z |
| 105 |
; rip_relative := rip_relative:rip_relative_kind |} |
| 106 |
end) |
| 107 |
(((strip_whitespace_after parse_AccessSize)?) ;; |
| 108 |
(parse_non_access_size_label?) ;; |
| 109 |
(parse_option_list_map |
| 110 |
(fun '(offset, vars) |
| 111 |
=> (vars <-- List.map (fun '(c, (v, e), vs) => match vs, e with [], 1%Z => Some (c, v) | _, _ => None end) vars; |
| 112 |
let regs : list (Z * (REG + rip_relative_kind)) := Option.List.map (fun '(c, v) => match v with inl v => Some (c, v) | inr _ => None end) vars in |
| 113 |
let labels : list (Z * string) := Option.List.map (fun '(c, v) => match v with inr v => Some (c, v) | inl _ => None end) vars in |
| 114 |
base_label <- match labels with |
| 115 |
| [] => Some None |
| 116 |
| [(1%Z, lbl)] => Some (Some lbl) |
| 117 |
| _ => None |
| 118 |
end; |
| 119 |
let offset := if (0 =? offset)%Z then None else Some offset in |
| 120 |
base_scale_reg <- match regs with |
| 121 |
| [] => Some (None, None) |
| 122 |
| [(1%Z, r)] => Some (Some r, None) |
| 123 |
| [(s, inl r)] => Some (None, Some (s, r)) |
| 124 |
| [(1%Z, r1); (s, inl r2)] |
| 125 |
| [(s, inl r2); (1%Z, r1)] |
| 126 |
=> Some (Some r1, Some (s, r2)) |
| 127 |
| _ => None |
| 128 |
end; |
| 129 |
let '(br, sr) := base_scale_reg in |
| 130 |
let rip_relative := match br with Some (inr k) => k | _ => if default_rel then implicitly_rip_relative else not_rip_relative end in |
| 131 |
let br := (br <- br; match br with inl br => Some br | inr _ => None end)%option in |
| 132 |
Some (br (*base reg*), sr (*scale reg, including z *), offset, base_label, rip_relative))%option) |
| 133 |
("[" ;;R parse_Z_poly_strict (sum_beq _ _ (sum_beq _ _ REG_beq rip_relative_kind_beq) String.eqb) (parse_or_else_gen (fun x => x) (parse_or_else_gen (fun x => x) parse_REG parse_rip_relative_kind) parse_label) ;;L "]"))). |
| 134 |
|
| 135 |
Definition parse_CONST (const_keyword : bool) : ParserAction CONST |
| 136 |
:= if const_keyword |
| 137 |
then "CONST " ;;R parse_Z_arith_strict ;;L parse_lookahead_not parse_one_whitespace |
| 138 |
else parse_lookahead_not parse_one_whitespace ;;R parse_Z_arith_strict ;;L parse_lookahead_not parse_one_whitespace. |
| 139 |
|
| 140 |
Definition parse_JUMP_LABEL : ParserAction JUMP_LABEL |
| 141 |
:= parse_map |
| 142 |
(fun '(near, lbl) |
| 143 |
=> {| jump_near := if near:option _ then true else false |
| 144 |
; label_name := lbl : string |
| 145 |
|}) |
| 146 |
((strip_whitespace_after "NEAR ")? ;; parse_label). |
| 147 |
|
| 148 |
(* we only parse something as a label if it cannot possibly be anything else, because asm is terrible and has ambiguous parses otherwise :-( *) |
| 149 |
Definition parse_ARG {opts : assembly_program_options} (const_keyword : bool) : ParserAction ARG |
| 150 |
:= parse_or_else |
| 151 |
(parse_alt_list |
| 152 |
[parse_map reg parse_REG |
| 153 |
; parse_map mem parse_MEM |
| 154 |
; parse_map const (parse_CONST const_keyword)]) |
| 155 |
(parse_map label parse_JUMP_LABEL). |
| 156 |
|
| 157 |
Definition parse_OpCode_list : list (string * OpCode) |
| 158 |
:= Eval vm_compute in |
| 159 |
List.map |
| 160 |
(fun r => (show r, r)) |
| 161 |
(list_all OpCode) |
| 162 |
++ [(".byte", db) |
| 163 |
; (".word", dw) |
| 164 |
; (".short", dw) |
| 165 |
; (".long", dd) |
| 166 |
; (".int", dd) |
| 167 |
; (".quad", dq)]. |
| 168 |
|
| 169 |
Definition parse_OpCode : ParserAction OpCode |
| 170 |
:= parse_strs_case_insensitive parse_OpCode_list. |
| 171 |
|
| 172 |
Definition parse_OpPrefix_list : list (string * OpPrefix) |
| 173 |
:= Eval vm_compute in |
| 174 |
List.map |
| 175 |
(fun r => (show r, r)) |
| 176 |
(list_all OpPrefix). |
| 177 |
|
| 178 |
Definition parse_OpPrefix : ParserAction OpPrefix |
| 179 |
:= parse_strs parse_OpPrefix_list. |
| 180 |
|
| 181 |
Definition chars_to_escape_list : list (string * ascii) |
| 182 |
:= Eval vm_compute in |
| 183 |
List.map |
| 184 |
(fun '(name, char) => (String name EmptyString, char)) |
| 185 |
[("b", Ascii.Backspace) |
| 186 |
; ("f", Ascii.FormFeed) |
| 187 |
; ("n", Ascii.LF) |
| 188 |
; ("r", Ascii.CR) |
| 189 |
; ("t", Ascii.HorizontalTab) |
| 190 |
; ("v", Ascii.VerticalTab) |
| 191 |
; ("""", """") |
| 192 |
; ("'", "'") |
| 193 |
; ("\", "\") |
| 194 |
; ("0", Ascii.Null) |
| 195 |
]%char. |
| 196 |
Definition parse_escaped_char : ParserAction ascii := |
| 197 |
"\" ;;R |
| 198 |
(parse_or_else |
| 199 |
(parse_map ascii_of_N |
| 200 |
(("x" ;;R parse_N_fixed_digits 16 false 2) |
| 201 |
|| (parse_N_fixed_digits 8 false 3))) |
| 202 |
(parse_strs chars_to_escape_list)). |
| 203 |
|
| 204 |
Definition should_escape (ch : ascii) : bool |
| 205 |
:= (List.existsb (Ascii.eqb ch) (List.map snd chars_to_escape_list)) |
| 206 |
|| negb (Ascii.is_printable ch). |
| 207 |
|
| 208 |
Definition escape_char (ch : ascii) : string := |
| 209 |
match List.find (fun '(escape_str, ch') => Ascii.eqb ch ch') chars_to_escape_list, should_escape ch with |
| 210 |
| Some (escape_str, _), _ => "\" ++ escape_str |
| 211 |
| None, true => |
| 212 |
let hex := Hex.show_N (Ascii.N_of_ascii ch) in |
| 213 |
let hex := String.substring 2 (String.length hex) hex in |
| 214 |
let hex := if (String.length hex <? 2)%nat then "0" ++ hex else hex in |
| 215 |
let hex := if (String.length hex <? 2)%nat then "0" ++ hex else hex in |
| 216 |
"\x" ++ hex |
| 217 |
| None, false => String ch EmptyString |
| 218 |
end%string. |
| 219 |
|
| 220 |
Definition escape_string (s : string) : string := |
| 221 |
String.concat "" (List.map escape_char (list_ascii_of_string s)). |
| 222 |
|
| 223 |
Definition unescape_string (s : string) : string := |
| 224 |
Option.value (finalize (parse_map string_of_list_ascii ( (parse_or_else parse_escaped_char (fun s => match s with EmptyString => [] | String char s => [(char, s)] end)* ))) s) s. |
| 225 |
|
| 226 |
|
| 227 |
(** assumes no leading nor trailing whitespace and no comment *) |
| 228 |
Definition parse_RawLine {opts : assembly_program_options} : ParserAction RawLine |
| 229 |
:= fun s => ( |
| 230 |
let s := String.trim s in |
| 231 |
(* get the first space-separated opcode *) |
| 232 |
let '(mnemonic, args) := String.take_while_drop_while (fun ch => negb (Ascii.is_whitespace ch)) s in |
| 233 |
let args := String.trim args in |
| 234 |
if (String.to_upper mnemonic =? "SECTION") || (String.to_upper mnemonic =? ".SECTION") |
| 235 |
then [(SECTION args, "")] |
| 236 |
else if (String.to_upper mnemonic =? "GLOBAL") || (String.to_upper mnemonic =? ".GLOBAL") || (String.to_upper mnemonic =? ".GLOBL") |
| 237 |
then [(GLOBAL args, "")] |
| 238 |
else if (String.to_upper mnemonic =? "ALIGN") || (String.to_upper mnemonic =? ".ALIGN") |
| 239 |
then [(ALIGN args, "")] |
| 240 |
else if (String.to_upper mnemonic =? "DEFAULT") && (String.to_upper args =? "REL") |
| 241 |
then [(DEFAULT_REL, "")] |
| 242 |
else if String.endswith ":" s |
| 243 |
then [(LABEL (substring 0 (pred (String.length s)) s), "")] |
| 244 |
else if (String.to_upper mnemonic =? ".ASCII") && (String.startswith """" args) && (String.endswith """" args) |
| 245 |
then [(ASCII (unescape_string (String.substring 1 (String.length args - 2) args)), "")] |
| 246 |
else if (String.to_upper mnemonic =? ".ASCIZ") && (String.startswith """" args) && (String.endswith """" args) |
| 247 |
then [(ASCIZ (unescape_string (String.substring 1 (String.length args - 2) args)), "")] |
| 248 |
else if (s =? "") |
| 249 |
then [(EMPTY, "")] |
| 250 |
else if (List.find (String.eqb (String.to_lower mnemonic)) |
| 251 |
[".addrsig" |
| 252 |
; ".addrsig_sym" |
| 253 |
; ".cfi_def_cfa" |
| 254 |
; ".cfi_def_cfa_offset" |
| 255 |
; ".cfi_def_cfa_register" |
| 256 |
; ".cfi_endproc" |
| 257 |
; ".cfi_offset" |
| 258 |
; ".cfi_startproc" |
| 259 |
; ".file" |
| 260 |
; ".ident" |
| 261 |
; ".intel_syntax" |
| 262 |
; ".loc" |
| 263 |
; ".p2align" |
| 264 |
; ".size" |
| 265 |
; ".text" |
| 266 |
; ".type" |
| 267 |
]) |
| 268 |
then [(DIRECTIVE s, "")] |
| 269 |
else let parsed_prefix := (parse_OpPrefix ;;L ε) mnemonic in |
| 270 |
List.flat_map |
| 271 |
(fun '(parsed_prefix, mnemonic, args) |
| 272 |
=> let parsed_mnemonic := (parse_OpCode ;;L ε) mnemonic in |
| 273 |
let parsed_args := (parse_list_gen "" "," "" (parse_ARG false) ;;L ε) args in |
| 274 |
List.flat_map |
| 275 |
(fun '(opc, _) |
| 276 |
=> List.map |
| 277 |
(fun '(argsv, _) => (INSTR {| prefix := parsed_prefix ; op := opc ; args := argsv |}, "")) |
| 278 |
parsed_args) |
| 279 |
parsed_mnemonic) |
| 280 |
match parsed_prefix with |
| 281 |
| [] |
| 282 |
=> [(None, mnemonic, args)] |
| 283 |
| _ |
| 284 |
=> List.map |
| 285 |
(fun '(parsed_prefix, _) |
| 286 |
=> let '(mnemonic, args) := String.take_while_drop_while (fun ch => negb (Ascii.is_whitespace ch)) args in |
| 287 |
let args := String.trim args in |
| 288 |
(Some parsed_prefix, mnemonic, args)) |
| 289 |
parsed_prefix |
| 290 |
end)%bool. |
| 291 |
|
| 292 |
Definition parse_Line {opts : assembly_program_options} (line_num : N) : ParserAction Line |
| 293 |
:= fun s |
| 294 |
=> let '(indentv, rest_linev) := take_while_drop_while Ascii.is_whitespace s in |
| 295 |
let '(precommentv, commentv) |
| 296 |
:= match String.split ";" rest_linev with |
| 297 |
| [] => ("", None) |
| 298 |
| [precommentv] => (String.rtrim precommentv, None) |
| 299 |
| precommentv::commentv => (precommentv, Some (String.concat ";" commentv)) |
| 300 |
end in |
| 301 |
let '(rev_trailing_whitespacev, rev_rawlinev) := take_while_drop_while Ascii.is_whitespace (String.rev precommentv) in |
| 302 |
let rawlinev := String.rev rev_rawlinev in |
| 303 |
let trailing_whitespacev := String.rev rev_trailing_whitespacev in |
| 304 |
List.map |
| 305 |
(fun '(r, rem) => ({| indent := indentv ; rawline := r ; pre_comment_whitespace := trailing_whitespacev ; comment := commentv ; line_number := line_num |}, rem)) |
| 306 |
(parse_RawLine rawlinev). |
| 307 |
|
| 308 |
(* the error is the unparsable lines *) |
| 309 |
Fixpoint parse_Lines' {opts : assembly_program_options} (l : list string) (line_num : N) : ErrorT (list string) Lines |
| 310 |
:= match l with |
| 311 |
| [] => Success [] |
| 312 |
| l :: ls |
| 313 |
=> let '(result, next_opts) := |
| 314 |
match finalize (@parse_Line opts line_num) l with |
| 315 |
| None => (None, opts) |
| 316 |
| Some result => |
| 317 |
(Some result, |
| 318 |
match result.(rawline) with |
| 319 |
| DEFAULT_REL => {| default_rel := true |} |
| 320 |
| _ => opts |
| 321 |
end) |
| 322 |
end in |
| 323 |
match result, @parse_Lines' next_opts ls (line_num + 1) with |
| 324 |
| None, Error ls => Error (("Line " ++ show line_num ++ ": " ++ l) :: ls) |
| 325 |
| None, Success _ => Error (("Line " ++ show line_num ++ ": " ++ l) :: nil) |
| 326 |
| Some _, Error ls => Error ls |
| 327 |
| Some l, Success ls => Success (l :: ls) |
| 328 |
end |
| 329 |
end. |
| 330 |
|
| 331 |
Definition parse_Lines {opts : assembly_program_options} (l : list string) : ErrorT (list string) Lines |
| 332 |
:= parse_Lines' (String.split_newlines l) 1. |
| 333 |
|
| 334 |
#[export] Instance default_assembly_program_options : assembly_program_options |
| 335 |
:= {| default_rel := false |}. |
| 336 |
|
| 337 |
Notation parse := (@parse_Lines default_assembly_program_options) (only parsing). |
| 338 |
|
| 339 |
Global Instance show_lvl_MEM : ShowLevel MEM |
| 340 |
:= fun m |
| 341 |
=> (match m.(mem_bits_access_size) with |
| 342 |
| Some n |
| 343 |
=> show_lvl_app (fun 'tt => if n =? 8 then "byte" |
| 344 |
else if n =? 16 then "word" |
| 345 |
else if n =? 32 then "dword" |
| 346 |
else if n =? 64 then "QWORD PTR" |
| 347 |
else if n =? 128 then "XMMWORD PTR" |
| 348 |
else if n =? 256 then "YMMWORD PTR" |
| 349 |
else if n =? 512 then "ZMMWORD PTR" |
| 350 |
else "BAD SIZE")%N (* TODO: Fix casing and stuff *) |
| 351 |
| None => show_lvl |
| 352 |
end) |
| 353 |
(fun 'tt |
| 354 |
=> let is_explict_rip_relative := match m.(rip_relative) with explicitly_rip_relative => true | _ => false end in |
| 355 |
let base_reg_str := |
| 356 |
match is_explict_rip_relative, m.(mem_base_reg) with |
| 357 |
| false, Some br => Some (show_REG br) |
| 358 |
| false, None => None |
| 359 |
| true, None => Some "rip" |
| 360 |
| true, Some br => Some ("rip + " ++ show_REG br) (* but this should not happen *) |
| 361 |
end in |
| 362 |
let reg_part |
| 363 |
:= (match base_reg_str, m.(mem_scale_reg) with |
| 364 |
| (*"[Reg]" *) Some br, None => br |
| 365 |
| (*"[Reg + Z * Reg]"*) Some br, Some (z, sr) => br ++ " + " ++ Decimal.show_Z z ++ " * " ++ show_REG sr (*only matching '+' here, because there cannot be a negative scale. *) |
| 366 |
| (*"[ Z * Reg]"*) None, Some (z, sr) => Decimal.show_Z z ++ " * " ++ show_REG sr |
| 367 |
| (*"[ ]"*) None, None => "" (* impossible, because only offset is invalid, but we seem to need it for coq because both are option's*) |
| 368 |
end%Z) in |
| 369 |
let offset_part |
| 370 |
:= (match m.(mem_offset) with |
| 371 |
| None => "" |
| 372 |
| Some offset |
| 373 |
=> (if offset <? 0 then " - " else " + ") |
| 374 |
++ (let offset := Z.abs offset in |
| 375 |
if (Z.modulo offset 8 =? 0)%Z |
| 376 |
then "0x08 * " ++ Decimal.show_Z (offset / 8) |
| 377 |
else Hex.show_Z offset) |
| 378 |
end%Z) in |
| 379 |
match m.(mem_base_label), is_explict_rip_relative, m.(mem_offset), m.(mem_scale_reg) with |
| 380 |
| Some lbl, true, None, None => lbl ++ "[" ++ reg_part ++ offset_part ++ "]" |
| 381 |
| Some lbl, _, _, _ => let l_offset := lbl ++ offset_part in |
| 382 |
"[" ++ |
| 383 |
(if reg_part =? "" |
| 384 |
then "((" ++ l_offset ++ "))" |
| 385 |
else reg_part ++ " + " ++ l_offset) |
| 386 |
++ "]" |
| 387 |
| None, _, _, _ => |
| 388 |
"[" ++ |
| 389 |
(if reg_part =? "" |
| 390 |
then "((" ++ offset_part ++ "))" |
| 391 |
else reg_part ++ offset_part) |
| 392 |
++ "]" |
| 393 |
end). |
| 394 |
Global Instance show_MEM : Show MEM := show_lvl_MEM. |
| 395 |
|
| 396 |
Global Instance show_lvl_JUMP_LABEL : ShowLevel JUMP_LABEL |
| 397 |
:= fun l _ |
| 398 |
=> ((if l.(jump_near) then "NEAR " else "") |
| 399 |
++ l.(label_name)). |
| 400 |
Global Instance show_JUMP_LABEL : Show JUMP_LABEL := show_lvl_JUMP_LABEL. |
| 401 |
|
| 402 |
Global Instance show_lvl_ARG : ShowLevel ARG |
| 403 |
:= fun a |
| 404 |
=> match a with |
| 405 |
| reg r => show_lvl r |
| 406 |
| mem m => show_lvl m |
| 407 |
| const c => show_lvl c |
| 408 |
| label l => show_lvl l |
| 409 |
end. |
| 410 |
Global Instance show_ARG : Show ARG := show_lvl_ARG. |
| 411 |
|
| 412 |
Global Instance show_NormalInstruction : Show NormalInstruction |
| 413 |
:= fun i |
| 414 |
=> match i.(prefix) with |
| 415 |
| None => "" |
| 416 |
| Some prefix => show prefix ++ " " |
| 417 |
end |
| 418 |
++ (show i.(op)) |
| 419 |
++ match i.(args) with |
| 420 |
| [] => "" |
| 421 |
| _ => " " ++ String.concat ", " (List.map show i.(args)) |
| 422 |
end. |
| 423 |
|
| 424 |
Global Instance show_RawLine : Show RawLine |
| 425 |
:= fun l |
| 426 |
=> match l with |
| 427 |
| SECTION name => "SECTION " ++ name |
| 428 |
| GLOBAL name => "GLOBAL " ++ name |
| 429 |
| ALIGN args => "ALIGN " ++ args |
| 430 |
| DEFAULT_REL => "DEFAULT REL" |
| 431 |
| LABEL name => name ++ ":" |
| 432 |
| EMPTY => "" |
| 433 |
| INSTR instr => show instr |
| 434 |
| DIRECTIVE s => s |
| 435 |
| ASCII s => ".ascii """ ++ escape_string s ++ """" |
| 436 |
| ASCIZ s => ".asciz """ ++ escape_string s ++ """" |
| 437 |
end. |
| 438 |
|
| 439 |
Global Instance show_Line : Show Line |
| 440 |
:= fun l |
| 441 |
=> strip_trailing_newline |
| 442 |
(l.(indent) ++ show l.(rawline) ++ l.(pre_comment_whitespace) ++ match l.(comment) with |
| 443 |
| Some c => ";" ++ c |
| 444 |
| None => "" |
| 445 |
end). |
| 446 |
|
| 447 |
Definition show_Line_with_line_number : Show Line |
| 448 |
:= fun l => show l ++ "; (line " ++ show l.(line_number) ++ ")". |
| 449 |
|
| 450 |
Global Instance show_lines_Lines : ShowLines Lines |
| 451 |
:= fun ls => List.map show ls. |
| 452 |
|
| 453 |
Definition parse_correct_on (v : list string) |
| 454 |
:= forall res, parse v = Success res -> parse v = parse (show_lines res). |
| 455 |
|
| 456 |
Inductive ParseError := |
| 457 |
| Parse_error (msgs : list string) |
| 458 |
. |
| 459 |
|
| 460 |
Inductive ParseValidatedError := |
| 461 |
| Initial_parse_error (err : ParseError) |
| 462 |
| Reparse_error (new_asm : list string) (err : ParseError) |
| 463 |
| Lengths_not_equal (old_asm : Lines) (new_asm : Lines) |
| 464 |
| Lines_not_equal (mismatched_lines : list (Line * Line)) |
| 465 |
| Duplicate_labels (name_counts : list (string * nat)) |
| 466 |
. |
| 467 |
Global Coercion Initial_parse_error : ParseError >-> ParseValidatedError. |
| 468 |
|
| 469 |
Global Instance show_lines_ParseError : ShowLines ParseError |
| 470 |
:= fun err => match err with |
| 471 |
| Parse_error err => err |
| 472 |
end. |
| 473 |
Global Instance show_ParseError : Show ParseError := _. |
| 474 |
Global Instance show_lines_ParseValidatedError : ShowLines ParseValidatedError |
| 475 |
:= fun err => match err with |
| 476 |
| Initial_parse_error err |
| 477 |
=> match show_lines err with |
| 478 |
| [] => ["Unknown error while parsing assembly"] |
| 479 |
| [err] => ["Error while parsing assembly: " ++ err]%string |
| 480 |
| lines => "Error while parsing assembly:" :: lines |
| 481 |
end |
| 482 |
| Reparse_error new_asm err |
| 483 |
=> match show_lines err with |
| 484 |
| [] => ["Unknown error while reparsing assembly:"] ++ new_asm |
| 485 |
| [err] => (["Error while reparsing assembly: " ++ err |
| 486 |
; "New assembly being parsed:"]%string) |
| 487 |
++ new_asm |
| 488 |
| lines => ["Error while parsing assembly:"] |
| 489 |
++ lines |
| 490 |
++ [""] |
| 491 |
++ ["New assembly being parsed:"] |
| 492 |
++ new_asm |
| 493 |
end |
| 494 |
| Lengths_not_equal old_asm new_asm |
| 495 |
=> ["Reparsing the assembly:"] |
| 496 |
++ show_lines old_asm |
| 497 |
++ [""] |
| 498 |
++ ["Yielded non-equal assembly:"] |
| 499 |
++ show_lines new_asm |
| 500 |
++ [""] |
| 501 |
++ (["The number of lines was not equal (" ++ show (List.length old_asm) ++ " ≠ " ++ show (List.length new_asm) ++ ")"]%string) |
| 502 |
| Lines_not_equal mismatched_lines |
| 503 |
=> ["When reparsing assembly for validation, the following lines were not equal:"] |
| 504 |
++ (List.flat_map (fun '(old, new) => ["- " ++ show old; "+ " ++ show new; ""]%string) |
| 505 |
mismatched_lines) |
| 506 |
| Duplicate_labels nil |
| 507 |
=> ["Internal error: Duplicate_labels []"] |
| 508 |
| Duplicate_labels [(name, count)] |
| 509 |
=> ["Label occurs multiple times: " ++ name ++ " occurs " ++ show count ++ " times"]%string |
| 510 |
| Duplicate_labels name_counts |
| 511 |
=> ["Labels occurs multiple times:"] |
| 512 |
++ List.map (fun '(name, count) => name ++ " occurs " ++ show count ++ " times")%string name_counts |
| 513 |
end%list. |
| 514 |
Global Instance show_ParseValidatedError : Show ParseValidatedError := _. |
| 515 |
|
| 516 |
Definition parse_validated (v : list string) : ErrorT ParseValidatedError Lines |
| 517 |
:= match parse v with |
| 518 |
| Success v |
| 519 |
=> let new_asm := show_lines v in |
| 520 |
match parse new_asm with |
| 521 |
| Success v' |
| 522 |
=> let labels := Option.List.map (fun l => match l.(rawline) with |
| 523 |
| LABEL n => Some n |
| 524 |
| _ => None |
| 525 |
end) v' in |
| 526 |
let counts := List.map (fun l => (l, List.count_occ string_dec labels l)) labels in |
| 527 |
let big_counts := List.filter (fun '(l, n) => (1 <? n)%nat) counts in |
| 528 |
match big_counts with |
| 529 |
| nil |
| 530 |
=> if (List.length v =? List.length v')%nat |
| 531 |
then match List.filter (fun '(x, y) => negb (Line_beq x y)) (List.combine v v') with |
| 532 |
| nil => Success v |
| 533 |
| mismatched_lines => Error (Lines_not_equal mismatched_lines) |
| 534 |
end |
| 535 |
else Error (Lengths_not_equal v v') |
| 536 |
| _ => Error (Duplicate_labels big_counts) |
| 537 |
end |
| 538 |
| Error e |
| 539 |
=> Error (Reparse_error new_asm (Parse_error e)) |
| 540 |
end |
| 541 |
| Error e => Error (Initial_parse_error (Parse_error e)) |
| 542 |
end. |
| 543 |
|
| 544 |
Definition parse_correct_on_bool (v : list string) : bool |
| 545 |
:= match parse v, parse_validated v with |
| 546 |
| Success _, Success _ => true |
| 547 |
| Error _, _ => true |
| 548 |
| Success _, Error _ => false |
| 549 |
end. |
| 550 |
|
| 551 |
Definition parse_validated_correct_on v |
| 552 |
:= forall res, parse_validated v = Success res <-> parse v = Success res. |
| 553 |
|
| 554 |
Lemma parse_validated_correct_on_iff v : parse_validated_correct_on v <-> parse_correct_on v. |
| 555 |
Proof. |
| 556 |
cbv [parse_validated_correct_on parse_correct_on parse_validated]. |
| 557 |
destruct (parse_Lines v) eqn:Hp; [ | split; [ congruence | split; congruence ] ]. |
| 558 |
destruct (parse_Lines (show_lines _)) eqn:Hp2; (split; [ intros H res Hres; inversion Hres; subst | intro H; specialize (H _ eq_refl); rewrite <- H in Hp2; inversion Hp2; subst ]); rewrite ?Nat.eqb_refl, ?combine_same; try congruence. |
| 559 |
all: repeat first [ progress destruct_head' iff |
| 560 |
| congruence |
| 561 |
| progress subst |
| 562 |
| progress rewrite ?Nat.eqb_eq in * |
| 563 |
| match goal with |
| 564 |
| [ H : forall x, _ <-> Success ?y = Success x |- _ ] => specialize (H y) |
| 565 |
| [ H : ?x = ?x |- _ ] => clear H |
| 566 |
| [ H : Success ?x = Success ?y |- _ ] => inversion H; clear H |
| 567 |
| [ H : ?x = ?x -> _ |- _ ] => specialize (H eq_refl) |
| 568 |
end |
| 569 |
| break_innermost_match_hyps_step |
| 570 |
| progress break_match_hyps |
| 571 |
| progress break_match |
| 572 |
| progress intros |
| 573 |
| apply conj ]. |
| 574 |
Abort. |
| 575 |
|
| 576 |
Lemma parse_correct_on_bool_iff v : parse_correct_on_bool v = true <-> parse_correct_on v. |
| 577 |
Proof. |
| 578 |
assert (parse_validated_correct_on_iff : forall v, parse_validated_correct_on v <-> parse_correct_on v) by admit. |
| 579 |
rewrite <- parse_validated_correct_on_iff. |
| 580 |
cbv [parse_correct_on_bool parse_validated_correct_on]. |
| 581 |
destruct (parse_Lines v) eqn:Heq1, (parse_validated v) eqn:Heq2; split; try split; try congruence. |
| 582 |
Abort. |
| 583 |
|
| 584 |
(* This version allows for easier debugging because it highlights the differences *) |
| 585 |
Definition parse_correct_on_debug (v : list string) |
| 586 |
:= match parse v with |
| 587 |
| Success v => match parse (show_lines v) with |
| 588 |
| Success v' |
| 589 |
=> if (List.length v =? List.length v')%nat |
| 590 |
then List.filter (fun '(x, y) => negb (Line_beq x y)) (List.combine v v') = nil |
| 591 |
else List.length v = List.length v' |
| 592 |
| Error e => forall x, e = x -> False |
| 593 |
end |
| 594 |
| Error e => forall x, e = x -> False |
| 595 |
end. |
| 596 |
Theorem parse_correct : forall v, parse_correct_on v. |
| 597 |
Proof. Abort. |
| 598 |
|
| 599 |
(** Some extra utility functions for processing assembly files *) |
| 600 |
(** We assume that the asm file contains GLOBAL declarations for each |
| 601 |
function. The function name must match the name which would be |
| 602 |
generated by fiat-crypto. The function names declare the labels |
| 603 |
that break up instructions into functions. We currently associate |
| 604 |
lines (including blank and comment lines) before a label to the |
| 605 |
previous label, though plausibly there should be some other |
| 606 |
heuristic for dealing with comments. *) |
| 607 |
|
| 608 |
Definition find_globals (ls : Lines) : list string |
| 609 |
:= Option.List.map |
| 610 |
(fun l => match l.(rawline) with |
| 611 |
| GLOBAL name => Some name |
| 612 |
| _ => None |
| 613 |
end) |
| 614 |
ls. |
| 615 |
|
| 616 |
Definition find_labels (ls : Lines) : list string |
| 617 |
:= Option.List.map |
| 618 |
(fun l => match l.(rawline) with |
| 619 |
| LABEL name => Some name |
| 620 |
| _ => None |
| 621 |
end) |
| 622 |
ls. |
| 623 |
|
| 624 |
Fixpoint split_code_to_functions' (label_is_function : string -> bool) (ls : Lines) : Lines (* prefix *) * list (string (* global name *) * Lines) |
| 625 |
:= match ls with |
| 626 |
| [] => ([], []) |
| 627 |
| l :: ls |
| 628 |
=> let '(prefix, rest) := split_code_to_functions' label_is_function ls in |
| 629 |
let default := (l :: prefix, rest) in |
| 630 |
match l.(rawline) with |
| 631 |
| LABEL name => if label_is_function name |
| 632 |
then ([], (name, l::prefix) :: rest) |
| 633 |
else default |
| 634 |
| _ => default |
| 635 |
end |
| 636 |
end. |
| 637 |
|
| 638 |
Definition string_matches_loose (allow_prefix : bool) (allow_suffix : bool) (longer_string shorter_string : string) : bool |
| 639 |
:= match allow_prefix, allow_suffix with |
| 640 |
| false, false => shorter_string =? longer_string |
| 641 |
| true, false => String.endswith shorter_string longer_string |
| 642 |
| false, true => String.startswith shorter_string longer_string |
| 643 |
| true, true => String.is_substring shorter_string longer_string |
| 644 |
end. |
| 645 |
Definition split_code_to_listed_functions {allow_prefix allow_suffix : bool} (functions : list string) (ls : Lines) : Lines (* prefix *) * list (string (* global name *) * Lines) |
| 646 |
:= split_code_to_functions' (fun name => List.existsb (fun f => string_matches_loose allow_prefix allow_suffix f name)%string functions) ls. |
| 647 |
Definition split_code_to_global_functions (ls : Lines) : Lines (* prefix *) * list (string (* global name *) * Lines) |
| 648 |
:= let globals := find_globals ls in |
| 649 |
split_code_to_listed_functions (allow_prefix:=false) (allow_suffix:=false) globals ls. |
| 650 |
Definition split_code_at_labels (ls : Lines) : Lines (* prefix *) * list (string (* label name *) * Lines) |
| 651 |
:= let labels := find_labels ls in |
| 652 |
split_code_to_listed_functions (allow_prefix:=false) (allow_suffix:=false) labels ls. |
| 653 |
|
| 654 |
Fixpoint get_initial_data (ls : Lines) : list (AccessSize * list Z) |
| 655 |
:= let get_arg_consts args := |
| 656 |
Option.List.lift |
| 657 |
(List.map (fun arg => match arg with |
| 658 |
| const c => Some c |
| 659 |
| _ => None |
| 660 |
end) |
| 661 |
args) in |
| 662 |
match ls with |
| 663 |
| [] => [] |
| 664 |
| l :: ls |
| 665 |
=> match l.(rawline) with |
| 666 |
| INSTR instr => |
| 667 |
match accesssize_of_declaration instr.(op) with |
| 668 |
| None => [] |
| 669 |
| Some size => |
| 670 |
let csts := get_arg_consts instr.(args) in |
| 671 |
match csts with |
| 672 |
| Some csts => (size, csts) :: get_initial_data ls |
| 673 |
| None => [] |
| 674 |
end |
| 675 |
end |
| 676 |
| LABEL _ |
| 677 |
| EMPTY |
| 678 |
| GLOBAL _ |
| 679 |
| DIRECTIVE _ |
| 680 |
| DEFAULT_REL |
| 681 |
=> get_initial_data ls |
| 682 |
| SECTION _ |
| 683 |
| ALIGN _ |
| 684 |
| ASCII _ |
| 685 |
| ASCIZ _ |
| 686 |
=> [] |
| 687 |
end |
| 688 |
end. |
| 689 |
|
| 690 |
Definition get_labeled_data (ls : Lines) : list (string * list (AccessSize * list Z)) := |
| 691 |
let '(_, labeled_data) := split_code_at_labels ls in |
| 692 |
let labeled_data := List.map (fun '(lbl, lines) => (lbl, get_initial_data lines)) labeled_data in |
| 693 |
let labeled_data := List.filter (fun '(_, data) => match data with nil => false | _ => true end) labeled_data in |
| 694 |
labeled_data. |
| 695 |
|
| 696 |
(* Definition parse_assembly_options (ls : Lines) : assembly_program_options |
| 697 |
:= {| default_rel := Option.is_Some (List.find (fun l => match l.(rawline) with |
| 698 |
| DEFAULT_REL => true |
| 699 |
| _ => false |
| 700 |
end) ls) |
| 701 |
|}. *) |