Library QedkConcrete.memorysizes

Bounds on concrete memory reads

Successful extension limits a nonempty read to the machine's capacity. The read then returns exactly the requested number of bytes. This is the size fact needed for internal calldata and RETURN/REVERT data, independently of their contents. The retained allocation-guard failure case is ruled out by no_bad_memory_init_comparison.
From Stdlib Require Import List String ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import RocqOfOCaml.Unreachable.StringBounds.
Require Import MonadVM.Vm QedkConcrete.memorywords QedkConcrete.memorycomposition
  QedkConcrete.nativeindices QedkConcrete.wordrange QedkConcrete.bytewords QedkConcrete.vmmachinewords.
Set Default Goal Selector "!".
Local Open Scope Z_scope.

Lemma word_to_uint_nonnegative {UN : Basics.Unreachable Support.UintN.t} value :
  0 ≤ U.to_z value → @U.to_uint value = Z.to_N (U.to_z value).
Proof.
  intro Hvalue.
  change (@Support.UintN.of_z_exn value = Z.to_N value).
  unfold Support.UintN.of_z_exn, Support.UintN.of_z_opt, Support.UintN.in_range.
  rewrite (proj2 (Z.leb_le 0 value) Hvalue). reflexivity.
Qed.

Lemma word_to_int_small {UI : Basics.Unreachable int} value :
  0 ≤ U.to_z value < 2^62 → @U.to_int value = U.to_z value.
Proof.
  intro Hvalue.
  cbn -[OCamlZ.checked_signed].
  unfold Numeric.Make.to_int, OCamlZ.to_int.
  unfold OCamlZ.checked_signed, OCamlZ.fits_signed, OCamlZ.signed_min, OCamlZ.signed_max.
  change (0 ≤ value < 2^62) in Hvalue.
  assert (Hlo : Z.leb (-(2^62)) value = true) by (apply Z.leb_le; lia).
  assert (Hhi : Z.leb value (Z.pred (2^62)) = true) by (apply Z.leb_le; lia).
  replace (Z.pred 63) with 62 by reflexivity.
  change (@Numeric.Make.to_z (@Numeric.TwosComplement.U_fargs Numeric.Bits256_fargs) value) with value.
  rewrite Hlo, Hhi. reflexivity.
Qed.

Lemma whole_words_cover {UN : Basics.Unreachable Support.UintN.t} bytes :
  (bytes ≤ @Support.UintN.bytes_to_whole_words bytes × 32)%N.
Proof.
  unfold Support.UintN.bytes_to_whole_words.
  pose proof (N.div_mod (bytes + 31) 32 ltac:(discriminate)).
  pose proof (N.mod_lt (bytes + 31) 32 ltac:(discriminate)). nia.
Qed.

Lemma word_is_zero {UF : Basics.Unreachable U.t} value :
  U.op_eq value (@U.zero) = Z.eqb value 0.
Proof. destruct value; reflexivity. Qed.

Section Memory.
Context {Host_t : Set} {F : @V.FArgs Host_t}.
Context {UN : Basics.Unreachable Support.UintN.t} {UF : Basics.Unreachable U.t}
  {UU : Basics.Unreachable unit} {US : Basics.Unreachable string}
  {UL : Basics.Unreachable (list string)} {UI : Basics.Unreachable int}
  {UZ : Basics.Unreachable Byte_string.B32.(Byte_string.Fixed.Fixed_result.t)}.

Lemma extend_nine_read_size start size before after :
  0 ≤ U.to_z start → 0 ≤ U.to_z size →
  @Mem.extend_to_monad_nine Host_t F start size before = Some after →
  (U.to_z size = 0 ∨ U.to_z start + U.to_z size ≤ Z.of_N (Mem.t.memory_capacity before)) ∧
  Mem.t.memory_capacity after = Mem.t.memory_capacity before.
Proof.
  intros Hstart Hsize Hextend. unfold Mem.extend_to_monad_nine in Hextend.
  rewrite word_is_zero in Hextend.
  destruct (Z.eqb size 0) eqn:Hzero.
  - apply Z.eqb_eq in Hzero. inversion Hextend; subst. split; [left; reflexivity|reflexivity].
  - rewrite !word_to_uint_nonnegative in Hextend by assumption.
    match type of Hextend with context [if ?fits then _ else _] ⇒ destruct fits eqn:Hfits end;
      [|discriminate].
    inversion Hextend; subst. split; [right|reflexivity].
    change (N.leb (Support.UintN.max (Mem.t.active_bytes before)
      ((@Support.UintN.bytes_to_whole_words (Z.to_N start + Z.to_N size)%N) × 32)%N)
      (Mem.t.memory_capacity before) = true) in Hfits.
    apply N.leb_le in Hfits.
    pose proof (@whole_words_cover UN (Z.to_N start + Z.to_N size)%N) as Hcover.
    change (0 ≤ start) in Hstart. change (0 ≤ size) in Hsize.
    change (start + size ≤ Z.of_N (Mem.t.memory_capacity before)).
    unfold Support.UintN.max in Hfits.
    match type of Hfits with context [if ?larger then _ else _] ⇒ destruct larger eqn:Hlarger end.
    + lia.
    + apply N.ltb_ge in Hlarger. lia.
