Proving correctness of Xor-Swapping - verifiable-c

Update: Now I have the following program 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;
}
My specification is
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.
Now I am stuck: I can unfold eval_binop, and try to proceed unfolding, but it doesn't really converge to anything that I can work with. Furthermore, I am not sure how to use the `eq properties to actually rewrite anything.

Your specification looks correct.
In Verifiable C's standard Separation Logic, you can reason
about only one load or store per C statement, so you will have to rewrite the code as,
ta = *a; tb = *b; *a = ta^tb;
ta = *a; tb = *b; *b = ta^tb;
ta = *a; tb = *b; *a = ta^tb;

Related

Modifying data via pointers

https://play.golang.org/p/DOhYaiH53Ek
I do not understand the *&p operation nor how a pointer *p which is an int() value NOT a memory address is able to modify its value i.e. valueX = valueY. I know that I must be misunderstanding something, but this code literally appears to be self-conflicting.
//point
package main
import "reflect"
var pt int = 27
func main() {
println(reflect.TypeOf(pt))
println("pt = ", pt) //value of pt
println("&pt = ", &pt) //memory address of pt
updatePointer(&pt)
println("pt = ", pt) //value of pt
}
func updatePointer(p *int) { //requires memory address of an int
println("&p = ", &p) //memory address of p
println("p = ", p) //memory address of pt
println("*p before = ", *p) //value of pt
println(*p == 27) //true
*p = 14 //27 = 14??????????
println("*p =", *p) //value of pt
println(reflect.TypeOf(&pt) == reflect.TypeOf(*&p)) //true!!!?????
println("*&p = ", *&p) //memory address which p's memory address evals to???? 0x800 (p) -> 0x900 (pt) = 0x800 (p)?
}
/*
Why can't I do the following?
func updatePointer(p *int){
p = 14
//OR
&p = 14
//OR
*&p = 14
}
*/
Considering *&p firstly lets simplify the example (removing all of the irrelevant stuff)
var pt int = 27
p := &pt // because &pt is passed as the argument into updatePointer
*p = 14 // This assigns 14 to whatever p points to (i.e. pt)
println(reflect.TypeOf(&pt) == reflect.TypeOf(*&p))
*& does nothing (and I can see no reason to use it in a real application); the statement gets the address of p (the &p bit) and then gets what the result points at (p). So this an be rewritten
println(reflect.TypeOf(&pt) == reflect.TypeOf(p))
p is pointing to pt so p == &pt (by definition this means that *p == pt). This means they are the same thing so will, of course, have the same type.
So why does *p = 14 work? You said that "*p which is an int() value NOT a memory address is able to modify its value" but that is not quite what the spec says:
For an operand x of pointer type *T, the pointer indirection *x
denotes the variable of type T pointed to by x. If x is nil, an
attempt to evaluate *x will cause a run-time panic.
So what *p = 14 is saying is set the variable that p points to to 14.
Now lets look at your second question:
// Why can't I do the following?
func updatePointer(p *int){
p = 14
//OR
&p = 14
//OR
*&p = 14
}
So p is a pointer to an integer (thats what *int means). Saying p = 14 is an attempt to set the pointer (not the int) to the value 14. 14 is an int not a pointer hence the compiler error cannot use 14 (type int) as type *int in assignment.
&p = 14 is saying set the address of p to 14. p is a *int so getting the address will give you a **int (a pointer to a pointer to an int). The compiler error you will get is cannot assign to &p and this is because the result of &p is not addressable. You could get around that by saying
x := &p
x = 14
and this will give you the error you might expect based upon what I said above: cannot use 14 (type int) as type **int in assignment.
*&p = 14 is basically the same as saying p=14 (it gets the address of p and then gets whatever the result points at whis will be p).
Pointers can get quite confusing (especially in contrived examples) and this article may help you understand.
Simplify. For example,
package main
import "fmt"
func f(q *int) {
fmt.Println(*q, q, &q, "f")
*q = 14
fmt.Println(*q, q, &q, "f")
}
func main() {
var i int = 27
var p *int = &i
fmt.Println(*p, p, &p, i, "main")
f(p)
fmt.Println(*p, p, &p, i, "main")
}
Output:
27 0x40e020 0x40c138 27 main
27 0x40e020 0x40c148 f
14 0x40e020 0x40c148 f
14 0x40e020 0x40c138 14 main
Errors:
/*
func g(r *int) {
// cannot use 14 (type int) as type *int in assignment
r = 14
// cannot assign to &r
&r = 14
// cannot use 14 (type int) as type *int in assignment
*(&r) = 14
}
*/
Playground: https://play.golang.org/p/Hwe3anFBTfD
In Go, all arguments are passed by value, as if by assignment. A pointer p to an int i is passed by value (q = p) to function f. The pointer q, a copy of p, is used to modify the value of i, *q = 14, *q dereferences type *int to type int.
The function g compiler error messages explain why the statements are illegal. For example, *&r = 14 is *(&r) = 14 is r = 14, cannot use 14 (type int) as type *int in assignment, r is type *int.
References:
A Tour of Go
The Go Programming Language Specification

