(* *********************************************************************)
(*                                                                     *)
(*            The CertiKOS Certified Kit Operating System              *)
(*                                                                     *)
(*                   The FLINT Group, Yale University                  *)
(*                                                                     *)
(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)
(*  This file is distributed under the terms of the Yale University    *)
(*  Non-Commercial License Agreement.                                  *)
(*                                                                     *)
(* *********************************************************************)
(* *********************************************************************)
(*                                                                     *)
(*              Layers of VM: PIPC                                     *)
(*                                                                     *)
(*          Provide the abstraction of ipc channel                     *)
(*                                                                     *)
(*          Haozhong Zhang <haozhong.zhang@yale.edu>                   *)
(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)
(*                                                                     *)
(*          Yale Flint Group                                           *)
(*                                                                     *)
(* *********************************************************************)

(** This file defines the abstract data and the primitives for the PIPC layer,
which will introduce the primtives of thread*)
Require Import Coqlib.
Require Import Maps.
Require Import ASTExtra.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Events.
Require Import Stacklayout.
Require Import Globalenvs.
Require Import AsmX.
Require Import Smallstep.
Require Import AuxStateDataType.
Require Import Constant.
Require Import GlobIdent.
Require Import FlatMemory.
Require Import CommonTactic.
Require Import AuxLemma.
Require Import RealParams.
Require Import PrimSemantics.
Require Import LAsm.
Require Import LoadStoreSem2.
Require Import XOmega.
Require Import ObservationImpl.

Require Import liblayers.logic.PTreeModules.
Require Import liblayers.logic.LayerLogicImpl.
Require Import liblayers.compat.CompatLayers.
Require Import liblayers.compat.CompatGenSem.

Require Import CalRealPTPool.
Require Import CalRealPT.
Require Import CalRealIDPDE.
Require Import CalRealInitPTE.
Require Import CalRealSMSPool.
Require Import CalRealProcModule.

Require Import INVLemmaContainer.
Require Import INVLemmaMemory.
Require Import INVLemmaThread.
Require Import INVLemmaProc.

Require Import AbstractDataType.

Require Export ObjCPU.
Require Export ObjFlatMem.
Require Export ObjContainer.
Require Export ObjVMM.
Require Export ObjLMM.
Require Export ObjShareMem.
Require Export ObjThread.
Require Export ObjProc.
Require Export ObjSyncIPC.

