Verif_strlib字符串函数

本章展示如何证明一类 C 程序的正确性: 这些程序使用空字符结尾的字符串。
下面是一些来自 C 标准库的函数,strlib.c
    #include <stddef.h>

    size_t strlen(const char *str) {
      size_t i;
      for (i=0; ; i++)
        if (str[i]==0) return i;
    }

    char *strcpy(char *dest, const char *src) {
      size_t i;
      for(i = 0;; i++){
        char d = src[i];
        dest[i] = d;
        if(d == 0) return dest;
      }
    }

    int strcmp(const char *str1, const char *str2) {
      size_t i;
      for(i = 0;; i++){
        char d1 = str1[i];
        char d2 = str2[i];
        if(d1 == 0 && d2 == 0) return 0;
        else if(d1 < d2) return -1;
        else if(d1 > d2) return 1;
      }
    }

标准样板

Require VC.Preface. (* 检查 VST 的正确版本 *)
Require Import VST.floyd.proofauto.
Require Import VC.strlib.
#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.
Definition Vprog : varspecs. mk_varspecs prog. Defined.
Require Import VC.hints. (* 为本教程导入特殊提示。 *)
Require Import Stdlib.Strings.Ascii.

空字符结尾字符串的表示

Rocq 把字符串表示为类似列表的 Ascii 字符【归纳类型|Inductive】:
Locate string. (* Coq.Strings.String.string *)
Print string.
(* Inductive string : Set :=
    EmptyString : string | String : Ascii.ascii -> string -> string *)

C 编程语言把【字符|Character】表示为 一个字节,即 8 位有符号或无符号整数。 在 Rocq 中我们用 byte 类型表示 8 位整数。
Print byte. (* Notation byte := Byte.int *)
CompCert 的 Byte 模块,是 n 位整数的一个 8 位实例;Int 模块则是 32 位实例。
我们可以问问 Byte 对 8 位模整数理论都知道些什么:
Search byte. (* 定理列表太长,此处不复现! *)
我们可以把 Rocq 字符串转换为字节列表:
Fixpoint string_to_list_byte (s: string) : list byte :=
  match s with
  | EmptyString ⇒ nil
  | String a s' ⇒ Byte.repr (Z.of_N (Ascii.N_of_ascii a))
                                      :: string_to_list_byte s'
  end.

Definition Hello := "Hello"%string.
Definition Hello' := string_to_list_byte Hello.

Eval simpl in string_to_list_byte Hello.
 (* = Byte.repr 72; Byte.repr 101; Byte.repr 108; Byte.repr 108; Byte.repr 111   :   list byte *)

Section StringDemo.

  Variable p : val. (* 假设我们在内存中有一个地址 *)
要描述内存中的单个字节,我们可以使用带 有符号字符类型的 data_at:
Print tschar. (* = Tint I8 Signed noattr : type *)
Check (data_at Tsh tschar (Vint (Int.repr 72)) p). (* : mpred *)
data_at Tsh tschar (Vint (Int.repr 72)) p 是一个 mpred, 即分离逻辑中的一个【内存谓词|Memory Predicate】。 它说的是:内存地址 p 处有一串字节, 长度与类型 tschar 相称,这里就是一个字节。 这个字节的内容是整数 72 的一种表示。 地址 p 处内存的【所有权份额|Ownership Share】 (即访问权限)是「最大份额」Tsh。
Check (data_at Tsh tschar (Vbyte (Byte.repr 72))).
我们可以用 Vbyte (Byte.repr 72) 表达同样的东西。 Vbyte 并非 CompCert 的原始值,它只是一个定义:
Print Vbyte. (* = fun c : byte => Vint (Int.repr (Byte.signed c))
     : byte -> val *)


Goal Vbyte (Byte.repr 72) = Vint (Int.repr 72).
Proof. reflexivity. Qed.

Goal Vbyte (Byte.repr 72) = Vint (Int.repr 72).
Proof.
  unfold Vbyte.
  rewrite Byte.signed_repr.
  auto.
  rep_lia.