F# Generic Map.count using Reflection

This is a follow-up on this previous question, but with a different twist.
I would like to write a function which, given an object oMap, returns its count if oMap happens to be of type Map<'k,'v>, and -1 otherwise. My constraint : oMap type can only be 'discovered' at runtime.
As apparently "there is no built-in way to pattern match on a generic Map." (see link to previous question), I am using reflection for this.
namespace genericDco
module Test1 =
let gencount (oMap : obj) : int =
let otype = oMap.GetType()
let otypenm = otype.Name
if otypenm = "FSharpMap`2" then
// should work, as oMap of type Map<'a,'b>, but does not. *How to fix this?*
Map.count (unbox<Map<_,_>> oMap)
else
// fails, as oMap is not of any type Map<'a,'b>.
-1
let testfailObj : int = gencount ("foo")
// FAILS
let testsuccessObj : int =
let oMap = [| ("k1", "v1"); ("k1", "v1") |] |> Map.ofArray
gencount (box oMap)
The error being :
System.InvalidCastException: Unable to cast object of type 'Microsoft.FSharp.Collections.FSharpMap`2[System.String,System.String]' to type 'Microsoft.FSharp.Collections.FSharpMap`2[System.IComparable,System.Object]'. at Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.UnboxGeneric[T](Object source)
My question: How should I rewrite the above to get this to work?
PS : I am not looking for solutions where we know at compile time that oMap is of type Map<'k,'v>, e.g. :
module Test2 =
let gencount2<'k,'v when 'k : comparison> (gMap : Map<'k,'v>) : int =
Map.count gMap
let testsuccessStr : int =
let gMap = [| ("k1", "v1"); ("k2", "v2") |] |> Map.ofArray
gencount2<string,string> gMap
let testsuccessDbl : int =
let gMap = [| ("k1", 1.0); ("k2", 2.0); ("k3", 3.0) |] |> Map.ofArray
gencount2<string,double> gMap
== EDIT ==
Thanks to Asti's suggestion, that's the solution that worked for me :
let gencount (oMap : obj) : int =
let otype = oMap.GetType()
let propt = otype.GetProperty("Count")
try
propt.GetValue(oMap) :?> int
with
| _ -> -1
Since Map.count is just defined as let count m = m.Count, we can just go for the Count property.
let gencount<'k,'v when 'k : comparison> map =
let mtype = typeof<Map<'k, 'v>>
let propt = mtype.GetProperty("Count")
if map.GetType() = mtype then
propt.GetValue(map) :?> int
else
-1
Test:
[<EntryPoint>]
let main argv =
let m = Map.ofSeq [ ("a", 1); ("b", 2)]
printfn "%d" (gencount<string, int> m)
printfn "%d" (gencount<string, string> m)
Console.ReadKey() |> ignore
0 // return exit code 0
Using _ in place of a type will simply end up as object if no additional constraint information is available. You use unbox when you strongly know what type your value is, except that the value is boxed in.

RSA decryption primitive (SP800-56B) using OpenSSL