(** * Abstract Data and Primitives at this layer*)
Section WITHMEM.

  Local Open Scope Z_scope.

  Context `{real_params: RealParams}.

  (** **Definition of the invariants at MPTNew layer*)
  (** [0th page map] is reserved for the kernel thread*)
  Record high_level_invariant (abd: RData) :=
    mkInvariant {
        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;
        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);
        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);
        valid_kern: ipt abd = false -> pg abd = true;
        valid_iptt: ipt abd = true -> ikern abd = true;
        valid_iptf: ikern abd = false -> ipt abd = false;
        valid_ihost: ihost abd = false -> pg abd = true /\ ikern abd = true;
        valid_container: Container_valid (AC abd);
        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);
        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;
        valid_PMap: pg abd = true ->
                    (forall i, 0<= i < num_proc ->
                               PMap_valid (ZMap.get i (ptpool abd)));
        (* 0th page map is reserved for the kernel thread*)
        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;
        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));
        valid_PT: pg abd = true -> 0<= PT abd < num_proc;
        valid_dirty: dirty_ppage (pperm abd) (HP abd);

        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);
        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);
        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);
        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);

        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;

        valid_TCB: pg abd = true -> AbTCBStrong_range (abtcb abd);
        valid_TDQ: pg abd = true -> AbQCorrect_range (abq abd);
        valid_notinQ: pg abd = true -> NotInQ (AC abd) (abtcb abd);
        valid_count: pg abd = true -> QCount (abtcb abd) (abq abd);
        valid_inQ: pg abd = true -> InQ (abtcb abd) (abq abd);
        valid_curid: 0 <= cid abd < num_proc;
        correct_curid: pg abd = true -> CurIDValid (cid abd) (AC abd) (abtcb abd);
        single_curid: pg abd = true -> SingleRun (cid abd) (abtcb abd);
        (*valid_chan: pg abd = true -> ChanPool_Valid (chpool abd)*)
        valid_chan: pg abd = true -> SyncChanPool_Valid (syncchpool abd)
      }.

  (** ** Definition of the abstract state ops *)
  Global Instance pipc_data_ops : CompatDataOps RData :=
    {
      empty_data := init_adt;
      high_level_invariant := high_level_invariant;
      low_level_invariant := low_level_invariant;
      kernel_mode adt := ikern adt = true /\ ihost adt = true;
      observe := ObservationImpl.observe
    }.

  (** ** Proofs that the initial abstract_data should satisfy the invariants*)
  Section Property_Abstract_Data.

    Lemma empty_data_high_level_invariant:
      high_level_invariant init_adt.
    Proof.
      constructor; simpl; intros; auto; try inv H.
      - apply empty_container_valid.
      - eapply Lconsistent_ppage_init.
      - eapply dirty_ppage_init.
      - eapply consistent_pmap_init.
      - eapply consistent_pmap_domain_init.
      - eapply consistent_lat_domain_init.
      - repeat rewrite ZMap.gi; intuition.
    Qed.

    (** ** Definition of the abstract state *)
    Global Instance pipc_data_prf : CompatData RData.
    Proof.
      constructor.
      - apply low_level_invariant_incr.
      - apply empty_data_low_level_invariant.
      - apply empty_data_high_level_invariant.
    Qed.

  End Property_Abstract_Data.

  Context `{Hstencil: Stencil}.
  Context `{Hmem: Mem.MemoryModel}.
  Context `{Hmwd: UseMemWithData mem}.

  (** * Proofs that the primitives satisfies the invariants at this layer *)
  Section INV.

    Section ALLOC.

      Lemma alloc_high_level_inv:
        forall d d' i n,
          alloc_spec i d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; simpl; eauto.
        - intros; eapply LAT_kern_norm; eauto. eapply _x.
        - intros; eapply LAT_usr_norm; eauto.
        - eapply alloc_container_valid'; eauto.
        - eapply Lconsistent_ppage_norm_alloc; eauto.
        - intros; congruence.
        - eapply dirty_ppage_gso_alloc; eauto.
        - eapply consistent_pmap_gso_at_false; eauto. apply _x.
        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.
        - eapply consistent_lat_domain_gss_nil; eauto.
        - zmap_solve.
        - intros; apply NotInQ_gso_true; auto.
        - intros; apply CurIDValid_gss_ac; auto.
      Qed.

      Lemma alloc_low_level_inv:
        forall d d' i n n',
          alloc_spec i d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; eauto.
      Qed.

      Lemma alloc_kernel_mode:
        forall d d' i n,
          alloc_spec i d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

      Global Instance alloc_inv: PreservesInvariants alloc_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply alloc_low_level_inv; eassumption.
        - eapply alloc_high_level_inv; eassumption.
        - eapply alloc_kernel_mode; eassumption.
      Qed.

    End ALLOC.

    Global Instance pfree_inv: PreservesInvariants pfree_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      - intros; eapply LAT_kern_norm; eauto.
      - intros; eapply LAT_usr_norm; eauto.
      - eapply Lconsistent_ppage_norm_undef; eauto.
      - eapply dirty_ppage_gso_undef; eauto.
      - eapply consistent_pmap_gso_pperm_alloc; eauto.
      - eapply consistent_pmap_domain_gso_at_0; eauto.
      - eapply consistent_lat_domain_gss_nil; eauto.
    Qed.

    Global Instance trapin_inv: PrimInvariants trapin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance trapout_inv: PrimInvariants trapout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance hostin_inv: PrimInvariants hostin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance hostout_inv: PrimInvariants hostout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance ptin_inv: PrimInvariants ptin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance ptout_inv: PrimInvariants ptout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance fstore_inv: PreservesInvariants fstore_spec.
    Proof.
      split; intros; inv_generic_sem H; inv H0; functional inversion H2.
      - functional inversion H. split; trivial.
      - functional inversion H.
        split; subst; simpl;
        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial.
      - functional inversion H0.
        split; simpl; try assumption.
    Qed.

    Global Instance setPT_inv: PreservesInvariants setPT_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
    Qed.

    Section PTINSERT.

      Section PTINSERT_PTE.

        Lemma ptInsertPTE_high_level_inv:
          forall d d' n vadr padr p,
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0; constructor_gso_simpl_tac; intros.
          - eapply LAT_kern_norm; eauto.
          - eapply LAT_usr_norm; eauto.
          - eapply Lconsistent_ppage_norm; eassumption.
          - eapply PMap_valid_gso_valid; eauto.
          - functional inversion H2. functional inversion H1.
            eapply PMap_kern_gso; eauto.
          - functional inversion H2. functional inversion H0.
            eapply consistent_pmap_ptp_same; try eassumption.
            eapply consistent_pmap_gso_pperm_alloc'; eassumption.
          - functional inversion H2.
            eapply consistent_pmap_domain_append; eauto.
            destruct (ZMap.get pti pdt); try contradiction;
            red; intros (v0 & p0 & He); contra_inv.
          - eapply consistent_lat_domain_gss_append; eauto.
            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;
            red; intros (v0 & p0 & He); contra_inv.
        Qed.

        Lemma ptInsertPTE_low_level_inv:
          forall d d' n vadr padr p n',
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            low_level_invariant n' d ->
            low_level_invariant n' d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0. constructor; eauto.
        Qed.

        Lemma ptInsertPTE_kernel_mode:
          forall d d' n vadr padr p,
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros. functional inversion H; subst; eauto.
        Qed.

      End PTINSERT_PTE.

      Section PTALLOCPDE.

        Lemma ptAllocPDE_high_level_inv:
          forall d d' n vadr v,
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0; constructor_gso_simpl_tac; intros.
          - eapply LAT_kern_norm; eauto. eapply _x.
          - eapply LAT_usr_norm; eauto.
          - eapply alloc_container_valid'; eauto.
          - apply Lconsistent_ppage_norm_hide; try assumption.
          - congruence.
          - eapply PMap_valid_gso_pde_unp; eauto.
            eapply real_init_PTE_defined.
          - functional inversion H3.
            eapply PMap_kern_gso; eauto.
          - eapply dirty_ppage_gss; eauto.
          - eapply consistent_pmap_ptp_gss; eauto; apply _x.
          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.
            eapply consistent_pmap_domain_ptp_unp; eauto.
            apply real_init_PTE_unp.
          - apply consistent_lat_domain_gss_nil; eauto.
            apply consistent_lat_domain_gso_p; eauto.
          - zmap_solve.
          - apply NotInQ_gso_true; auto.
          - apply CurIDValid_gss_ac; auto.
        Qed.

        Lemma ptAllocPDE_low_level_inv:
          forall d d' n vadr v n',
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            low_level_invariant n' d ->
            low_level_invariant n' d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0. constructor; eauto.
        Qed.

        Lemma ptAllocPDE_kernel_mode:
          forall d d' n vadr v,
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros. functional inversion H; subst; eauto.
        Qed.

      End PTALLOCPDE.

      Lemma ptInsert_high_level_inv:
        forall d d' n vadr padr p v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_high_level_inv; eassumption.
        - eapply ptAllocPDE_high_level_inv; eassumption.
        - eapply ptInsertPTE_high_level_inv; try eassumption.
          eapply ptAllocPDE_high_level_inv; eassumption.
      Qed.

      Lemma ptInsert_low_level_inv:
        forall d d' n vadr padr p n' v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_low_level_inv; eassumption.
        - eapply ptAllocPDE_low_level_inv; eassumption.
        - eapply ptInsertPTE_low_level_inv; try eassumption.
          eapply ptAllocPDE_low_level_inv; eassumption.
      Qed.

      Lemma ptInsert_kernel_mode:
        forall d d' n vadr padr p v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_kernel_mode; eassumption.
        - eapply ptAllocPDE_kernel_mode; eassumption.
        - eapply ptInsertPTE_kernel_mode; try eassumption.
          eapply ptAllocPDE_kernel_mode; eassumption.
      Qed.

    End PTINSERT.

    Section PTRESV.

      Lemma ptResv_high_level_inv:
        forall d d' n vadr p v,
          ptResv_spec n vadr p d = Some (d', v) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_high_level_inv; try eassumption.
        eapply alloc_high_level_inv; eassumption.
      Qed.

      Lemma ptResv_low_level_inv:
        forall d d' n vadr p n' v,
          ptResv_spec n vadr p d = Some (d', v) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_low_level_inv; try eassumption.
        eapply alloc_low_level_inv; eassumption.
      Qed.

      Lemma ptResv_kernel_mode:
        forall d d' n vadr p v,
          ptResv_spec n vadr p d = Some (d', v) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_kernel_mode; try eassumption.
        eapply alloc_kernel_mode; eassumption.
      Qed.

      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply ptResv_low_level_inv; eassumption.
        - eapply ptResv_high_level_inv; eassumption.
        - eapply ptResv_kernel_mode; eassumption.
      Qed.

    End PTRESV.

    Section OFFER_SHARE.

      Section PTRESV2.

        Lemma ptResv2_high_level_inv:
          forall d d' n vadr p n' vadr' p' v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_high_level_inv; try eassumption.
          - eapply alloc_high_level_inv; eassumption.
          - eapply ptInsert_high_level_inv; try eassumption.
            eapply alloc_high_level_inv; eassumption.
        Qed.

        Lemma ptResv2_low_level_inv:
          forall d d' n vadr p n' vadr' p' l v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            low_level_invariant l d ->
            low_level_invariant l d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_low_level_inv; try eassumption.
          - eapply alloc_low_level_inv; eassumption.
          - eapply ptInsert_low_level_inv; try eassumption.
            eapply alloc_low_level_inv; eassumption.
        Qed.

        Lemma ptResv2_kernel_mode:
          forall d d' n vadr p n' vadr' p' v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_kernel_mode; try eassumption.
          - eapply alloc_kernel_mode; eassumption.
          - eapply ptInsert_kernel_mode; try eassumption.
            eapply alloc_kernel_mode; eassumption.
        Qed.

      End PTRESV2.

      Global Instance offer_shared_mem_inv:
        PreservesInvariants offer_shared_mem_spec.
      Proof.
        preserves_invariants_simpl';
        functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).
        - exploit ptResv2_low_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_low_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_high_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_high_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_kernel_mode; eauto.
        - exploit ptResv2_kernel_mode; eauto.
      Qed.

    End OFFER_SHARE.

    Global Instance shared_mem_status_inv:
      PreservesInvariants shared_mem_status_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
    Qed.

    Global Instance thread_spawn_inv: DNewInvariants thread_spawn_spec.
    Proof.
      constructor; intros; inv H0;
      unfold thread_spawn_spec in *;
      subdestruct; inv H; simpl; auto.

      - (* low level invariant *)
        constructor; trivial; intros; simpl in *.
        eapply kctxt_inject_neutral_gss_flatinj'; eauto.
        eapply kctxt_inject_neutral_gss_flatinj; eauto.

      - (* high_level_invariant *)
        constructor; simpl; eauto 2; try congruence; intros.
        + exploit split_container_valid; eauto.
          eapply container_split_some; eauto.
          auto.
        + unfold update_cusage, update_cchildren; zmap_solve.
        + eapply AbTCBStrong_range_gss_READY; eauto.
        + eapply AbQCorrect_range_gss_enqueue; eauto.
        + unfold update_cusage, update_cchildren; apply NotInQ_gso_ac_true; auto.
          zmap_simpl; repeat apply NotInQ_gso_true; auto.
        + eapply QCount_gss_spawn; eauto.
          eapply AbTCBStrong_range_impl; eauto.
          split; [|split; [|eauto]].
          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.
          apply cvalid_unused_next_child; auto.
        + eapply InQ_gss_spawn; eauto.
          eapply AbTCBStrong_range_impl; eauto.
          split; [|split; [|eauto]].
          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.
          apply cvalid_unused_next_child; auto.
        + unfold update_cusage, update_cchildren; apply CurIDValid_gso_neq_true; auto.
          zmap_simpl; repeat apply CurIDValid_gss_ac; auto.
          assert (Hneq:= cvalid_child_id_neq _ valid_container0 _ Hdestruct3); zmap_simpl.
          apply cvalid_unused_next_child; auto.
        + eapply SingleRun_gso_state_READY; eauto.
    Qed.

    Local Opaque remove.

    Global Instance thread_yield_inv: ThreadScheduleInvariants thread_yield_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst.
        assert (HOS: 0<= num_chan <= num_chan) by omega.
        exploit last_range_AbQ; eauto. intros Hrange.
        constructor; auto; simpl in *; intros; try congruence.
        + eapply AbTCBStrong_range_gss_RUN; eauto.
          eapply AbTCBStrong_range_gss_READY; eauto.
        + eapply AbQCorrect_range_gss_remove'; eauto.
          eapply list_range_enqueue; eauto.
          eapply AbQCorrect_range_impl; eauto.
        + eapply NotInQ_gso_neg; eauto.
          eapply NotInQ_gso_ac; eauto.
          eapply correct_curid0; eauto.
        + eapply QCount_gss_yield; eauto.
        + eapply InQ_gss_yield; eauto.
        + eapply CurIDValid_gss_last; eauto.
        + eapply SingleRun_gss_gso_cid; eauto. congruence.
    Qed.

    Global Instance thread_sleep_inv: ThreadTransferInvariants thread_sleep_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst.
        assert (HOS: 0<= num_chan <= num_chan) by omega.
        assert (HNeq: 64 <> n') by omega.
        exploit last_range_AbQ; eauto. intros Hrange.
        assert (HOS': 0 <= n' <= num_proc) by omega.
        assert (Hcid: ZMap.get (cid d) (abtcb d) = AbTCBValid RUN (-1))
          by (eapply correct_curid0; eauto).
        constructor; auto; simpl in *; intros; try congruence.
        + eapply AbTCBStrong_range_gss_RUN; eauto.
          eapply AbTCBStrong_range_gss_SLEEP; eauto.
        + eapply AbQCorrect_range_gss_remove; eauto.
          * eapply AbQCorrect_range_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
        + eapply NotInQ_gso_neg; eauto.
          eapply NotInQ_gso_ac; eauto.
          eapply correct_curid0; eauto.
        + eapply QCount_gss_remove; eauto.
          * eapply QCount_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
        + eapply InQ_gss_remove; eauto.
          * eapply InQ_gss_enqueue; eauto.
          * eapply QCount_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
          * apply last_correct; eauto.
        + eapply CurIDValid_gss_last; eauto.
        + eapply SingleRun_gss_gso_cid; eauto. congruence.
    Qed.

    (*Global Instance sendto_chan_inv: PreservesInvariants sendto_chan_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      eapply ChanPool_Valid_gss; eauto.
    Qed.*)

    Section THREAD_WAKEUP.

      Lemma thread_wakeup_high_level_inv:
        forall d d' n,
          thread_wakeup_spec n d = Some d' ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; simpl; eauto; intros.
        - eapply AbTCBStrong_range_gss_READY; eauto.
        - eapply AbQCorrect_range_gss_wakeup; eauto.
        - clear valid_curid0. eapply NotInQ_InQ_gss_wakeup; eauto.
        - eapply QCount_gss_wakeup; eauto.
        - eapply InQ_gss_wakeup; eauto.
        - eapply CurIDValid_gso_tcb; eauto.
          eapply last_neq_cid; eauto. omega.
        - eapply SingleRun_gso_state_READY; eauto.
      Qed.

      Lemma thread_wakeup_low_level_inv:
        forall d d' n n',
          thread_wakeup_spec n d = Some d' ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; eauto.
      Qed.

      Lemma thread_wakeup_kernel_mode:
        forall d d' n,
          thread_wakeup_spec n d = Some d' ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

      Global Instance thread_wakeup_inv: PreservesInvariants thread_wakeup_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply thread_wakeup_low_level_inv; eassumption.
        - eapply thread_wakeup_high_level_inv; eassumption.
        - eapply thread_wakeup_kernel_mode; eassumption.
      Qed.

    End THREAD_WAKEUP.

    (*Section RECEIVE_CHAN.

      Lemma receive_chan_high_level_inv:
        forall d d' n,
          receive_chan_spec d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_high_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2; simpl; intros.
        eapply ChanPool_Valid_gss; eauto.
      Qed.

      Lemma receive_chan_low_level_inv:
        forall d d' n n',
          receive_chan_spec d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_low_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2.
      Qed.

      Lemma receive_chan_kernel_mode:
        forall d d' n,
          receive_chan_spec d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_kernel_mode; eauto.
      Qed.

      Global Instance receive_chan_inv: PreservesInvariants receive_chan_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply receive_chan_low_level_inv; eassumption.
        - eapply receive_chan_high_level_inv; eassumption.
        - eapply receive_chan_kernel_mode; eassumption.
      Qed.

    End RECEIVE_CHAN.*)

    Global Instance syncsendto_chan_pre_inv: PreservesInvariants syncsendto_chan_pre_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      eapply SyncChanPool_Valid_gss; eauto.
    Qed.

    Global Instance syncsendto_chan_post_inv: PreservesInvariants syncsendto_chan_post_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      eapply SyncChanPool_Valid_gss; eauto.
    Qed.

    Section MEMCPY.

      Lemma flatmem_copy_high_level_inv:
        forall d d' from to len,
          flatmem_copy_spec len to from d = Some d'
          -> high_level_invariant d
          -> high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0.
        constructor; simpl; intros;
        try eapply dirty_ppage_gss_copy; eauto.
      Qed.

      Lemma flatmem_copy_low_level_inv:
        forall d d' from to len n,
          flatmem_copy_spec len to from d = Some d'
          -> low_level_invariant n d
          -> low_level_invariant n d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; eauto 2.
      Qed.

      Lemma flatmem_copy_kernel_mode:
        forall d d' from to len,
          flatmem_copy_spec len to from d = Some d'
          -> kernel_mode d
          -> kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

    End MEMCPY.

    Section SYNCRECEIVE_CHAN.

      Lemma syncreceive_chan_high_level_inv:
        forall fromid vaddr count d d' n,
          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_high_level_inv; eauto.
        exploit flatmem_copy_high_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2; simpl; intros.
        eapply SyncChanPool_Valid_gss; eauto.
      Qed.

      Lemma syncreceive_chan_low_level_inv:
        forall fromid vaddr count d d' n n',
          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_low_level_inv; eauto.
        exploit flatmem_copy_low_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2.
      Qed.

      Lemma syncreceive_chan_kernel_mode:
        forall fromid vaddr count d d' n,
          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_kernel_mode; eauto.
        exploit flatmem_copy_kernel_mode; eauto.
      Qed.

      Global Instance syncreceive_chan_inv: PreservesInvariants syncreceive_chan_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply syncreceive_chan_low_level_inv; eassumption.
        - eapply syncreceive_chan_high_level_inv; eassumption.
        - eapply syncreceive_chan_kernel_mode; eassumption.
      Qed.

    End SYNCRECEIVE_CHAN.

    Global Instance proc_init_inv: PreservesInvariants proc_init_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant.
      - apply real_nps_range.
      - apply real_lat_kern_valid.
      - apply real_lat_usr_valid.
      - apply real_container_valid.
      - rewrite init_pperm0; try assumption.
        apply Lreal_pperm_valid.
      - eapply real_pt_PMap_valid; eauto.
      - apply real_pt_PMap_kern.
      - omega.
      - assumption.
      - apply real_idpde_init.
      - apply real_pt_consistent_pmap.
      - apply real_pt_consistent_pmap_domain.
      - apply Lreal_at_consistent_lat_domain.
      - apply real_abtcb_strong_range'; eauto.
      - apply real_abq_range; auto.
      - eapply real_abtcb_pb_notInQ'; eauto.
      - eapply real_abtcb_abq_QCount'; eauto.
      - eapply real_abq_tcb_inQ; eauto.
      - omega.
      - eapply real_abtcb_AC_CurIDValid; eauto.
      - eapply real_abtcb_SingleRun; eauto.
      - eapply real_syncchpool_valid'; eauto.
    Qed.

    Global Instance device_output_inv: PreservesInvariants device_output_spec.
    Proof.
      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.
    Qed.

  End INV.

  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).

  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).

  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).
  Proof.
    split; inversion 1; intros.
    - functional inversion H0. split; trivial.
    - functional inversion H1.
      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.
  Qed.

  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.
  Proof.
    split; inversion 1; intros; constructor; auto.
  Qed.

  (** * Layer Definition *)
  Definition pipc_fresh : compatlayer (cdata RData) :=
    syncreceive_chan ↦ gensem syncreceive_chan_spec
                  ⊕ syncsendto_chan_pre ↦ gensem syncsendto_chan_pre_spec
                  ⊕ syncsendto_chan_post ↦ gensem syncsendto_chan_post_spec
                  ⊕ proc_init ↦ gensem proc_init_spec.

  Definition pipc_passthrough : compatlayer (cdata RData) :=
    fload ↦ gensem fload_spec
          ⊕ fstore ↦ gensem fstore_spec
          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec
          ⊕ device_output ↦ gensem device_output_spec
          ⊕ pfree ↦ gensem pfree_spec
          ⊕ set_pt ↦ gensem setPT_spec
          ⊕ pt_read ↦ gensem ptRead_spec
          ⊕ pt_resv ↦ gensem ptResv_spec
          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec
          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec

          ⊕ get_curid ↦ gensem get_curid_spec
          ⊕ thread_spawn ↦ dnew_compatsem thread_spawn_spec
          ⊕ thread_wakeup ↦ gensem thread_wakeup_spec

          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)
          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)
          ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec
          ⊕ container_get_quota ↦ gensem container_get_quota_spec
          ⊕ container_get_usage ↦ gensem container_get_usage_spec
          ⊕ container_can_consume ↦ gensem container_can_consume_spec
          ⊕ container_alloc ↦ gensem alloc_spec
          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec
          ⊕ trap_out ↦ primcall_general_compatsem trapout_spec
          ⊕ host_in ↦ primcall_general_compatsem hostin_spec
          ⊕ host_out ↦ primcall_general_compatsem hostout_spec
          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec
          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec

          ⊕ thread_yield ↦ primcall_thread_schedule_compatsem thread_yield_spec (prim_ident:= thread_yield)
          ⊕ thread_sleep ↦ primcall_thread_transfer_compatsem thread_sleep_spec

          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.

  Definition pipc : compatlayer (cdata RData) := pipc_fresh ⊕ pipc_passthrough.

  (*Definition semantics := LAsm.Lsemantics pipc.*)

