Testing intermediate variables in a large file using Frama-c - c

I am trying to use Frama-c to check some properties of a C function that I have. The function is quite large and there are some intermediate variables that I need to check. (I am following this and this manual)
My program has the following structure:
There are 15 return statements spread throughout the program.
The variables I need to check are assigned values at several places in the program, depending on the path of the program.
my_function(){
intermediate var 1=xx;
//#assert var 1>some_value;
intermediate var 2=yy;
return var 4;
intermediate var 1=xx;
//#assert var 1>some_value;
return var 4;
intermediate var 2=xx;
intermediate var 1=yy;
//#assert var 1>some_value;
return var 4;
}
Explanation: I need to check certain properties related to var 1, var 2 and var 4. I tried 2 approaches.
use assert whenever var 1 is set as above.
Problem with this was that Frama-C checks only the first assert.
use annotations in the beginning.
/*# requires \valid(var 1);
ensures var 1 > some_value;
*/
In this case, Frama-C returns an error.
Question: How can I check the properties for intermediate problems? Is there a sample program?
*I haven't included my original function as it is very long.

As Virgile has mentioned, your question is not very clear, but I assume you are trying to validate some properties of var1 and var2.
This book provides some nice examples and I think the following should help you.
int abs(int val){
int res;
if(val < 0){
//# assert val < 0 ;
res = - val;
//# assert \at(val, Pre) >= 0 ==> res == val && \at(val, Pre) < 0 ==> res == -val;
} else {
//# assert !(val < 0) ;
res = val;
//# assert \at(val, Pre) >= 0 ==> res == val && \at(val, Pre) < 0 ==> res == -val;
}
return res;
}
The author has used the concept of Hoare triples in this scenario, where you check (assert) a certain property by asserting its requirements (pre-condition) for a property and check if a property holds after the corresponding statements are executed.
Hope this helps.

Related

Getting timeout error in New Year Chaos problem using scala

I have got a working scala code for New Year Chaos problem in Hackerrank, but Im recieving timeout errors in some test cases
https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
Please help me with optimization of below code:
def minimumBribes(q: Array[Int]){
val c = q.sorted
var swap = 0
var count_swap=0
import scala.util.control._
val loop = new Breaks
var temp = 0
var flag = true
loop.breakable
{
for (i <- q.length-1 to 0 by -1)
{
swap = 0
if (q(i) != i+1)
{
swap=i-q.indexOf(i+1)
if (swap > 2) {println("Too Chaotic");flag=false;loop.break()}
else
{
temp= q(q.indexOf(i+1))
q(q.indexOf(i+1)) = q(i-1)
q(i-1) = q(i)
q(i) = temp
count_swap += swap
if(q.deep == c.deep){
loop.break()
}
}
}
}
}
if (flag)println(count_swap)
}
To be honest I don't understand your implementation but
1) q.sorted could possibly already run out of time given that n is ~10^5.
2) q.sorted call is actually redundant since it's just a 1..n sequence.
3) using q.indexOf makes your algorithm O(n^2) complex. It's possible to solve it in linear time.

Move Zeroes in Scala