I'm trying to implement RSA decryption primitive using OpenSSL (Refer https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf; section 7.1.2.1).
Here is my code:
BIGNUM *m = NULL, *n = NULL, *d = NULL, *c = NULL;
RSA *rsa = NULL;
int isValid = -1;
n = BN_bin2bn(N, 256, n);
d = BN_bin2bn(D, 256, d);
c = BN_bin2bn(ciphertext, 256, d);
rsa = RSA_new();
if (c == NULL || n == NULL || d == NULL)
printf("\n\nC,N,D is NULL, BN_bin2bn() failed!!\n\n");
isValid = BN_mod_exp(m, c, d, n, rsa);
RSA_free(rsa);
BN_free(n); BN_free(d); BN_free(m);
My inputs are shown below:
N : bff722714050aebb23a9bd018c3e9ba26a47f53816eeac7e10543958702d9265c8d67784fe03c07bfceac05e7f2a434971dfa2a5ea461893450ced52fcb3f143a85fb3a9194417ff220258840a3359a104079ccd201afec091bab6587d4cfe0b95bba34ef74a70b392a92a93f026c9bed41eb4ec80452492a2ad524e6b0333c5787b34ee941829020bb75ee5dd216b3734823ddd547d50f8a7e711f8a24fd7dbc0bd2f062ccaba98cdbf62c15d2521b39ce44c53125604493e482ae35f945c4efff1d01414b0aad33de77b020ea4aedf3d88171fe51b22881bc70c639f8b6f1b5a70ed39aa121a8f44887dcbbfce29e1e508d1b0f0666693b476d81faa6a18bd
D : a13aec8eba3a09c7dc18404b0083c52c10a00771e8b0e5e7abc751b2d9e52cc4987ea93be62d3889eacf306b2ddb4d506e782a9fb7b8d0034147ae3cb94a59253e51c3100fcc856b2021603ee66262b13e3536998291a9ce0b980a7720267e693485b890265b3b75578505e1e31e70ebfa3520385333bf97f9522183039658efd9b09fc0bd67a7d3c32e23adada71320ada2135f1d06a9144033ff9e0037a3b7ed1f5729b6db5f02470ecdde9eb2d97c759c73d13889bae550ab97205b67ce2f91eefb487f18c19bc6dd8831a43b0d699c771e1a9c55a1d5d2ae975691789b5c0a814c4f5e3d6a8e9e5f75419194b2d7dfe06700f6891cae8b712b3af1f9ec71
C : 534d1f57d948cac580b88b922bc47bc3d64c8cd1262bbf0944b99833ec94d072c1a1496be44d47a9c419dc403855a4b1cb2bb30e56e0cc5fd557d34373d785dbe70d67e30355fc228a353b05432a40874ba84253af5cc52d3ab4118e8ca1e28e6c9c610760e753f87a15912774ccb80b00ca21e85926143c1ed8385a607c4e55fa531f1f208bb3f23bc0c4eff4c272068f9939157bc61f5427cc32f017ef31f6363c8a736ec984da763ebea5eb94d83fa31d70223ec5503cfd97e598d883f43aca5e884b702a2f76d298659181cb5180e25faf56c9aa0ebe49413b9acbbefde95ec102ee4e351a8ff8d5a3fbdcee448ff466dffb45fdc0a0b3d31b3d192bb5cb
From the documentation, m can be derived by doing:
m = (c^d) mod n
I use the OpenSSL function BN_mod_exp() to do this. (Refer: https://www.openssl.org/docs/man1.1.0/man3/BN_mod_exp.html). I've followed the usage example of this function from : https://github.com/openssl/openssl/blob/master/test/bntest.c but still see the following error.
Can someone please tell me if they see anything wrong with what I've done!
I've made sure I copied values correctly and freed them after use.
Thanks in advance!
Update: I've passed in NULL arg as the fifth arg to BN_mod_exp function:
BN_mod_exp(m, c, d, n, NULL);
I still see an error, slightly different to the previous one. Initially I had the fifth arg as NULL but that gave me this error which is why I passed in NULL.
Shown the output after passing NULL below:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff792fd39 in fips_bn_ctx_start (ctx=0x0) at bn_ctx.c:261
261 if(ctx->err_stack || ctx->too_many)
(gdb) bt
#0 0x00007ffff792fd39 in fips_bn_ctx_start (ctx=0x0) at bn_ctx.c:261
#1 0x00007ffff7932a55 in fips_bn_mod_exp_mont (rr=0x0, a=0x6a9b30, p=0x6a9b30, m=0x6a99c0, ctx=0x0, in_mont=0x0) at bn_exp.c:417
#2 0x00007ffff79320f0 in fips_bn_mod_exp (r=0x0, a=0x6a9b30, p=0x6a9b30, m=0x6a99c0, ctx=0x0) at bn_exp.c:237
Datatypes of N, D and ciphertext:
unsigned char N[512];
unsigned char D[512];
unsigned char ciphertext[512];

Creating char Trie in OCaml

I'm trying to build an initial Trie structure in OCaml where the edges are the char. So the string "ESK" would be mapped as:
[('E', [('S', [('K', [])])])]
My definition for this is:
type trie = Trie of (char * trie) list
However, on implementing an add function with:
let rec add_string str =
let key = String.get str 0 in
if String.length str = 1 then
(key, empty_trie) :: []
else
(key, add_string (tail str)) :: []
for add (tail str) the compiler gives me:
Error: This expression has type (char * trie) list
but an expression was expected of type trie
I'm a bit puzzled by this as I have not defined a trie as (char * trie) list?
tail is simply let tail str = String.slice str 1 (String.length str) and empty_trie is let empty_trie = Trie([])
Note that a more idiomatic way of writing the function would be
let rec add_string str =
let key = str.[0] in
if String.length str = 1 then
Trie [key, empty_trie]
else
Trie [key, add_string (tail str)]
Then there are two problems left with add_string: first it reallocates a new string at each iteration. It is simpler and more efficient to keep track of the current position:
let add_string str =
let rec add_string_aux pos str =
if pos = String.length str then empty_trie
else
let key = str.[pos] in
Trie [key, add_string_aux (pos+1) str] in
add_string_aux 0 str
The second problem is that the function is ill-named since it does not add a string to an existing trie but build a trie from a string: from_string or of_string might be better names.
Resolved. Trie should be explicitly used:
let rec add_string str =
let key = String.get str 0 in
if String.length str = 1 then
(key, empty_trie) :: []
else
(key, Trie (add_string (tail str))) :: []
This will result in add_string "ESK" producing:
(char * trie) list = [('E', Trie [('S', Trie [('K', Trie [])])])]

Strange module loading issue in OCaml

I have two files: myUnionFind.ml and myUnionFind_test.ml. Both files are in the same directory.
myUnionFind.ml
open Batteries
module type MyUnionFindSig =
sig
type union_find
val print_array : 'a array -> unit
val create_union : int -> union_find
val union_weighted : union_find -> int -> int -> unit
val is_connected_weighted : union_find -> int -> int -> bool
end;;
module MyUnionFind : MyUnionFindSig =
struct
let print_array ary = print_endline (BatPervasives.dump ary);;
type union_find = {id_ary : int array; sz_ary : int array};;
let create_union n = {id_ary = Array.init n (fun i -> i);
sz_ary = Array.make n 1};;
(* weighted quick union find *)
let find_root ary i =
let rec find j =
if ary.(j) = j then j
else find ary.(j)
in
find i;;
let union_weighted {id_ary;sz_ary} p q =
let root_p = find_root id_ary p in
let root_q = find_root id_ary q in
if sz_ary.(root_p) < sz_ary.(root_q) then begin
id_ary.(root_p) <- id_ary.(root_q);
sz_ary.(root_q) <- sz_ary.(root_q) + sz_ary.(root_p)
end
else begin
id_ary.(root_q) <- id_ary.(root_p);
sz_ary.(root_p) <- sz_ary.(root_p) + sz_ary.(root_q)
end;;
let is_connected_weighted {id_ary;_} p q = (find_root id_ary p) = (find_root id_ary q);;
end
myUnionFind_test.ml
open Batteries
let uf2 = MyUnionFind.create_union 10;;
MyUnionFind.union_weighted uf2 0 3;;
MyUnionFind.union_weighted uf2 1 4;;
MyUnionFind.union_weighted uf2 4 3;;
MyUnionFind.union_weighted uf2 2 8;;
MyUnionFind.print_array uf2.MyUnionFind.id_ary;;
BatPervasives.print_bool (MyUnionFind.is_connected_weighted uf2 0 3);;
I tried
ocamlfind ocamlc -package batteries -c myUnionFind.ml. It worked, I can see myUnionFind.cmi and myUnionFind.cmo.
Then I tried to compile myUnionFind_test.ml via
ocamlfind ocamlc -package batteries -c myUnionFind_test.ml.
It gives this error:
File "myUnionFind_test.ml", line 3, characters 10-34: Error: Unbound
value MyUnionFind.create_union
I can't figure out why. I have defined create_union in module MyUnionFind, but why it can't be found?
You define a module in a module (your myUnionFind.ml is a module).
So in your test file, you have to open your module like this:
open Batteries
open MyUnionFind (* Here !*)
let uf2 = MyUnionFind.create_union 10;;
MyUnionFind.union_weighted uf2 0 3;;
MyUnionFind.union_weighted uf2 1 4;;
MyUnionFind.union_weighted uf2 4 3;;
MyUnionFind.union_weighted uf2 2 8;;
MyUnionFind.print_array uf2.MyUnionFind.id_ary;;
BatPervasives.print_bool (MyUnionFind.is_connected_weighted uf2 0 3);;
or prefix each call like:
let uf2 = MyUnionFind.MyUnionFind.create_union 10;;
If you just define a module in myUnionFind.ml and you don't want to have two modules like previously, you can just create a .ml and .mli file like this:
(* myUnionFind.mli *)
type union_find = {id_ary : int array; sz_ary : int array}
val print_array : 'a array -> unit
val create_union : int -> union_find
val union_weighted : union_find -> int -> int -> unit
val is_connected_weighted : union_find -> int -> int -> bool
(* myUnionFind.ml *)
type union_find = {id_ary : int array; sz_ary : int array};;
let print_array ary = (* ... *)
let create_union n = (* ... *)
let union_weighted r p q = (* ... *)
let find_root ary i = (* ... *)
Be careful, if you have a reference to id_ary field, you have to put it in the module signature
OCaml gives you one level of module for free with each file. So your myUnionFind.ml has a module within this free module. To avoid this, declare everything at the top level of the file. Then you have just one module, with the same name as the file.

Resources