Qed.

Lemma read_block_length_or_bad_comparison start size memory :
  0 ≤ U.to_z size < 2^32 → memoryWordChunks memory →
  OCamlString.length (@Mem.read_block_at Host_t F start size memory) = U.to_z size ∨
  badMemoryInitComparison.
Proof.
  intros Hsize Hmemory. unfold Mem.read_block_at.
  rewrite word_is_zero.
  destruct (Z.eqb size 0) eqn:Hzero.
  - apply Z.eqb_eq in Hzero. left. subst size. reflexivity.
  - rewrite (word_to_int_small size ltac:(lia)).
    rewrite (surjective_pairing (@Mem.align Host_t F (@U.to_int start))).
    cbn beta iota zeta.
    rewrite memory_word_count by (first [apply align_offset_range|exact Hsize]).
    set (position := @U.to_int start).
    set (offset := snd (@Mem.align Host_t F position)).
    set (base := fst (@Mem.align Host_t F position)).
    set (count := (offset + U.to_z size + 31) ÷ 32).
    pose proof (align_offset_range position) as Hoffset. fold offset in Hoffset.
    pose proof (chunks_cover offset (U.to_z size) ltac:(lia) (proj1 Hsize)) as [Hcount [Hcover Hpadding]].
    rewrite <- (Z.quot_div_nonneg (offset + U.to_z size + 31) 32) by lia.
    fold count in Hcount, Hcover, Hpadding.
    destruct (Z.ltb count 0) eqn:Hguard.
    + right. ∃ count. split; assumption.
    + left. change (OCamlString.length (@OCamlString.sub (Opaque.legacy_witness (@Mem._rocq_fallback_read_block_at_0 Host_t F))
        (OCamlString.concat EmptyString (@OCamlList.init string (Opaque.legacy_witness (@Mem._rocq_fallback_read_block_at_1 Host_t F)) count
          (fun index ⇒ @Mem.read_aligned Host_t F (OCamlInt.add base (OCamlInt.mul index 32)) memory)))
        offset (U.to_z size)) = U.to_z size).
      apply StringBounds.sub_length_in_bounds; [lia|lia|].
      rewrite concat32_length.
      × rewrite list_init_length by assumption. exact Hcover.
      × apply list_init_property; [lia|exact Hguard|]. intros index Hindex.
        apply read_aligned_length. exact Hmemory.
Qed.

Lemma extended_nine_read_bounded start size before after :
  0 ≤ U.to_z start → 0 ≤ U.to_z size →
  Z.of_N (Mem.t.memory_capacity before) < 2^32 → memoryWordChunks before →
  @Mem.extend_to_monad_nine Host_t F start size before = Some after →
  (OCamlString.length (@Mem.read_block_at Host_t F start size after) = U.to_z size ∧
    U.to_z size ≤ Z.of_N (Mem.t.memory_capacity before)) ∨ badMemoryInitComparison.
Proof.
  intros Hstart Hsize Hcapacity Hmemory Hextend.
  pose proof (extend_nine_read_size start size before after Hstart Hsize Hextend) as [Hbound _].
  assert (HsizeBound : U.to_z size ≤ Z.of_N (Mem.t.memory_capacity before)) by
    (destruct Hbound; lia).
  assert (Hafter : memoryWordChunks after).
  { unfold Mem.extend_to_monad_nine in Hextend.
    repeat match type of Hextend with context [if ?test then _ else _] ⇒ destruct test end;
      inversion Hextend; subst; exact Hmemory. }
  destruct (read_block_length_or_bad_comparison start size after ltac:(lia) Hafter)
    as [Hlength|Hfailure]; [left; split; assumption|right; exact Hfailure].
Qed.

