VSU_stdlib2用 C 编写的 malloc/free/exit

VSU_stdlib 把 malloc、free、exit 公理化为外部函数。本章不同: 我们把它们构造为普通 C 函数,并证明其正确。 本章还展示如何管理模块私有的全局变量。
在 C 代码中,有一个 stdlib.h 接口, 以及两个相当独立的可选实现 stdlib.c 与 stdlib2.c。
证明方面有一条规约 Spec_stdlib.MallocFreeASI (即「malloc-free 抽象规约接口」), 还有两个带证明的可选实现: VSU_stdlib.MallocFreeVSU 与 VSU_stdlib2.MallocFreeVSU。
第二个 VSU 就是本章要构造的。

C 程序

这是我们的 C 程序。注意 pool, pool_index, freelist 这些变量对模块而言是全局的,本意却是私有的。 模块客户不应直接操纵它们。 这些变量带有初始值: pool_index=0, freelist=NULL, pool 隐式零初始化。 它们表示一个有意义的初始状态。
/* stdlib2.c */
#include <stddef.h>
#include "stdlib.h"

struct cell {struct cell *a, *b, *c, *d;};

#define N 80000

struct cell pool[N];
int pool_index = 0;
struct cell *freelist=NULL;

void *malloc (size_t n) {
  struct cell *p;
  if (n>sizeof(struct cell)) return NULL;
  if (freelist) {
    p = freelist;
    freelist = p->a;
  } else if (pool_index < N) {
    p = pool+pool_index++;
  } else p=NULL;
  return (void* ) p;
}

void free (void *p) {
  struct cell *pp = p;
  if (pp==NULL) return;
  pp->a = freelist;
  freelist=pp;
}

void exit (int n) {
  while (1) ;
}
如你所见,malloc 能分配大小从 0 到 sizeof(struct cell) 的块,即最长四个字。任何更大的 malloc 请求都会返回 NULL, 这对 malloc 是合法行为。此外,pool 的最大容量是 N=80000, 超过它 malloc 就返回 NULL。
exit() 函数进入无限循环。 在我们的部分正确性霍尔逻辑中, 这满足了它那条为 False 的后置条件。

常规样板

Require Import VST.floyd.proofauto.
Require Import VST.floyd.VSU.
Require Import VC.stdlib2.
Require Import VC.Spec_stdlib.
#[export] Instance CompSpecs : compspecs. make_compspecs stdlib2.prog. Defined.
照常,我们定义表示关系。首先是空闲链表, 它就是一个链表,与 VSU_stack 中的很像。
Definition tcell := Tstruct _cell noattr.

Fixpoint freelistrep (n: nat) (p: val) : mpred :=
 match n with
 | S n' ⇒ EX y: val,
        !! malloc_compatible (sizeof tcell) p &&
        data_at Ews tcell (y, (Vundef, (Vundef, Vundef))) p ×
        freelistrep n' y
 | O ⇒ !! (p = nullval) && emp
 end.

Arguments freelistrep n p : simpl never.

Lemma freelistrep_local_prop: ∀ n p,
   freelistrep n p |-- !! (is_pointer_or_null p ∧ (n=0↔p=nullval) ∧ (n>0↔isptr p))%nat.
(* 在这里填写 *) Admitted.
#[export] Hint Resolve freelistrep_local_prop : saturate_local.

Lemma freelistrep_valid_pointer:
  ∀ n p,
   freelistrep n p |-- valid_pointer p.
(* 在这里填写 *) Admitted.
#[export] Hint Resolve freelistrep_valid_pointer : valid_pointer.
☐

malloc_token

假定用户执行 p = malloc(7);。 那么 p 指向一个新分配的 7 字节块。 malloc_token(p) 表示什么?
  • 通常,必须有某种办法让 free(p) 得知块的大小。 这可以在地址 p 正前方放一个给出大小的头部字来实现。 当然还有其他办法。通常这个头部字 是 malloc_token 所表示的一部分。 但在本实现中,所有块大小相同,因此不需要这样的头部。
  • 内存管理器的空闲链表中所有块的大小都是 sizeof(tcell)。 当 sizeof(size_t)=4 时为 16 字节, sizeof(size_t)=8 时为 32 字节。 当 malloc(7) 把一个块劈成两半时, malloc_token 表示第二半,即块中从偏移 7 到末尾的部分。 那就是下面定义中显示的 memory_block。
  • 此外,malloc_token 还有三条关于地址 p 的命题事实。 free() 会用它们重组被劈开块的两部分。
Definition malloc_token_sz (sh: share) (n: Z) (p: val) : mpred :=
  !! (field_compatible tcell [] p
      ∧ malloc_compatible (sizeof tcell) p
      ∧ 0 ≤ n ≤ sizeof tcell)
 && memory_block Ews (sizeof tcell - n) (offset_val n p).

练习: 2 stars,标准 (malloc_token_properties)

Lemma malloc_token_sz_valid_pointer:
    ∀ (sh : share) (sz : Z) (p : val),
            sz ≤ 0 →
              malloc_token_sz sh sz p |-- valid_pointer p.
(* 在这里填写 *) Admitted.

Lemma malloc_token_sz_local_facts :
   ∀ (sh : share) (sz : Z) (p : val),
     malloc_token_sz sh sz p |-- !! malloc_compatible sz p.
(* 在这里填写 *) Admitted.
☐
接下来三行定义了一个不透明常量, 但 rep_lia 仍能展开它。 见 VC.pdf 第 65 章「不透明常量」。
Definition N : Z := proj1_sig (opaque_constant 80000).
Definition N_eq : N=_ := proj2_sig (opaque_constant _).
#[export] Hint Rewrite N_eq : rep_lia.