End WITHMEM.


Require Import floyd.proofauto.
Import ListNotations.
Local Open Scope logic.

Require Import hmacdrbg.entropy.
Require Import hmacdrbg.entropy_lemmas.
Require Import hmacdrbg.hmac_drbg.
Require Import hmacdrbg.DRBG_functions.
Require Import hmacdrbg.HMAC_DRBG_algorithms.
Require Import hmacdrbg.spec_hmac_drbg.
Require Import hmacdrbg.spec_hmac_drbg_pure_lemmas.
Require Import hmacdrbg.HMAC_DRBG_common_lemmas.

Definition my_fold_right {A B} (f : B -> A -> A) (a : A):=
fix my_fold_right (l : list B) : A :=
  match l with
  | [] => a
  | b :: t => f b (my_fold_right t)
  end.
Lemma my_fold_right_eq {A B} (f : B -> A -> A) a: my_fold_right f a = fold_right f a.
Proof. extensionality l. induction l; auto. Qed.

Lemma FRZL_ax' ps: FRZL ps = my_fold_right sepcon emp ps.
Proof. rewrite FRZL_ax. rewrite my_fold_right_eq. trivial. Qed.

(*Tactic requires the resulting goal to be normalized manually.*)
Ltac my_thaw' name :=
  rewrite (FRZL_ax' name); unfold name, abbreviate; clear name.

(*add simplification of the list operations inside the freezer,
   flatten the sepcon, and eliminate the emp term*)
Ltac my_thaw name :=
  my_thaw' name; simpl nat_of_Z; unfold my_delete_nth, my_nth, my_fold_right;
  repeat flatten_sepcon_in_SEP; repeat flatten_emp.

Lemma isptrD v: isptr v -> exists b ofs, v = Vptr b ofs.
Proof. intros. destruct v; try contradiction. eexists; eexists; reflexivity. Qed.

Lemma REST: forall (Espec : OracleKind) (contents : list Z) additional add_len ctx
  md_ctx' V' reseed_counter' entropy_len' prediction_resistance' reseed_interval'
  key V reseed_counter entropy_len prediction_resistance reseed_interval kv
  info_contents (s : ENTROPY.stream)
(*Delta_specs := abbreviate : PTree.t funspec*)
  seed
  (XH : 0 <= add_len <= Int.max_unsigned)
  (XH0 : Zlength V = 32)
  (XH1 : add_len = Zlength contents)
  (contents' : list Z)
  (Heqcontents' : contents' = contents_with_add additional add_len contents)
  (ELc' : 0 < entropy_len + Zlength contents' (* <= 384*))
(*  (ELc' : 0 < entropy_len + Zlength contents (* <= 384*))*)
  (XH3 : Forall general_lemmas.isbyteZ V)
  (XH4 : Forall general_lemmas.isbyteZ contents)
  (XH5 : map Vint (map Int.repr V) = V')
  (XH6 : Vint (Int.repr reseed_counter) = reseed_counter')
  (XH7 : Vint (Int.repr entropy_len) = entropy_len')
  (XH8 : Vint (Int.repr reseed_interval) = reseed_interval')
  (XH9 : Val.of_bool prediction_resistance = prediction_resistance')
  (PNadditional : is_pointer_or_null additional)
  (Pctx : isptr ctx)
  (ELnonneg : 0 <= entropy_len)
  (ZLc' : Zlength contents' = 0 \/ Zlength contents' = Zlength contents)
  (*(H10 : zlt 256 add_len = false)
  (H11 : zlt 384 (entropy_len + add_len) = false)*)
  (Hfield : field_compatible (tarray tuchar 384) [] seed)
  (AL256 : (add_len >? 256) = false)
  (EAL384 : (entropy_len + add_len >? 384) = false)
  (entropy_bytes : list Z)
  (s0 : ENTROPY.stream)
  (Heqentropy_result : ENTROPY.success entropy_bytes s0 = ENTROPY.get_bytes (Z.to_nat entropy_len) s),
@semax hmac_drbg_compspecs.CompSpecs Espec
  (initialized_list [_entropy_len; _t'2; _t'1]
     (func_tycontext f_mbedtls_hmac_drbg_reseed HmacDrbgVarSpecs
        HmacDrbgFunSpecs))
  (PROP ( )
   LOCAL (temp _t'2 Vzero; temp _entropy_len (Vint (Int.repr entropy_len));
   lvar _seed (tarray tuchar 384) seed; temp _ctx ctx; temp _additional additional;
   temp _len (Vint (Int.repr add_len)); gvar sha._K256 kv)
   SEP (Stream (get_stream_result (get_entropy 0 entropy_len entropy_len false s));
   data_at Tsh (tarray tuchar entropy_len) (map Vint (map Int.repr entropy_bytes)) seed;
   data_at Tsh (tarray tuchar (384 - entropy_len))
     (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero))
     (offset_val entropy_len seed);
   da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional;
   md_full key md_ctx';
   data_at Tsh t_struct_mbedtls_md_info info_contents
     (hmac256drbgstate_md_info_pointer
        (md_ctx',
        (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))));
   spec_sha.K_vector kv;
   data_at Tsh t_struct_hmac256drbg_context_st
     (md_ctx',
     (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval')))))
     ctx))
  (Ssequence (Sset _seedlen (Etempvar _entropy_len tuint))
     (Ssequence
        (Ssequence
           (Sifthenelse
              (Ebinop Cop.One (Etempvar _additional (tptr tuchar))
                 (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)) tint)
              (Sset _t'3
                 (Ecast
                    (Ebinop Cop.One (Etempvar _len tuint) (Econst_int (Int.repr 0) tint) tint)
                    tbool)) (Sset _t'3 (Econst_int (Int.repr 0) tint)))
           (Sifthenelse (Etempvar _t'3 tint)
              (Ssequence
                 (Scall None
                    (Evar _memcpy
                       (Tfunction
                          (Tcons (tptr tvoid) (Tcons (tptr tvoid) (Tcons tuint Tnil)))
                          (tptr tvoid) cc_default))
                    [Ebinop Oadd (Evar _seed (tarray tuchar 384))
                       (Etempvar _seedlen tuint) (tptr tuchar);
                    Etempvar _additional (tptr tuchar); Etempvar _len tuint])
                 (Sset _seedlen
                    (Ebinop Oadd (Etempvar _seedlen tuint) (Etempvar _len tuint) tuint)))
              Sskip))
        (Ssequence
           (Scall None
              (Evar _mbedtls_hmac_drbg_update
                 (Tfunction
                    (Tcons (tptr (Tstruct _mbedtls_hmac_drbg_context noattr))
                       (Tcons (tptr tuchar) (Tcons tuint Tnil))) tvoid cc_default))
              [Etempvar _ctx (tptr (Tstruct _mbedtls_hmac_drbg_context noattr));
              Evar _seed (tarray tuchar 384); Etempvar _seedlen tuint])
           (Ssequence
              (Sassign
                 (Efield
                    (Ederef
                       (Etempvar _ctx (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))
                       (Tstruct _mbedtls_hmac_drbg_context noattr)) _reseed_counter tint)
                 (Econst_int (Int.repr 1) tint))
              (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))
 (frame_ret_assert
     (function_body_ret_assert tint
        (fun a : environ =>
         EX x : val,
         (PROP ( )
          LOCAL (temp ret_temp x)
          SEP (reseedPOST x contents additional add_len s
                 (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval) ctx
                 info_contents kv
                 (md_ctx',
                 (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))))) a))
     (fun a : environ =>
      EX x : val,
      local (lvar_denote _seed (tarray tuchar 384) x) a && ` (data_at_ Tsh (tarray tuchar 384) x) a)).
Proof.
  intros.
  assert (ZLbytes: Zlength entropy_bytes = entropy_len).
    { eapply get_bytes_Zlength. omega. eassumption. }
  apply Zgt_is_gt_bool_f in EAL384.
  abbreviate_semax.
(*  remember (contents_with_add additional add_len contents) as contents'.
  assert (ZLc': Zlength contents' = 0 \/ Zlength contents' = Zlength contents).
    { subst contents'. unfold contents_with_add.
      destruct (eq_dec add_len 0); simpl.
        rewrite andb_false_r. left; apply Zlength_nil.
        destruct (Memory.EqDec_val additional nullval); simpl. left; apply Zlength_nil.
        right; trivial.
    }
*)
  freeze [0;(*2;*)4;5;6;7] FR6. freeze [1;2] SEED.

  replace_SEP 0 (data_at Tsh (tarray tuchar 384)
         ((map Vint
            (map Int.repr entropy_bytes)) ++ (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero))) seed).
  {
    entailer!. thaw SEED; clear FR6. (*subst entropy_len.*) rewrite sepcon_emp.
    apply derives_refl'. symmetry.
    apply data_at_complete_split; repeat rewrite Zlength_map;
    try rewrite (*Hentropy_bytes_length,*) Zlength_list_repeat; try rewrite Zplus_minus; trivial; omega.
  }

  (* seedlen = entropy_len; *)
  clear SEED. freeze [0;1] FR7.
  forward.
(*  remember (if eq_dec additional nullval then false else if eq_dec add_len 0 then false else true) as non_empty_additional.*)
  remember (andb (negb (eq_dec additional nullval)) (negb (eq_dec add_len 0))) as non_empty_additional.

  forward_if (
      PROP  ()
      LOCAL  (temp _seedlen (Vint (Int.repr (entropy_len)));
      temp _entropy_len (Vint (Int.repr entropy_len));
      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;
      temp _additional additional; temp _len (Vint (Int.repr add_len));
      temp _t'3 (Val.of_bool non_empty_additional);
      gvar sha._K256 kv)
      SEP  (FRZL FR7; da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional)).
  { destruct additional; simpl in PNadditional; try contradiction.
    + subst i. rewrite da_emp_null. entailer. reflexivity.
    + rewrite da_emp_ptr. normalize.
      eapply denote_tc_test_eq_split; auto 50 with valid_pointer.
      (* TODO regression, this should have solved it *)
      apply sepcon_valid_pointer2.
      apply data_at_valid_ptr; auto. }
  { (*nonnull additional*)
    destruct additional; simpl in PNadditional; try contradiction. subst i. elim H; trivial. clear H.
    forward. entailer!. simpl.
    destruct (initial_world.EqDec_Z (Zlength contents) 0).
    + rewrite e. simpl. reflexivity.
    + simpl in *. rewrite Int.eq_false; simpl. reflexivity.
      intros N.
      assert (Y: Int.unsigned (Int.repr (Zlength contents)) = Int.unsigned (Int.repr 0)) by (rewrite N; trivial).
      clear N. rewrite Int.unsigned_repr in Y. 2: omega. rewrite Int.unsigned_repr in Y; omega.
  }
  { (*nullval additional*)
    rewrite H in *.
    forward. entailer!.
  }
  thaw FR7.
(*  freeze [1;2] FR8.*) (*my_thaw FR6.*)
  forward_if (
      PROP  ()
      LOCAL  (temp _seedlen (Vint (Int.repr (entropy_len + Zlength contents')));
      temp _entropy_len (Vint (Int.repr entropy_len));
      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;
      temp _additional additional; temp _len (Vint (Int.repr add_len));
      gvar sha._K256 kv)
      SEP (data_at Tsh (tarray tuchar 384)
         (map Vint
            (map Int.repr entropy_bytes) ++ (map Vint (map Int.repr (*contents*)contents')) ++
          list_repeat (Z.to_nat (384 - entropy_len - Zlength (*contents*)contents')) (Vint Int.zero)) seed;
           (*FRZL FR8*)FRZL FR6;
       da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional)).
  + rewrite H in Heqnon_empty_additional. rename H into NEA.
    destruct additional; simpl in PNadditional; try contradiction.
    - subst i; simpl in *; discriminate.
    - destruct (eq_dec add_len 0); try discriminate.
      subst non_empty_additional; clear Heqnon_empty_additional.
    rename b into bb. rename i into ii.
    rewrite da_emp_ptr. Intros. rename H into addlen_pos.
    assert (contents' = contents).
    { subst contents'. unfold contents_with_add. simpl.
        destruct (initial_world.EqDec_Z add_len 0). omega. reflexivity. }
    clear Heqcontents'; subst contents'. clear ZLc'.
    replace_SEP 0 ((data_at Tsh (tarray tuchar entropy_len)
         (map Vint
            (map Int.repr entropy_bytes)) seed) * (data_at Tsh (tarray tuchar (384 - entropy_len))
         (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) (offset_val entropy_len seed))).
    {
      entailer!.
      apply derives_refl'; apply data_at_complete_split; trivial; try omega.
      rewrite Zlength_app in H; rewrite H; trivial.
      repeat rewrite Zlength_map; trivial.
      rewrite Zlength_list_repeat; omega.
    }
    flatten_sepcon_in_SEP. rewrite data_at_isptr with (p:=seed); Intros.
    apply isptrD in Pseed; destruct Pseed as [b [i SEED]]; rewrite SEED in *.
    change (offset_val entropy_len (Vptr b i)) with (Vptr b (Int.add i (Int.repr entropy_len))).
    assert_PROP (field_compatible (Tarray tuchar (384 - entropy_len) noattr)
          [] (Vptr b (Int.add i (Int.repr entropy_len)))) as FC_el by entailer!.
    simpl in *.
    replace_SEP 1 (
      (data_at Tsh (tarray tuchar (Zlength contents))
         (list_repeat (Z.to_nat (Zlength contents)) (Vint Int.zero)) (Vptr b (Int.add i (Int.repr entropy_len)))) *
      (data_at Tsh (tarray tuchar (384 - entropy_len - Zlength contents))
         (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents)) (Vint Int.zero)) (offset_val (Zlength contents) (Vptr b (Int.add i (Int.repr entropy_len)))))).
    { (*
      subst entropy_len.
      replace (384 - 32) with 352 by omega.
      remember (Vptr b (Int.add i (Int.repr 32))) as seed'.
      clear Heqseed'.
      (*entailer!*) go_lower.
      replace (length contents) with (Z.to_nat (Zlength contents)) by
        (rewrite Zlength_correct; apply Nat2Z.id).
      apply derives_refl'; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto.
      {
        (*replace (Zlength contents + (352 - Zlength contents')) with (384 - 32) by omega.*)
        replace (Zlength contents + (352 - Zlength contents)) with 352 by omega.
        replace (384-32) with 352 in H11 by omega.
        assumption.
      }
      {
        rewrite list_repeat_app.
        rewrite <- Z2Nat.inj_add; try omega.
        replace (Zlength contents + (352 - Zlength contents)) with 352 by omega.
        reflexivity.
      }*)
      remember (Vptr b (Int.add i (Int.repr entropy_len))) as seed'.
      clear Heqseed'.
      (*entailer!*) go_lower.
      apply derives_refl'.
      apply data_at_complete_split; try rewrite Zlength_list_repeat; try omega; auto.
      + rewrite Zlength_list_repeat.
        replace (Zlength contents + (384 - entropy_len - Zlength contents)) with (384 - entropy_len); trivial; omega.
        omega.
      + rewrite list_repeat_app, <- Z2Nat.inj_add.
        replace (Zlength contents + (384 - entropy_len - Zlength contents)) with (384 - entropy_len); trivial; omega.
        omega. omega.
    }

    flatten_sepcon_in_SEP.
    replace_SEP 1 (memory_block Tsh (Zlength contents) (Vptr b (Int.add i (Int.repr entropy_len)))).
    { entailer!. replace (Zlength contents) with (sizeof (*cenv_cs*) (tarray tuchar (Zlength contents))) at 2.
      apply data_at_memory_block. simpl. rewrite Zmax0r; omega.
    }
    forward_call ((Tsh, Tsh), (Vptr b (Int.add i (Int.repr entropy_len))), (*additional*)Vptr bb ii, Zlength contents, map Int.repr contents).
    {
      (* type checking *)
      red in LV.
      unfold eval_var. destruct (Map.get (ve_of rho) _seed); try contradiction.
      destruct p; destruct LV  as [LV1 LV2]; inversion LV2. subst b0 i t; simpl; trivial.
    }
    {
      (* match up function parameter *)
      rewrite XH1; simpl.
      apply prop_right; trivial.
    }
    {
      (* match up SEP clauses *)
      change (fst (Tsh, Tsh)) with Tsh;
      change (snd (Tsh, Tsh)) with Tsh.
      (*change (@data_at spec_sha.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))
         (@map int val Vint (@map Z int Int.repr contents)) additional) with (@data_at hmac_drbg_compspecs.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))
         (@map int val Vint (@map Z int Int.repr contents)) additional).*)
      cancel. my_thaw FR6.
      rewrite XH1; cancel.
    }
    {
      (* prove the PROP clauses *)
      repeat split; auto; omega.
    }
    (*Intros memcpy_vret. subst memcpy_vret.*)
    forward.
    change (fst (Tsh, Tsh)) with Tsh;
    change (snd (Tsh, Tsh)) with Tsh.
    rewrite XH1, SEED.

    (* Time entailer!. (*8.5pl2: 1230secs*) *)
    go_lower. normalize.
    apply andp_right. apply prop_right. repeat split; auto.

    thaw FR6. rewrite (*H1,*) da_emp_ptr. normalize.
    apply andp_right. apply prop_right. simpl. (*specialize (Zlength_nonneg contents).*) subst add_len; omega.
    cancel.
    erewrite data_at_complete_split with
     (A:=map Vint (map Int.repr entropy_bytes))
     (p:=Vptr b i)(*(offset:=entropy_len)*)
     (AB:= (map Vint (map Int.repr entropy_bytes) ++
       map Vint (map Int.repr contents) ++
       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))
         (Vint Int.zero))).
    7: solve[reflexivity].
    cancel.
    6: solve[reflexivity].
    3: solve [repeat rewrite Zlength_map; omega].

    3: solve [reflexivity].
    3: solve [rewrite Zlength_app, Zlength_list_repeat; repeat rewrite Zlength_map; try omega].

    Focus 2. rewrite Zlength_app, (* <- H17, *) Zlength_list_repeat; try omega.
             repeat rewrite Zlength_map. rewrite ZLbytes(*, H2*).
             assert (X: entropy_len + (Zlength contents + (384 - entropy_len - Zlength contents)) = 384) by omega.
             rewrite X; assumption.

    rewrite Zlength_app; repeat rewrite Zlength_map; rewrite Zlength_list_repeat.
    assert (X: Zlength contents + (384 - entropy_len - Zlength contents) = 384 - entropy_len) by omega.
    rewrite X.
    erewrite data_at_complete_split with (AB:=map Vint (map Int.repr contents) ++
       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))
         (Vint Int.zero))
      (p:=(Vptr b (Int.add i (Int.repr entropy_len))))
      (A:= map Vint (map Int.repr contents)).
    7: reflexivity. 3: reflexivity. 5: reflexivity.
    3: reflexivity. 3: solve [rewrite Zlength_list_repeat; repeat rewrite Zlength_map; try omega].

    unfold offset_val. rewrite Int.add_assoc, add_repr. repeat rewrite Zlength_map. cancel. (*apply derives_refl.*)
    repeat rewrite Zlength_map. rewrite Zlength_list_repeat; try omega.
    apply derives_refl.
    rewrite Zlength_list_repeat; repeat rewrite Zlength_map; try omega. rewrite X; assumption.

    omega.

  + rewrite H in Heqnon_empty_additional; clear H.
    forward.
    go_lower. normalize.
    assert (contents' = nil).
    { subst contents'. unfold contents_with_add.
      destruct (eq_dec add_len 0); simpl in *.
      + rewrite e in *. rewrite andb_false_r; trivial.
      + destruct (Memory.EqDec_val additional nullval); simpl in *; trivial; discriminate. }
    clear Heqcontents'; subst contents'.
    rewrite Zlength_nil, Zplus_0_r.
    apply andp_right.
    apply prop_right. repeat split; trivial.
    do 2 rewrite map_nil. rewrite app_nil_l, Zminus_0_r. cancel.

  + (*continuation after conditional*)

  replace_SEP 0 (
    (data_at Tsh (tarray tuchar (entropy_len + Zlength contents')) (map Vint
            (map Int.repr entropy_bytes) ++
            map Vint (map Int.repr contents')) seed) *
    (data_at Tsh (tarray tuchar (384 - (entropy_len + Zlength contents'))) (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents'))
            (Vint Int.zero)) (offset_val (entropy_len + Zlength contents') seed))
      ).
  {
    clear Heqcontents'.
    rewrite app_assoc.
    entailer!.
    rewrite Zlength_app, Zlength_list_repeat in H; try omega.
    apply derives_refl'.
    apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto;
      (* rewrite Zlength_app;*)try rewrite H; try rewrite Hentropy_bytes_length; repeat rewrite Zlength_map; auto.
  }
  flatten_sepcon_in_SEP.

  do 2 rewrite map_map.
  rewrite <- map_app.
  rewrite <- map_map.
  thaw FR6.
  rewrite data_at_isptr with (p:=seed). Intros.

  (*mbedtls_hmac_drbg_update( ctx, seed, seedlen )*)
  freeze [1;2;7] FR9.
  remember (entropy_len + Zlength contents') as ll.
  repeat rewrite Zlength_map in Hentropy_bytes_length.
  forward_call (entropy_bytes ++ contents', seed, ll,
                ctx,
                (md_ctx',
                 (map Vint (map Int.repr V),
                 (Vint (Int.repr reseed_counter),
                 (Vint (Int.repr entropy_len),
                 (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))),
                (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval),
                kv, info_contents).
  {
    (* prove the SEP clauses match up *)
    destruct seed; simpl in Pseed; try contradiction.
    rewrite da_emp_ptr.
    rewrite Zlength_app.
    rewrite ZLbytes. simpl.
    normalize. apply andp_right. apply prop_right. repeat split; trivial.
      { omega. (*subst contents' add_len. unfold contents_with_add.
        destruct (eq_dec (Zlength contents) 0); simpl in *.
        + rewrite andb_false_r, Zlength_nil. rewrite e, Zplus_0_r in *.
          destruct ZL
          rewrite Z.max_r; omega.
        + rewrite andb_true_r.
          destruct (Memory.EqDec_val additional nullval); simpl in *. right. omega.*) }
    rewrite <- Heqll, XH5, XH6, XH7, XH8, XH9. cancel.
  }
  {
    (* prove the PROP clauses *)
    simpl in *. repeat split; trivial; try omega. (*
    rewrite H2 in *;*) rewrite int_max_unsigned_eq. omega.
    left; rewrite Zlength_app, ZLbytes; trivial.
    { apply isbyteZ_app; try assumption.
      eapply get_bytes_isbyteZ; eauto.
      subst contents'; unfold contents_with_add.
      destruct (eq_dec add_len 0); simpl.
        rewrite andb_false_r. constructor.
      destruct (Memory.EqDec_val additional nullval); simpl. constructor.
      trivial.
    }
  }
  unfold hmac256drbgabs_common_mpreds.
  repeat flatten_sepcon_in_SEP.
  thaw FR9.
  freeze [1;2;4;6;7] FR10.
  freeze [0;1] FR11.
  gather_SEP 1 2.
  replace_SEP 0 (data_at Tsh (tarray tuchar 384) ((map Vint
         (map Int.repr entropy_bytes)) ++ (map Vint (map Int.repr contents') ++
       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents'))
         (Vint Int.zero))) seed).
  { (*
    subst entropy_len.
    replace (384 - 32) with 352 by omega.
    replace (384 - (32 + Zlength contents')) with (352 - Zlength contents') by omega.*)
    rewrite app_assoc.
    rewrite map_map.
    rewrite map_app.
    rewrite <- map_map.
    replace (map (fun x : Z => Vint (Int.repr x)) contents') with (map Vint (map Int.repr contents')) by (rewrite map_map; auto).
    clear Heqcontents'.
    rewrite Zlength_app, ZLbytes.
    entailer!.
    destruct seed; simpl in Pseed; try contradiction.
    rewrite da_emp_ptr. Intros.
    apply derives_refl'; symmetry; apply data_at_complete_split;
     repeat rewrite Zlength_list_repeat; try omega; auto; try rewrite Zlength_app;
     try rewrite ZLbytes; repeat rewrite Zlength_map; auto.
     replace (Zlength entropy_bytes + Zlength contents' +
      (384 - Zlength entropy_bytes - Zlength contents')) with 384 by omega.
     assumption.
  }

  (* ctx->reseed_counter = 1; *)
  my_thaw FR11.
  freeze [0;1] FR12. rewrite XH5, XH6, XH7, XH8, XH9.
  unfold hmac256drbgabs_to_state. simpl.
  remember (HMAC256_DRBG_functional_prog.HMAC256_DRBG_update
            (contents_with_add seed ll
               (entropy_bytes ++ contents')) key V).
  destruct p.
  simpl. normalize. rewrite XH6, XH7, XH8, XH9. drop_LOCAL 0%nat. drop_LOCAL 0%nat.
  subst contents'.
  unfold_data_at 1%nat. (*crucial: doing the field assignment without unfolding data_at results in the forward taking 1200secs*)
(*  freeze [0;1;2;4;5;6] FIELDS. optional wrt performance*)
  forward.

  (* return 0 *)
  idtac "Timing a forward (goal: 5secs)". Time forward. (*5 secs*)
  Exists seed (Vint (Int.repr 0)). normalize.
  entailer!.

  assert (ZL1: Zlength (contents_with_add additional (Zlength contents) contents) >? 256 = false).
  { clear - ZLc' AL256. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; trivial. }

  apply Zgt_is_gt_bool_f in AL256.
  assert (Z: (zlt 256 (Zlength contents)
       || zlt 384
            (hmac256drbgabs_entropy_len
               (HMAC256DRBGabs key V reseed_counter (Zlength entropy_bytes) prediction_resistance
                  reseed_interval) + Zlength contents))%bool = false).
  { destruct (zlt 256 (Zlength contents)); simpl; try omega.
    destruct (zlt 384 (Zlength entropy_bytes + Zlength contents)); simpl; trivial. omega.
  }
  unfold reseedPOST. rewrite Z.
  entailer!.
  { unfold return_value_relate_result. simpl.
    rewrite andb_negb_r, ZL1.
    unfold get_entropy. rewrite <- Heqentropy_result. trivial. }
(*  remember (mbedtls_HMAC256_DRBG_reseed_function s
            (HMAC256DRBGabs key V reseed_counter (Zlength entropy_bytes) prediction_resistance reseed_interval)
            (contents_with_add additional (Zlength contents) contents)).*)
  simpl.
  rewrite andb_negb_r, ZL1.
  unfold get_entropy. rewrite <- Heqentropy_result.
  remember (HMAC_DRBG_update HMAC256_functional_prog.HMAC256
              (entropy_bytes ++ contents_with_add additional (Zlength contents) contents) key V) as q.
  destruct q. normalize.
  thaw FR12. thaw FR10. cancel. simpl. rewrite <- Heqp.
  unfold  hmac256drbgabs_common_mpreds. cancel.
  unfold get_entropy; rewrite <- Heqentropy_result. simpl. normalize. entailer!.
  { simpl in *. unfold HMAC_DRBG_update in Heqq.
    destruct (entropy_bytes ++
         contents_with_add additional (Zlength contents) contents); inv Heqq.
    + split. apply hmac_common_lemmas.HMAC_Zlength. apply hmac_common_lemmas.isbyte_hmac.
    + split. apply hmac_common_lemmas.HMAC_Zlength. apply hmac_common_lemmas.isbyte_hmac.
  }
  unfold_data_at 1%nat. cancel.
  unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_update in Heqp.
  destruct seed; simpl in Pseed; try contradiction.
  unfold contents_with_add in Heqp at 1. simpl in Heqp.
  destruct (initial_world.EqDec_Z (Zlength entropy_bytes +
                 Zlength (contents_with_add additional (Zlength contents) contents)) 0); simpl in Heqp.
  specialize (Zlength_nonneg (contents_with_add additional (Zlength contents) contents)).
  intros; omega.

  rewrite <- Heqp in *. inv Heqq.
idtac "Timing the Qed of REST (goal: 45secs)". cancel.
Time Qed. (*Feb 23 2017: 216.218 secs (135.625u,0.046s) (successful)*)
         (*was: Coq8.5pl2: 44secs*)

Lemma body_hmac_drbg_reseed: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs
       f_mbedtls_hmac_drbg_reseed hmac_drbg_reseed_spec.
Proof.
  start_function.
  rename lvar0 into seed.
  destruct initial_state_abs.
  destruct initial_state as [md_ctx' [V' [reseed_counter' [entropy_len' [prediction_resistance' reseed_interval']]]]].
  unfold hmac256drbg_relate.
  Intros. simpl in *.
  rename H into XH1.
  rename H0 into XH2.
  rename H1 into XH3.
  rename H2 into XH4.
  rename H3 into El2.
  rename H4 into XH6.
  rename H5 into XH7.
  rename H6 into XH8.
  rename H7 into XH9.
  rename H8 into XH10.
  rename H9 into XH11.
  rename H10 into XH12.
  rename H11 into XH13.
  rewrite da_emp_isptrornull. (*needed later*)
  rewrite data_at_isptr with (p:=ctx).
  Intros.

  (* entropy_len = ctx->entropy_len *)
  simpl in *.
  remember (contents_with_add additional add_len contents) as contents'.
  assert (ZLc': Zlength contents' = 0 \/ Zlength contents' = Zlength contents).
    { subst contents'. unfold contents_with_add.
      destruct (eq_dec add_len 0); simpl.
        rewrite andb_false_r. left; apply Zlength_nil.
        destruct (Memory.EqDec_val additional nullval); simpl. left; apply Zlength_nil.
        right; trivial.
    }

  freeze [0;1;3;4;5;6] FR1.
  forward. (*{ rewrite <- H7; entailer!. }*)

  remember (orb (zlt 256 add_len) (zlt 384 (entropy_len + add_len))) as add_len_too_high.

  (* if (len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
        entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) *)
  freeze [0;1] FR2.
  forward_if (PROP  ()
      LOCAL  (temp _entropy_len (Vint (Int.repr entropy_len));
      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;
      temp _additional additional; temp _len (Vint (Int.repr add_len));
      temp _t'1 (Val.of_bool add_len_too_high);
      gvar sha._K256 kv)
      SEP  (FRZL FR2)).
  { forward. entailer!. }
  { forward. entailer!. simpl.
      unfold Int.ltu; simpl.
      rewrite add_repr.
      rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.
      rewrite Int.unsigned_repr_eq, Zmod_small.
      + destruct (zlt 384 (entropy_len + (Zlength contents))); simpl; try reflexivity.
      + omega.
  }

  forward_if (PROP  (add_len_too_high = false)
      LOCAL  (temp _entropy_len (Vint (Int.repr entropy_len));
      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;
      temp _additional additional; temp _len (Vint (Int.repr add_len));
      gvar sha._K256 kv)
      SEP (FRZL FR2)
  ).
  { rewrite H in *. subst add_len_too_high. forward.
    Exists seed (Vint (Int.neg (Int.repr 5))). normalize. entailer!.
    unfold reseedPOST. simpl; rewrite <- Heqadd_len_too_high.
    (*remember (zlt 256 (Zlength contents) || zlt 384 (entropy_len + Zlength contents))%bool as c.
    destruct c; simpl in Heqadd_len_too_high; try discriminate.*)
    normalize. apply andp_right. apply prop_right; repeat split; trivial.
    thaw FR2. thaw FR1. cancel.
  }
  {
    forward.
    entailer!.
  }
  Intros. rewrite H in *; clear H add_len_too_high.
  symmetry in Heqadd_len_too_high; apply orb_false_iff in Heqadd_len_too_high; destruct Heqadd_len_too_high.

  assert (AL256: 256 >= add_len).
  { destruct (zlt 256 add_len); try discriminate; trivial. }
  assert (EL384 : 384 >= entropy_len + add_len).
  { destruct ( zlt 384 (entropy_len + add_len)); try discriminate; trivial. }

  thaw FR2. thaw FR1. freeze [1;2;3;4;5;6] FR3.
  (* memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT ); *)
  forward_call (Tsh, seed, 384, Int.zero).
  { rewrite data_at__memory_block.
    change (sizeof (*cenv_cs*) (tarray tuchar 384)) with 384.
    normalize. cancel.
  }

  (*freeze [1;2;3;4;5;6] FR3.*)
  assert_PROP (field_compatible (tarray tuchar 384) [] seed) as Hfield by entailer!.
  replace_SEP 0 ((data_at Tsh (tarray tuchar entropy_len)
         (list_repeat (Z.to_nat entropy_len) (Vint Int.zero)) seed) * (data_at Tsh (tarray tuchar (384 - entropy_len))
         (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) (offset_val entropy_len seed))).
  {
    (*subst entropy_len.*)
    erewrite <- data_at_complete_split with (length:=384)(AB:=list_repeat (Z.to_nat 384) (Vint Int.zero)); repeat rewrite Zlength_list_repeat; trivial; try omega.
    go_lower. apply derives_refl. rewrite Zplus_minus. assumption.
    rewrite list_repeat_app. rewrite Z2Nat.inj_sub; try omega. rewrite le_plus_minus_r. trivial. apply Z2Nat.inj_le; try omega.
  }
  flatten_sepcon_in_SEP.

  replace_SEP 0 (memory_block Tsh entropy_len seed).
  {
    (*subst entropy_len.*) go_lower.
     eapply derives_trans. apply data_at_memory_block. simpl. rewrite Z.max_r, Z.mul_1_l; trivial.
  }

  (* get_entropy(seed, entropy_len ) *)
  thaw FR3. freeze [1;2;3;4;6;7] FR4.
  forward_call (Tsh, s, seed, entropy_len).
  { split. split; try omega. rewrite int_max_unsigned_eq. omega.
    apply writable_share_top.
(*
    subst entropy_len; auto.*)
  }
  Intros vret. rename H1 into ENT.
  assert (AL256': add_len >? 256 = false).
  { remember (add_len >? 256) as d.
    destruct d; symmetry in Heqd; trivial.
    apply Zgt_is_gt_bool in Heqd.
    destruct (zlt 256 add_len); try discriminate; omega.
  }
  assert (EAL256': (entropy_len + add_len)  >? 384 = false).
  { remember (entropy_len + add_len >? 384) as d.
    destruct d; symmetry in Heqd; trivial.
    apply Zgt_is_gt_bool in Heqd.
    destruct (zlt 384 (entropy_len + add_len)); try discriminate; omega.
  }

  (* if( get_entropy(seed, entropy_len ) != 0 ) *)
  freeze [0;1;2] FR5.
  forward_if (
      PROP  (vret=Vzero)
      LOCAL  (temp _t'2 vret;
      temp _entropy_len (Vint (Int.repr entropy_len));
      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;
      temp _additional additional; temp _len (Vint (Int.repr add_len));
      gvar sha._K256 kv)
      SEP (FRZL FR5)
  ).
  {
    (* != 0 case *)
    forward.
    Exists seed (Vint (Int.neg (Int.repr (9)))). normalize. entailer!.
    unfold reseedPOST.
    remember ((zlt 256 (Zlength contents)
       || zlt 384
            (hmac256drbgabs_entropy_len
               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance
                  reseed_interval) + (Zlength contents)))%bool) as z.
    destruct z.
    { exfalso. simpl in Heqz. rewrite H, H0 in Heqz. inv Heqz. }
    clear Heqz.
    unfold return_value_relate_result, get_entropy in ENT.
    simpl in ENT.
    remember (ENTROPY.get_bytes (Z.to_nat entropy_len) s) as  GE.
    destruct GE.
    + inv ENT. discriminate.
    + thaw FR5. unfold get_entropy. rewrite <- HeqGE.
      remember (mbedtls_HMAC256_DRBG_reseed_function s
            (HMAC256DRBGabs key V reseed_counter 32 prediction_resistance
               reseed_interval) (contents_with_add additional (Zlength contents) contents)) as M.
      remember (mbedtls_HMAC256_DRBG_reseed_function s
             (HMAC256DRBGabs key V reseed_counter 32 prediction_resistance
                reseed_interval) contents).
      unfold mbedtls_HMAC256_DRBG_reseed_function, HMAC256_DRBG_functional_prog.HMAC256_DRBG_reseed_function in *.
      unfold DRBG_reseed_function in *. rewrite andb_negb_r in *.
      unfold return_value_relate_result in ENT.
      unfold get_entropy in *; simpl in *. rewrite <- HeqGE in *.

      rewrite AL256' in *.
      remember (Zlength (contents_with_add additional (Zlength contents) contents)) as ZLa.
      assert (ZLa256: ZLa >? 256 = false).
      { destruct ZLc' as [PP | PP]; rewrite PP; trivial. }
      rewrite ZLa256 in *. subst M r. normalize. simpl. cancel.
      unfold get_entropy. simpl. rewrite andb_negb_r, <- HeqGE.
      unfold hmac256drbgabs_common_mpreds. simpl. normalize.
      apply andp_right. apply prop_right. repeat split; trivial.
      thaw FR4. cancel.
      rewrite data_at__memory_block. entailer!.
      destruct seed; inv Pseed. unfold offset_val.
      rewrite <- repr_unsigned with (i:=i).
      assert (XX: sizeof (tarray tuchar 384) = entropy_len + (384 - entropy_len)).
      { simpl. omega. }
      rewrite XX.
      rewrite (memory_block_split Tsh b (Int.unsigned i) entropy_len (384 - entropy_len)), add_repr; try omega.
      cancel.
      eapply derives_trans. apply data_at_memory_block.
          simpl. rewrite Z.max_r, Z.mul_1_l; try omega; trivial.
      rewrite Zplus_minus. cbv; trivial.
      assert (Int.unsigned i >= 0) by (pose proof (Int.unsigned_range i); omega).
      split. omega.
      clear - Hfield. red in Hfield; simpl in Hfield. omega.
  }
  {
    forward.
    entailer!. clear FR4 FR5. (*subst add_len.*)
    apply negb_false_iff in H1. symmetry in H1; apply binop_lemmas2.int_eq_true in H1.
    subst vret; split; trivial.
  }
  Intros. subst vret. unfold return_value_relate_result in ENT.
  (* now that we know entropy call succeeded, use that fact to simplify the SEP clause *)
  remember (entropy.ENTROPY.get_bytes (Z.to_nat entropy_len) s) as entropy_result.
  unfold entropy.get_entropy in ENT;
  rewrite <- Heqentropy_result in ENT.
  destruct entropy_result; [|
    normalize;
    simpl in ENT; destruct e; [inversion ENT | inversion ENT ]
    (*assert (contra: False) by (apply ENT; reflexivity); inversion contra]*)
    ].
  Focus 2. destruct ENT_GenErrAx as [EC1 _]; elim EC1; trivial.
(*
  unfold entropy.get_entropy in ENT;
  rewrite <- Heqentropy_result in ENT;
  destruct entropy_result; [|
  normalize;
  simpl in ENT; destruct e; [inversion ENT |
  assert (contra: False) by (apply ENT; reflexivity); inversion contra]
  ].*)
  clear ENT.

  rename l into entropy_bytes.
  thaw FR5. thaw FR4.
  eapply REST with (s0:=s0)(contents':=contents'); trivial.
idtac "Timing the Qed of drbg_reseed (goal: 25secs)". omega.
Time Qed. (*Feb 23 2017: Finished transaction in 105.344 secs (74.078u,0.015s) (successful)*)
          (*earlier Coq8.5pl2: 24secs*)