证明Xor-Swapping的正确性

时间:2015-08-09 18:21:14

标签: verifiable-c

更新:现在我有以下程序swap.c

void swap (int* a, int* b) {
  int ta = *a;             
  int tb = *b;            
  ta = ta ^ tb;
  tb = ta ^ tb;
  ta = ta ^ tb;
  *a = ta;
  *b = tb;                           
}

我的规格是

Require Import floyd.proofauto.
Require Import floyd.entailer.
Require Import veric.SeparationLogic.

Require Import swap.

Local Open Scope logic.
Local Open Scope Z.

Definition swap_spec :=
  DECLARE _swap
   WITH sh : share, aptr : val, a : int, bptr : val, b : int
     PRE [ _a OF (tptr tint), _b OF (tptr tint)]
       PROP ()
       LOCAL (`(eq aptr) (eval_id _a);
              `(eq bptr) (eval_id _b))
       SEP (` (mapsto sh tint aptr (Vint a));
            ` (mapsto sh tint bptr (Vint b)))
       POST [tint] (`(mapsto sh tint aptr (Vint b)) *
                    `(mapsto sh tint bptr (Vint a))).

Definition Vprog : varspecs := nil.
Definition Gprog : funspecs := swap_spec :: nil.

Lemma body_swap : semax_body Vprog Gprog f_swap swap_spec.
Proof.
  start_function.
  forward.
  forward.
  forward.
  forward.
  forward.  
  eapply semax_seq.
  eapply semax_seq.

现在我陷入困境:我可以展开eval_binop,并尝试继续展开,但它并没有真正融合到我可以使用的任何东西上。此外,我不知道如何使用`eq属性来实际重写任何东西。

1 个答案:

答案 0 :(得分:1)

您的规范看起来是正确的。

在Verifiable C的标准分离逻辑中,您可以推理 每个C语句只有一个加载或存储,所以你必须重写代码,

ta = *a; tb = *b; *a = ta^tb;
ta = *a; tb = *b; *b = ta^tb;
ta = *a; tb = *b; *a = ta^tb;