Qed.
C 把长度为 k 的字符串表示成 一个非空字符(字节)数组,末尾是空字符。 分离逻辑里用 cstring 内存谓词表示它:
Locate cstring. (* VST.floyd.entailer.cstring *)
Print cstring. (* =
  fun {CS : compspecs} (sh : Share.t) (s : list byte) (p : val) =>
  !! (~ In Byte.zero s) &&
  data_at sh (tarray tschar (Zlength s + 1)) (map Vbyte (s++Byte.zero)) p *)

这是一个 cstring 谓词的例子: 在地址 p 处有一个空字符结尾字符串,内容是「Hello」。
Check (cstring Tsh Hello' p). (* : mpred *)
展开 cstring 的定义后,这等价于:
Check (
  !! (¬ In Byte.zero Hello') &&
  data_at Tsh (tarray tschar (5 + 1)) (map Vbyte (Hello'++[Byte.zero])) p ).
它断言列表 Hello' 中没有元素等于 Byte.zero。 在内存地址 p 处有一个 6 字节的数组, 内容是 Hello',末尾再添一个 Byte.zero。
有时已知长度 n 的数组里藏着一个空字符结尾字符串。 它由三部分组成:先是 k 个非空字符(k<n), 接着一个空字符, 再是 n-(k+1) 个未初始化(或不必关心)的字符。 我们用 cstringn 谓词表示它。
Print cstringn. (* =
 fun {CS : compspecs} (sh : Share.t) (s : list byte) (n : Z) (p : val) =>
 !! (~ In Byte.zero s) &&
 data_at sh (tarray tschar n)
  (map Vbyte (s ++ Byte.zero) ++
   Zrepeat Vundef (n - (Zlength s + 1))) p *)


Check (cstringn Tsh Hello' 10 p). (* : mpred *)

End StringDemo.

关于 C 字符串内容的推理

C 字符串的分离逻辑证明中, 常会遇到与下列引理类似的证明目标:
Lemma demonstrate_cstring1:
 ∀ i contents
   (H: ¬ In Byte.zero contents)
   (H0: Znth i (contents ++ [Byte.zero]) ≠ Byte.zero)
   (H1: 0 ≤ i ≤ Zlength contents),
   0 ≤ i + 1 < Zlength (contents ++ [Byte.zero]).
Proof.
intros.
空字符结尾字符串是包含三部分的字符数组:
  • 字符串的内容,其中没有 '\0' 字符;
  • 空终止字符,等于 Byte.zero;
  • 空字符之后数组里剩下的垃圾。
处理字符串时,横线上方要维持三类假设:
  • H 说内容中没有空字符;
  • H0 通常来自循环测试 s[i]!=0;
  • H1 通常来自循环不变式:循环迭代变量
_i(取值 i)正遍历数组。 我们希望循环走到空字符为止,不再越过它, 即停在内容之后的那一格。
cstring 策略会同时用上这三个假设, 由此得出 i < Zlength contents。
assert (H7: i < Zlength contents) by cstring.
其实 cstring 能证明该事实的 任何 rep_lia 推论。例如:
clear H7.
autorewrite with sublist.
cstring.
Qed.
再看一个例子。当遍历字符串内容的循环 走到末尾,测试 s[i]!=0 为假, 于是 s[i]=0。
Lemma demonstrate_cstring2:
 ∀ i contents
   (H: ¬ In Byte.zero contents)
   (H0: Znth i (contents ++ [Byte.zero]) = Byte.zero)
   (H1: 0 ≤ i ≤ Zlength contents),
   i = Zlength contents.
Proof.
intros.
假设 H0 表达了循环测试判定 s[i]=0。 cstring 便能证明 i = Zlength contents。
cstring.
Qed.

函数规约

strlen(s) 返回字符串 s 的长度。
Definition strlen_spec :=
 DECLARE _strlen
  WITH sh: share, s : list byte, str: val
  PRE [ tptr tschar ]
    PROP (readable_share sh)
    PARAMS (str)
    SEP (cstring sh s str)
  POST [ size_t ]
    PROP ()
    RETURN (Vptrofs (Ptrofs.repr (Zlength s)))
    SEP (cstring sh s str).

关于 size_t 的题外话

Vptrofs?Ptrofs.repr?那是什么?
要写同时移植到 64 位与 32 位平台的 C 程序时, 程序员会用 size_t。这个 typedef 代表 与指针同大小的无符号(long)整数类型。 可验证 C 中,size_t 对应的 C 无符号类型是:
Print size_t.
(*   = if Archi.ptr64
         then Tlong Unsigned noattr
         else Tint I32 Unsigned noattr *)

所以 RETURN 子句不返回 Vlong (Int64.repr (Zlength s)) 或 Vint (Int.repr (Zlength s)) 这类不可移植的值, 而用 Vptrofs,它视平台给出 Vlong 或 Vint:
Print Vptrofs.
(*  =  fun n : ptrofs =>
          if Archi.ptr64
          then Vlong (Ptrofs.to_int64 n)
          else Vint (Ptrofs.to_int n) *)

「ptrofs」不好发音,它是「pointer offset」 (指针偏移)的缩写。CompCert 的东西,别深究。 Vptrofs 的实参是 ptrofs,即 Ptrofs.int。 64 位配置下模块 Ptrofs 与 Int64 同构, 32 位配置下与 Int 同构。同构却不相同, 两者之间有引理相连:
Search Ptrofs.int Int64.int.
Search Ptrofs.int Int.int.
VST-Floyd 有自动化策略, 会在合适处替你应用这些引理。 比如本章的证明里,你不必为 Vptrofs 做太多特殊处理。

关于 size_t 的题外话结束

strcpy(dest,src) 把字符串 src 复制到数组 dest。
Definition strcpy_spec :=
 DECLARE _strcpy
  WITH wsh: share, rsh: share, dest : val, n : Z, src : val, s : list byte
  PRE [ tptr tschar, tptr tschar ]
    PROP (writable_share wsh; readable_share rsh; Zlength s < n)
    PARAMS (dest; src)
    SEP (data_at_ wsh (tarray tschar n) dest; cstring rsh s src)
  POST [ tptr tschar ]
    PROP ()
    RETURN (dest)
    SEP (cstringn wsh s n dest; cstring rsh s src).
strcmp(s1,s2) 按【字典序|Lexicographic Order】 比较字符串 s1 与 s2。这个 funspec 对实际行为是 【规约不足|Underspecification】:它只规约了相等性测试。
Definition strcmp_spec :=
 DECLARE _strcmp
  WITH sh1: share, sh2: share, str1 : val, s1 : list byte, str2 : val,
       s2 : list byte
  PRE [ tptr tschar, tptr tschar ]
    PROP (readable_share sh1; readable_share sh2)
    PARAMS (str1; str2)
    SEP (cstring sh1 s1 str1; cstring sh2 s2 str2)
  POST [ tint ]
   EX i : int,
    PROP (if Int.eq_dec i Int.zero then s1 = s2 else s1 ≠ s2)
    RETURN (Vint i)
    SEP (cstring sh1 s1 str1; cstring sh2 s2 str2).

Definition Gprog : funspecs := [ strlen_spec; strcpy_spec; strcmp_spec ].

strlen 函数的证明

练习: 2 stars,标准 (body_strlen)

Lemma body_strlen: semax_body Vprog Gprog f_strlen strlen_spec.
Proof.
start_function.
看横线下方的证明目标。断言是
  PROP ( ) LOCAL (temp _str str) SEP (cstring sh s str)) 证明字符串处理函数时,先要决定一件事。 该函数是【抽象地】处理字符串, 还是下标访问数组、逐个查看字符?
  • 若是抽象处理,我们【不】应展开 cstring 的定义。
  • 若直接下标访问数组,就【必须】展开 cstring。
strlen 确实会读数组内容, 所以我们先展开 cstring。
unfold cstring in ×.
现在 SEP 子句里有一个 Proposition ¬ In Byte.zero s。用 Intros 把它移到横线上方。
Intros.
forward. (* i=0; *)
现在到了一个 for 循环。它与简单 while 循环不同:
  • break;(提前终止整个循环)
  • continue;(提前结束本轮,跳到自增步骤)
简单的霍尔逻辑 while 规则因此并不总能用。 可验证 C 的 loop 策略一般长这样:
  forward_loop Inv1 continue: Inv2 break: Inv3 Inv1 是循环测试前成立的不变式; Inv2 是自增步骤前成立的不变式; Inv3 是循环的后置条件。
continue: Inv2 可以省略,break: Inv3 也可以。 很多情况下,forward_loop 能自己判断: 循环没有 continue 语句,就不要 continue: 不变式; 没有 break 语句、循环之后也没有命令, 就不要 break: 后置条件。
先用单个循环不变式来试这个循环:
forward_loop (EX i : Z,
  PROP (0 ≤ i < Zlength s + 1)
  LOCAL (temp _str str; temp _i (Vptrofs (Ptrofs.repr i)))
  SEP (data_at sh (tarray tschar (Zlength s + 1))
          (map Vbyte (s ++ [Byte.zero])) str)).
看把 temp _i 绑定到值 Vptrofs (Ptrofs.repr i) 的 LOCAL 子句。 为什么?推理 C 程序时,我们需要:
  • 8 位整数,Byte.int 或简写 byte
  • 32 位整数,Int.int 或简写 int
  • 64 位整数,Int64.int
还有一个 C 中写作 size_t 的概念, 即【与指针同位数的整数类型】。 它可能与 32 位 int 相同,也可能与 64 位 int 相同。
CompCert 有推理 32 位整数的 Int 模块, 也有推理 64 位整数的 Int64 模块; 同样地,它有推理【指针偏移】的 Ptrofs 模块。 Ptrofs 与 Int64 或 Int 之一同构(但不相同), 取决于布尔值 Archi.ptr64。
Compute Archi.ptr64. (* = false : bool *)
算出 false,说明这份可验证 C 装的是 32 位指针; 算出 true 则是 64 位。 无论哪种,把 Ptrofs.int 变成 CompCert val 都靠 Vptrofs。 正如 size_t 能写出兼容 32/64 位指针的 C 程序, Ptrofs 也能写出可移植的证明脚本。
Print Vptrofs. (* =
 fun n : ptrofs =>
   if Archi.ptr64 then Vlong (Ptrofs.to_int64 n)
                  else Vint (Ptrofs.to_int n)
     : ptrofs -> val  *)

于是 _i 是类型 size_t 的 C 变量, i 是类型 Z 的 Rocq 变量; Vptrofs (Ptrofs.repr i) 是 CompCert val, 把 i 【表示】成 val。
assert (Example: Archi.ptr64=false →
          ∀ n, Vptrofs (Ptrofs.repr n) = Vint (Int.repr n)). {
 intro Hx; try discriminate Hx. (* 以防 Archi.ptr64 = true *)
  (* 在 32 位 C 系统中: *)
all: intros.
all: hint.
all: autorewrite with norm.
all: auto.
} clear Example.
现在来证明 forward_loop 的所有子目标。
× (* 证明前置条件蕴含循环不变式 *)
(* 在这里填写 *) admit.
× (* 证明循环体保持不变式 *)
(* 在这里填写 *) admit.
(* 在这里填写 *) Admitted.
☐

strcpy 函数的证明

练习: 2 stars,标准 (strcpy_then_clause)

下一条引理(或其某种变体)在 strcpy 函数的证明中会用到(在 if 语句的 then 子句中)。
Lemma strcpy_then_clause:
  ∀ (wsh: share) (dest: val) (n: Z) (s: list byte),
  Zlength s < n →
  ¬ In Byte.zero s →
    data_at wsh (tarray tschar n)
      (map Vbyte (sublist 0 (Zlength s) s) ++
       upd_Znth 0 (Zrepeat Vundef (n - Zlength s))
         (Vint (Int.repr (Byte.signed (Znth (Zlength s) (s ++ [Byte.zero]))))))
      dest
  |-- data_at wsh (tarray tschar n)
        (map Vbyte (s ++ [Byte.zero]) ++
             Zrepeat Vundef (n - (Zlength s + 1)))
        dest.
Proof.
intros.
apply derives_refl'.
f_equal.
Check Zrepeat_app. (* 提示:这条引理会用到。 *)
Check upd_Znth_app1. (* 提示:这条引理会用到。 *)
Check app_Znth2. (* 提示:这条引理会用到。 *)
Check Znth_0_cons. (* 提示:这条引理会用到。 *)
(* 其他有用的引理有 map_app、app_assoc *)
(* 在这里填写 *) Admitted.
☐

练习: 2 stars,标准 (strcpy_else_clause)

Lemma strcpy_else_clause: ∀ wsh dest n s i,
  Zlength s < n →
  ¬ In Byte.zero s →
  0 ≤ i < Zlength s + 1 →
  Znth i (s ++ [Byte.zero]) ≠ Byte.zero →
     data_at wsh (tarray tschar n)
      (upd_Znth i (map Vbyte (sublist 0 i s)
                       ++ Zrepeat Vundef (n - i))
             (Vint (Int.repr (Byte.signed (Znth i (s ++ [Byte.zero])))))) dest
  |-- data_at wsh (tarray tschar n)
      (map Vbyte (sublist 0 (i + 1) s)
           ++ Zrepeat Vundef (n - (i + 1))) dest.
Proof.
intros.
apply derives_refl'.
f_equal.
这里有用的引理有:upd_Znth_app2、sublist_split、 repeat_app'、app_Znth1、map_app、app_assoc、sublist_len_1。
(* 在这里填写 *) Admitted.
☐

data_at 不是单射的!

Vundef 值表示【未初始化】、【未定义】, 或【已定义但不关心】。考虑这条引理:
Lemma data_at_Vundef_example:
  ∀ i n sh p,
    0 ≤ i < n →
  data_at sh (tarray tschar n)
          (Zrepeat (Vbyte Byte.zero) (i+1)
             ++ Zrepeat Vundef (n-(i+1))) p
 |--
  data_at sh (tarray tschar n)
          (Zrepeat (Vbyte Byte.zero) i
             ++ Zrepeat Vundef (n-i)) p.
Proof.
intros.
这个目标在说:单元 0 ≤ j < i+1 全为零, 单元 i+1 ≤ j < n 不必关心。 由此可得一个较弱的陈述:单元 0 ≤ j < i 全为零, 单元 i ≤ j < n 不必关心。
证法与 strcpy_then_clause 中的相同:
apply derives_refl'.
f_equal.
rewrite <- Zrepeat_app by lia.
replace (n-i) with (1 + (n-(i+1))) by lia.
rewrite <- Zrepeat_app by lia.
rewrite !app_assoc.
f_equal.
f_equal.
哎呀!当前的证明目标是 False! 问题在于我们不应应用 derives_refl'。
Abort.

Lemma data_at_Vundef_example:
  ∀ i n sh p,
    0 ≤ i < n →
  data_at sh (tarray tschar n)
          (Zrepeat (Vbyte Byte.zero) (i+1)
             ++ Zrepeat Vundef (n-(i+1))) p
 |--
  data_at sh (tarray tschar n)
          (Zrepeat (Vbyte Byte.zero) i
             ++ Zrepeat Vundef (n-i) ) p.
Proof.
intros.
rewrite <- Zrepeat_app by lia.
replace (n-i) with (1 + (n-(i+1))) by lia.
rewrite <- Zrepeat_app by lia.
rewrite <- !app_assoc.
Check split2_data_at_Tarray_app.
(*  forall (cs : compspecs) (mid n : Z) (sh : Share.t)
    (t : type) (v1 v2 : list (reptype t)) (p : val),
  Zlength v1 = mid ->
  Zlength v2 = n - mid ->
  data_at sh (tarray t n) (v1 ++ v2) p =
  data_at sh (tarray t mid) v1 p *
  data_at sh (tarray t (n - mid)) v2
    (field_address0 (tarray t n) ArraySubsc mid p)
*)

rewrite (split2_data_at_Tarray_app i) by list_solve.
rewrite (split2_data_at_Tarray_app 1) by list_solve.
rewrite (split2_data_at_Tarray_app i) by list_solve.
rewrite (split2_data_at_Tarray_app 1) by list_solve.
cancel.
Qed.
为什么这行得通?看个更简单的例子。
Lemma cancel_example:
 ∀ sh i j p q,
   data_at sh tint (Vint i) p × data_at sh tint (Vint j) q
 |-- data_at sh tint (Vint i) p × data_at sh tint (Vundef) q.
Proof.
intros.
取消下面这行的注释,看看它解决了目标。
(* cancel. *)
cancel 把目标分成两个子目标:
apply sepcon_derives.
-
第一个子目标用到 |-- 是自反的
apply derives_refl.
-
第二个子目标用到:【任何】值都蕴含 Vundef。 更一般地,【任何】值都蕴含 CompCert 类型 t 的 default_val t。
apply stronger_default_val.
Qed.
这个例子说明:要证明
   data_at sh t a p |-- data_at sh t b p 当 (a=b) 时,可以用下列方式简化目标
   apply derives_refl'; f_equal. 但若 a 比 b 严格更有定义,derives_refl' 就不合适。

练习: 3 stars,标准 (body_strcpy)

Lemma body_strcpy: semax_body Vprog Gprog f_strcpy strcpy_spec.
Proof.
start_function.
这个函数下标访问字符串, 并非【抽象地】处理字符串, 所以必须展开 cstring 与 cstringn。
unfold cstring,cstringn in ×.
forward.
Intros.
forward_loop (EX i : Z,
  PROP (0 ≤ i < Zlength s + 1)
  LOCAL (temp _i (Vptrofs (Ptrofs.repr i)); temp _dest dest; temp _src src)
  SEP (data_at wsh (tarray tschar n)
        (map Vbyte (sublist 0 i s) ++ Zrepeat Vundef (n - i)) dest;
       data_at rsh (tarray tschar (Zlength s + 1)) (map Vbyte (s ++ [Byte.zero])) src)).
+ (* 证明前置条件蕴含循环不变式 *)
(* 在这里填写 *) admit.
+ (* 证明循环体 *)
这个证明的 then 子句里,你可能会遇到 与 Lemma strcpy_then_clause 相似、却不完全相同的目标。 那时不妨套用那道练习中的技术。 else 子句同理,对应 strcpy_else_clause。
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (example_call_strcpy)

证明一个调用 strcpy 的函数的正确性。
  int example_call_strcpy(void) {
    char buf[10];
    strcpy(buf,"Hello");
    return buf[0];
  }
Definition stringlit_1_contents := Hello' ++ [Byte.zero].

Definition example_call_strcpy_spec :=
 DECLARE _example_call_strcpy
  WITH gv: globals
  PRE [ ]
    PROP ()
    PARAMS() GLOBALS (gv)
    SEP (cstring Ews Hello' (gv ___stringlit_1))
  POST [ tint ]
    PROP ()
    RETURN (Vint (Int.repr (Z.of_N (Ascii.N_of_ascii "H"%char))))
    SEP (cstring Ews Hello' (gv ___stringlit_1)).

Lemma body_example_call_strcpy: semax_body Vprog Gprog
         f_example_call_strcpy example_call_strcpy_spec.
Proof.
start_function.
这个证明相当直截了当。先弄清传给 forward_call 的 WITH 见证是什么。提示:看 strcpy_spec 前置条件的 SEP 子句,看 data_at 与 cstring 合取项 要怎样与当前断言匹配。
调用之后别忘了展开 cstringn。必须如此, 因为紧接着我们要下标访问 _buf 数组。
(* 在这里填写 *) Admitted.
☐

练习: 4 stars,标准,可选 (body_strcmp)

Lemma body_strcmp: semax_body Vprog Gprog f_strcmp strcmp_spec.
(* 在这里填写 *) Admitted.
☐
(* 2026-11-26 16:01 *)