题外话(可随意跳过)

Module Digression.
假定有人改了源程序 stdlib2.c, 把常量换成不同于 80000 的值。 你会希望验证脚本自动调整。 我们将修改 Definition N : Z := ... 这一行, 以自动找出该常量。
第一步是找出该常量。你可以在 stdlib2.v (由 CompCert clightgen 从 stdlib2.c 产生) 中找变量定义 v_pool, 然后看 80000 出现在 gvar_info(v_pool) 的何处:
Compute gvar_info (stdlib2.v_pool).
  (*   = Tarray
         (Tstruct 57 {| attr_volatile := false; attr_alignas := None |})
         80000
         {| attr_volatile := false; attr_alignas := None |}
     : type *)

自动提取那个数字很容易:
Compute match gvar_info (stdlib2.v_pool) with Tarray _ n _ ⇒ n | _ ⇒ 0 end.
  (*  = 80000: Z *)
下面的 N 定义效果不好,因为 N 不会是常量, 而会是一个 match 表达式:
Definition N' := match gvar_info (stdlib2.v_pool) with Tarray _ n _ ⇒ n | _ ⇒ 0 end.
Print N'. (* N' = match gvar_info v_pool with Tarray _ n _ => n | _ => 0 end *)
于是改用这个 Rocq 技巧:
Definition N'' :=
  ltac:(let x := constr:(match gvar_info (stdlib2.v_pool) with
                         | Tarray _ n _ ⇒ n
                         | _ ⇒ 0 end)
        in let x := eval compute in x in exact x).
Print N''. (* N'' = 80000 : Z *)
现在把 N'' 放到一边,把两个技巧合起来:
  • opaque_constant 用于定义一个常量, 除显式改写外它不展开;以及
  • 从程序本身提取该常量的值。
Definition N := proj1_sig (opaque_constant
                            (ltac:(let x := constr:(match gvar_info (stdlib2.v_pool) with
                                          Tarray _ n _ ⇒ n | _ ⇒ 0 end)
                                    in let x := eval compute in x in exact x))).
Definition N_eq : N=_ := proj2_sig (opaque_constant _).
#[export] Hint Rewrite N_eq : rep_lia.
Check N_eq. (* : N = 80000 *)

End Digression.

题外话结束。你很高兴跳过了它吧?

定义 mem_mgr APD

这个 mem_mgr 谓词从客户视角看是抽象谓词。 它刻画本模块全局状态变量 pool、pool_index 与 freelist 的内容。
Definition mem_mgr (gv: globals) : mpred :=
 EX i: Z, EX p: val, EX frees: nat,
  !! (0 ≤ i ≤ N) &&
  data_at Ews tint (Vint (Int.repr i)) (gv _pool_index) ×
  data_at_ Ews (tarray tcell (N-i))
     (field_address0 (tarray tcell N) [ArraySubsc i] (gv _pool)) ×
  data_at Ews (tptr tcell) p (gv _freelist) ×
  freelistrep frees p.

Definition M : MallocFreeAPD :=
    Build_MallocFreeAPD mem_mgr malloc_token_sz
           malloc_token_sz_valid_pointer malloc_token_sz_local_facts.

构造 Vprog 与 Gprog

  Definition MF_ASI: funspecs := MallocFreeASI M.
  Definition MF_imported_specs:funspecs := nil.
  Definition MF_internal_specs: funspecs := MF_ASI.
  Definition MF_globals gv : mpred:= Spec_stdlib.mem_mgr M gv.
  Definition MFVprog : varspecs. mk_varspecs stdlib2.prog. Defined.
  Definition MFGprog: funspecs := MF_imported_specs ++ MF_internal_specs.

练习: 3 stars,标准 (stdlib2_body_malloc)

Lemma body_malloc: semax_body MFVprog MFGprog f_malloc (malloc_spec_sz M).
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (stdlib2_body_free)

Lemma body_free: semax_body MFVprog MFGprog f_free (free_spec_sz M).
(* 在这里填写 *) Admitted.
☐

练习: 2 stars,标准 (stdlib2_body_exit)

Lemma body_exit: semax_body MFVprog MFGprog f_exit exit_spec.
(* 在这里填写 *) Admitted.
☐

全局数据的初始化器

Check @Comp_MkInitPred.
每个 VSU 都可以有一些构成其「局部状态」的 私有全局变量。VSU 的客户不应直接访问它们; 在分离逻辑中,所有这些变量应被抽象为单个抽象谓词。 这些变量可能带有初始值,具体表示某个抽象状态。 于是 VSU 接口中需要一条公理 (在 VSU 实现中作为引理证明)。 它说明:这些初始值恰当地表示了 该抽象谓词的一个合适状态。

练习: 2 stars,标准 (stdlib2_initialize)

Lemma initialize: VSU_initializer prog MF_globals.
Proof.
InitGPred_tac.
unfold MF_globals.
(* 在这里填写 *) Admitted.

定义 VSU 的组成部分

现在照常把这些部分拼合起来:

构造组件与 VSU

  Definition MF_Externs : funspecs := nil.

Definition MallocFreeVSU: @VSU NullExtension.Espec
         MF_Externs MF_imported_specs ltac:(QPprog prog) MF_ASI MF_globals.
  Proof.
 mkVSU prog MF_internal_specs.
    - solve_SF_internal body_malloc.
    - solve_SF_internal body_free.
    - solve_SF_internal body_exit.
    - apply initialize; auto.
Qed.

下一章:VSU_main2

(* 2026-11-26 16:01 *)