I'm working on "Move Zeroes" of leetcode with scala. https://leetcode.com/problems/move-zeroes/description/
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.
I have a solution which works well in IntelliJ but get the same Array with input while executing in Leetcode, also I'm not sure whether it is done in-place... Something wrong with my code ?
Thanks
def moveZeroes(nums: Array[Int]): Array[Int] = {
val lengthOrig = nums.length
val lengthFilfter = nums.filter(_ != 0).length
var numsWithoutZero = nums.filter(_ != 0)
var numZero = lengthOrig - lengthFilfter
while (numZero > 0){
numsWithoutZero = numsWithoutZero :+ 0
numZero = numZero - 1
}
numsWithoutZero
}
And one more thing: the template code given by leetcode returns Unit type but mine returns Array.
def moveZeroes(nums: Array[Int]): Unit = {
}
While I agree with #ayush, Leetcode is explicitly asking you to use mutable states. You need to update the input array so that it contains the changes. Also, they ask you to do that in a minimal number of operations.
So, while it is not idiomatic Scala code, I suggest you a solution allong these lines:
def moveZeroes(nums: Array[Int]): Unit = {
var i = 0
var lastNonZeroFoundAt = 0
while (i < nums.size) {
if(nums(i) != 0) {
nums(lastNonZeroFoundAt) = nums(i)
lastNonZeroFoundAt += 1
}
i += 1
i = lastNonZeroFoundAt
while(i < nums.size) {
nums(i) = 0
i += 1
}
}
As this is non-idomatic Scala, writing such code is not encouraged and thus, a little bit difficult to read. The C++ version that is shown in the solutions may actually be easier to read and help you to understand my code above:
void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
// After we have finished processing new elements,
// all the non-zero elements are already at beginning of array.
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
nums[i] = 0;
}
}
Your answer gives TLE (Time Limit Exceeded) error in LeetCode..I do not know what the criteria is for that to occur..However i see a lot of things in your code that are not perfect .
Pure functional programming discourages use of any mutable state and rather focuses on using val for everything.
I would try it this way --
def moveZeroes(nums: Array[Int]): Array[Int] = {
val nonZero = nums.filter(_ != 0)
val numZero = nums.length - nonZero.length
val zeros = Array.fill(numZero){0}
nonZero ++ zeros
}
P.S - This also gives TLE in Leetcode but still i guess in terms of being functional its better..Open for reviews though.

Compare NDIS_STRING case-insensitively at IRQL = DISPATCH_LEVEL?

I have a NDIS 6 filter driver. And I need to compare two NDIS_STRING in a case-insensitive manner at IRQL = DISPATCH_LEVEL. I know the RtlEqualUnicodeString function can compare strings in a case-insensitive manner. But it's only callable at PASSIVE_LEVEL.
So I have to write my own function using the basic memory copy way. And I found my function is not well functioned, because some of my users complain that this function returns FALSE when it's supposed to return TRUE. So there should be some bugs in my code. But I didn't find it by myself.
BOOLEAN
NPF_EqualAdapterName(
PNDIS_STRING s1,
PNDIS_STRING s2
)
{
int i;
BOOLEAN bResult;
TRACE_ENTER();
if (s1->Length != s2->Length)
{
IF_LOUD(DbgPrint("NPF_EqualAdapterName: length not the same, s1->Length = %d, s2->Length = %d\n", s1->Length, s2->Length);)
TRACE_EXIT();
return FALSE;
}
for (i = 0; i < s2->Length / 2; i ++)
{
if (s1->Buffer[i] >= L'A' && s1->Buffer[i] <= L'Z')
{
s1->Buffer[i] += (L'a' - L'A');
}
if (s2->Buffer[i] >= L'A' && s2->Buffer[i] <= L'Z')
{
s2->Buffer[i] += (L'a' - L'A');
}
}
bResult = RtlEqualMemory(s1->Buffer, s2->Buffer, s2->Length);
IF_LOUD(DbgPrint("NPF_EqualAdapterName: bResult = %d, s1 = %ws, s2 = %ws\n", i, bResult, s1->Buffer, s2->Buffer);)
TRACE_EXIT();
return bResult;
}
The entire code is here: https://github.com/nmap/npcap/blob/master/packetWin7/npf/npf/Openclos.c, if you want to know it.
So my question is simply, is there any bugs in the above code? Thanks!
UPDATE:
The adapter names (e.g., s1 and s2) are some GUIDs like {1CC605D7-B674-440B-9D58-3F68E0529B54}. They can be upper-case or lower-case. So they are definitely English.
An idea of using an index or key would be storing the names in GUID structure instead of strings. I noticed that Windows has provided RtlStringFromGUID and RtlGUIDFromString functions. However, these two functions also only work at IRQL = PASSIVE_LEVEL.
And much of my code just runs under DISPATCH_LEVEL. So I'm afraid storing in GUID is not a good idea.

AS3: Create a function that accepts both Array and Vector as an argument