Memory writes alter chunks, not the capacity shared with child calls. This fact holds even for an arbitrary fallback list of write indices.
Lemma memory_fold_capacity {A : Set} (f : @Mem.t Host_t F → A → @Mem.t Host_t F)
    items memory :
  (∀ before item, Mem.t.memory_capacity (f before item) = Mem.t.memory_capacity before) →
  Mem.t.memory_capacity (OCamlList.fold_left f memory items) = Mem.t.memory_capacity memory.
Proof.
  intro Hframe. revert memory. induction items as [|item items IH]; intro memory.
  - reflexivity.
  - cbn [OCamlList.fold_left]. rewrite IH. apply Hframe.
Qed.

Context {UB : Basics.Unreachable Byte_string.Bytes.t}
  {ULI : Basics.Unreachable (list int)}.

Lemma write_block_capacity start bytes memory :
  Mem.t.memory_capacity (@Mem.write_block_at Host_t F start bytes memory) =
    Mem.t.memory_capacity memory.
Proof.
  unfold Mem.write_block_at. destruct (Byte_string.Bytes.op_eq _ _); [reflexivity|].
  reflexivity.
Qed.

Lemma write_word_capacity {UR : Basics.Unreachable U.Repr.t}
    {UC : Basics.Unreachable ascii} {UP : Basics.Unreachable (int × int)} start value memory :
  Mem.t.memory_capacity (@Mem.write_word_at Host_t F start value memory) =
    Mem.t.memory_capacity memory.
Proof.
  unfold Mem.write_word_at. destruct (Mem.is_aligned _); [reflexivity|apply write_block_capacity].
Qed.

Lemma write_byte_capacity start byte memory :
  Mem.t.memory_capacity (@Mem.write_byte_at Host_t F start byte memory) =
    Mem.t.memory_capacity memory.
Proof. unfold Mem.write_byte_at. apply write_block_capacity. Qed.

Lemma write_block_active_bytes start bytes memory :
  Mem.t.active_bytes (@Mem.write_block_at Host_t F start bytes memory) =
    Mem.t.active_bytes memory.
Proof.
  unfold Mem.write_block_at. destruct (Byte_string.Bytes.op_eq _ _); [reflexivity|].
  reflexivity.
Qed.

Lemma write_word_active_bytes {UR : Basics.Unreachable U.Repr.t}
    {UC : Basics.Unreachable ascii} {UP : Basics.Unreachable (int × int)} start value memory :
  Mem.t.active_bytes (@Mem.write_word_at Host_t F start value memory) =
    Mem.t.active_bytes memory.
Proof.
  unfold Mem.write_word_at. destruct (Mem.is_aligned _); [reflexivity|apply write_block_active_bytes].
Qed.

Lemma write_byte_active_bytes start byte memory :
  Mem.t.active_bytes (@Mem.write_byte_at Host_t F start byte memory) =
    Mem.t.active_bytes memory.
Proof. unfold Mem.write_byte_at. apply write_block_active_bytes. Qed.

Lemma available_nine_memory_bounded
    {UA : Basics.Unreachable (@Mem.t Host_t F → Support.UintN.t)} memory :
  (@V.Params Host_t F).(Vm.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  (Mem.t.active_bytes memory ≤ Mem.t.memory_capacity memory)%N →
  (@Mem.available_memory_size Host_t F memory ≤ Mem.t.memory_capacity memory)%N.
Proof.
  intros Hrevision Hactive. unfold Mem.available_memory_size. rewrite Hrevision.
  unfold Support.UintN.op_minus. rewrite (proj2 (N.leb_le _ _) Hactive). apply N.le_sub_l.
Qed.

Lemma empty_active_within_capacity capacity :
  (Mem.t.active_bytes (@Mem.empty Host_t F capacity) ≤ capacity)%N.
Proof. apply N.le_0_l. Qed.

Lemma extend_nine_active_within_capacity start size before after :
  (Mem.t.active_bytes before ≤ Mem.t.memory_capacity before)%N →
  @Mem.extend_to_monad_nine Host_t F start size before = Some after →
  (Mem.t.active_bytes after ≤ Mem.t.memory_capacity after)%N.
Proof.
  intros Hactive Hextend. unfold Mem.extend_to_monad_nine in Hextend.
  destruct (U.op_eq _ _).
  - inversion Hextend; subst. exact Hactive.
  - match type of Hextend with context [if ?test then _ else _] ⇒ destruct test eqn:Hfits end;
      [|discriminate].
    inversion Hextend; subst. apply N.leb_le in Hfits. exact Hfits.
Qed.
End Memory.

Print Assumptions extend_nine_read_size.
Print Assumptions read_block_length_or_bad_comparison.
Print Assumptions extended_nine_read_bounded.
Print Assumptions write_block_capacity.