I'm trying to create a function that will work for any array-like object in Flash but I'm really struggling to find a way to let the compiler know what I'm doing. I need to use functions like indexOf on the argument, but unless it is cast to the correct data type the compiler doesn't know that method is available. It's frustrating because Vector and Array share pretty much the same interface but there isn't an Interface to reflect that!
At the moment I've got this:
private function deleteFirst(tV:* , tVal:*):void {
trace(tV)
var tIndex:int
if (tV is Array) {
var tArray:Array = tV as Array
tIndex = tArray.indexOf(tVal)
if (tIndex >= 0) tArray.splice(tIndex, 1)
} else if (tV is Vector.<*>) {
var tVObj:Vector.<*> = tV as Vector.<*>
tIndex = tVObj.indexOf(tVal)
if (tIndex >= 0) tVObj.splice(tIndex, 1)
} else if (tV is Vector.<Number>) {
var tVNum:Vector.<Number> = tV as Vector.<Number>
tIndex = tVNum.indexOf(tVal)
if (tIndex >= 0) tVNum.splice(tIndex, 1)
} else if (tV is Vector.<int>) {
var tVInt:Vector.<int> = tV as Vector.<int>
tIndex = tVInt.indexOf(tVal)
if (tIndex >= 0) tVInt.splice(tIndex, 1)
} else if (tV is Vector.<uint>) {
var tVUInt:Vector.<uint> = tV as Vector.<uint>
tIndex = tVUInt.indexOf(tVal)
if (tIndex >= 0) tVUInt.splice(tIndex, 1)
}
trace(tV)
}
It kind of works but it's not exactly elegant! I'm wondering if there's a trick I'm missing. Ideally I'd do this by extending the base class, but I don't think that's possible with Vector.
Thanks
I would be very careful about mixing and matching Vectors and Arrays. The biggest difference between them is that Arrays are sparse, and Vectors are dense.
That said, here is your very compact generic removal function that will work on ANY "set" class that has indexOf and splice...
function deleteFirst( set:Object, elem:Object ) : Boolean
{
if ( ("indexOf" in set) && ("splice" in set) )
{
var idx:int = set.indexOf( elem );
if ( idx >= 0 )
{
set.splice( idx, 1 );
return true;
}
}
return false;
}
You can test the code with this code
var arr:Array = [ 1, 2, 3, 4, 5 ];
var vec:Vector.<int> = new Vector.<int>();
vec.push( 1, 2, 3, 4, 5 );
deleteFirst( arr, 2 ); // will remove 2
deleteFirst( vec, 3 ); // will remove 3
deleteFirst( "aaa4", "4" ); // nothing, cuz String doesn't have splice
trace( arr );
trace( vec );
UPDATE - For #Arron only, I've made the below change. Note that getting exceptions is good. They are informative and help reveal issues with the code path.
function deleteFirst( set:Object, elem:Object ) : Boolean
{
var idx:int = set.indexOf( elem );
if ( idx >= 0 )
{
set.splice( idx, 1 );
return true;
}
return false;
}
There! Now it's even simpler. You get an exception that tells you what's wrong!
This is definitely a short-coming of AS3, I don't think there is any elegant solution.
However, one code simplification you can make:
Since the syntax for indexOf() and splice() is the same for both arrays and vectors, you don't need that big if/else ladder to cast every type. You can simply call indexOf() and splice() on the object without any casting. Of course, you don't get any code-hints in your IDE, but it will work the same as you currently have. Example:
function deleteFirst(arrayOrVector:* , searchValue:*):* {
if (arrayOrVector is Array || arrayOrVector is Vector.<*> || arrayOrVector is Vector.<Number> || arrayOrVector is Vector.<int> || arrayOrVector is Vector.<uint>) {
var index:int = arrayOrVector.indexOf(searchValue)
if (index >= 0)
arrayOrVector.splice(index, 1)
}else
throw new ArgumentError("Argument 'arrayOrVector' must be an array or a vector, but was type " + getQualifiedClassName(arrayOrVector));
return arrayOrVector;
}
You can even skip the whole if/else type check and it would still work, it would just make the code more confusing, and you would get a slightly more confusing error if you called the function with an argument other than array or vector (like "indexOf not found on type Sprite" if you passed a sprite object by accident).
Also it's worth mentioning that, while this doesn't help you with number base type vectors, with other vectors you can sort of use Vector.<*> as a generic vector reference. You can assign a reference using the Vector global function with wildcard (Vector.<*>(myVector)) and it will return a reference to the original vector instead of a new copy as it usually does. If you don't mind returning a copy of number based type vectors instead of always modifying the original vector, you can still take advantage of this to simplify your code:
function deleteFirst(arrayOrVector:* , searchValue:*):* {
if (arrayOrVector is Array) {
var array:Array = arrayOrVector;
var index:int = array.indexOf(searchValue)
if (index >= 0)
array.splice(index, 1)
return array;
}else if(arrayOrVector is Vector.<*> || arrayOrVector is Vector.<Number> || arrayOrVector is Vector.<int> || arrayOrVector is Vector.<uint>) {
var vector:Vector.<*> = Vector.<*>(arrayOrVector);
index = vector.indexOf(searchValue);
if (index >= 0)
vector.splice(index, 1);
return vector;
}
throw new ArgumentError("Argument 'arrayOrVector' must be an array or a vector, but was type " + getQualifiedClassName(arrayOrVector));
}

Partially working array/hitTestobject

I am trying new things with arrays and having some difficulty. I am trying to create multiple instances of 1 class and putting them into an array.
I am creating the instances like so:
public function creatingitem(e:TimerEvent)
{
amtcreated = Math.ceil(Math.random() * 4);
while (amtcreated >= 1)
{
amtcreated--;
var i:Number = Math.ceil(Math.random() * 3);
switch (i)
{
case 1 :
//Object1
objectnum = 1;
objectwei = 3;
r = new Board(objectnum,objectwei,stagw,stagh);
addChild(r);
fallingitem.push(r);
break;
case 2 :
//Object2
objectnum = 2;
objectwei = 4;
c = new Board(objectnum,objectwei,stagw,stagh);
addChild(c);
fallingitem.push(c);
break;
case 3 :
//Object3
objectnum = 3;
objectwei = 4;
l = new Board(objectnum,objectwei,stagw,stagh);
addChild(l);
fallingitem.push(l);
break;
default :
break;
}
}
}
Once these are created they check if they collide with the main ball:
public function hitcheck(e:Event)
{
for (var v:int = fallingitem.length - 1; v >= 0; v--)
{
if (ball.hitTestObject(fallingitem[v]))
{
trace(fallingitem[v]);
if (fallingitem[v] == r)
{
bonusscore += 100;
fallingitem[v].removeitem();
}
else if (fallingitem[v] == c)
{
bonusscore += 75;
fallingitem[v].removeitem();
}
else if (fallingitem[v] == l)
{
bonusscore += 75;
fallingitem[v].removeitem();
}
trace(bonusscore);
}
}
}
The issue is I am seeing every item getting hit due to the trace function. Not all instances are meeting the if conditions. As an example I could have 2 "r" instances and when I hit both 1 will go through and add to the score and the other will just continue past. The trace directly following the hitTestObject shows me that both are being hit and registered but I am not sure why it does not add score.
Thank you,
You can't really have 2 r instances. When you're creating the instances, if you happen to create 2 rs, the second r = new Board... statement overwrites the reference, and the variable r is referring to the second one. Both objects still exist, but the variable can only refer to one of them, so when you perform the check, you're ignoring the object that was previously set to r but isn't any more.
To fix this, you could turn r, c and l into Arrays and whenever you create an instance, add it to the appropriate array. Then, you would perform the check using (r.indexOf(fallingitem[v]) != -1), which returns true if the object is in the array.
The other way, based on the provided code, would be to check whatever value objectnum is setting in the constructor, since you're setting that value based on whether it's in the r, c or l category. Though, that won't work if the property is private or might be changed.

Resources