Specification of Access Functions in ACSL - frama-c

I have a problem specifiying the access to internal state variables, i.e. those local to a module that are accessed by getters and setters only. I have tried to use the getter function in the specification of the function contract of the setter function, but frama-c returns an error:
> frama-c -wp -wp-rte -verbose 0 intstate.c intstate.h
...
intstate.h:4:[kernel] user error: unexpected token ')'
[kernel] user error: skipping file "intstate.c" that has errors.
[kernel] Frama-C aborted: invalid user input.
Here is the header:
int get_state(void);
/*#
# ensures val == get_state();
#*/
void set_state(int val);
and here the source:
#include "intstate.h"
static int the_state = 0;
int get_state(void) {
return the_state;
}
void set_state(int val) {
the_state = val;
}
I think it is a common problem. How is it done in ACSL? Does anyone have an example of a similar problem?
I use Frama-C Fluorine-20130601.
Thanks in advance
Frank
Edit:
Re-reading the ACSL spec more closely revealed to me that C-functions are not possible in specifications, only logic functions. I tried to wrap the C-function in a logic function but that wasn't accepted too, same error message. I finally modelled the interanl state variable by a ghost variable, but I am not sure if this is the decent approach.

Related

The program has unexpectedly finished. try catch throw in Qt

I have a problem in my qt project, when an exception is thrown my windows crash and close, why? Where is the problem? I do not understand.
class MyException:public std::exception{
private:
QMessageBox* mex;
public:
MyException(QString);
};
class err_parser_binary:public MyException{
public:
err_parser_binary(QString);
};
MyException::MyException(QString d):mex(new QMessageBox()){
mex->setText("Error");
mex->setDetailedText(d);
mex->button(QMessageBox::Ok);
mex->show();
}
err_parser_binary::err_parser_binary(QString detail): MyException(detail){
}
QString binary_controller::calcolaop1op2(QString x, QString y, QString op) try{
...............
Binary* pb=new Binary(op2);
..................
}
catch (err_parser_binary) {}
Binary::Binary(std::string str){
......
throw err_parser_binary("only 1 o 0");
......
}
From what I've read, Qt is not really exception safe. Take a look at this page. At the top, it says:
Preliminary warning: Exception safety is not feature complete! Common
cases should work, but classes might still leak or even crash.
Qt itself will not throw exceptions. Instead, error codes are used. In
addition, some classes have user visible error messages, for example
QIODevice::errorString() or QSqlQuery::lastError(). This has
historical and practical reasons - turning on exceptions can increase
the library size by over 20%.
You should just use error codes and/or error messages instead.

How to get QDBusConnection::connect() failure reason

I'm trying to connect to a D-Bus signal this way:
bool result = QDBusConnection::systemBus().connect(
"foo.bar", // service
"/foo/bar", // path
"foo.bar", // interface
"SignalSomething",
this,
SLOT(SignalSomethingSlot()));
if( !result )
{
// Why!?
}
QDBusConnection::connect() returns a boolean, how do I get extended error information? If a check QDBusConnection::lastError() it returns no useful information (as QDBusError::isValid() is false).
I had the same issue and it turned out that the slot I connected to had the wrong parameter types. They must match according to Qt's documentation and it looks like connect() verifies that, despite not explicitly mentioned.
Warning: The signal will only be delivered to the slot if the parameters match.
I suggest d-feet to list signals and check their parameter types. dbus-monitor does list signals, paths and such too, but not always the exact type of parameters.
One important observation though: I fixed the issue in my particular case by using different slot parameters than the actual signal has!
I wanted to connect to a com.ubuntu.Upstart0_6 signal mentioned here to detect when the screen in Ubuntu is locked/unlocked. dbusmonitor prints the following and d-feet shows parameters (String, Array of [String])
// dbusmonitor output
signal time=1529077633.579984 sender=:1.0 -> destination=(null destination) serial=809 path=/com/ubuntu/Upstart; interface=com.ubuntu.Upstart0_6; member=EventEmitted
string "desktop-unlock"
array [
]
Hence the signal should be of type
void screenLockChangedUbuntu(QString event, QVector<QString> args) // connect() -> false
This however made connect() return false. The solution was to remove the array parameter from the slot:
void screenLockChangedUbuntu(QString event) // works
I am aware that the array parameter was always empty, but I cannot explain why it only worked when removing it.
You could try these tricks:
1) Set QDBUS_DEBUG environment variable before running your application.
export QDBUS_DEBUG=1
2) Start dbus-monitor to see what's happening on the bus. You may need to set a global policy to be able to eavesdrop system bus depending on your distro.
Update:
Are you sure connecting to the system bus succeeded? If it fails you should probably check system.conf policy and possibly create own conf in system.d. This post might be helpful.
You could first connect to the system bus with QDBusConnection::connectToBus and check if it succeeded with QDBusConnection::isConnected. Only after that you try to connect to the signal and check if that succeeded.
QDBusConnection bus = QDBusConnection::connectToBus(QDBusConnection::systemBus, myConnectionName);
if (bus.isConnected())
{
if(!bus.connect( ... ))
{
// Connecting to signal failed
}
}
else
{
// Connecting to system bus failed
}

Photon Networking Instantiate Error (Unity3d)

Ok, so I'm making an online FPS in Unity and I was scripting that Photon Networking Script to connect and spawn the player and I keep getting these two errors:
Assets/Resources/GameManager.cs(64,23): error CS1502: The best overloaded method match for `PhotonNetwork.Instantiate(string, UnityEngine.Vector3, UnityEngine.Quaternion, int)' has some invalid arguments
Assets/Resources/GameManager.cs(64,23): error CS1503: Argument `#1' cannot convert `UnityEngine.Transform' expression to type `string'
Here is where the error is in my code:
// When Connected [Photon Callback]
void OnJoinedRoom()
{
PhotonNetwork.Instantiate(playerPrefab, transform.position, Quaternion.identity, 0);
}
//In Game: Disconnect from room.
void InGameGUI()
{
if (GUILayout.Button("Leave Game"))
PhotonNetwork.LeaveRoom();
}
}
And I did reference the Transform at the top:
public Transform playerPrefab;
Any ideas on what I did wrong and how I could fix it. Please help!
PhotonNetwork.Instantiate requires a string, not a Transform object as it's first parameter. (I do believe this was changed from a Transform object a while ago). Simply name the prefab that you want to instantiate (which must be in the Resources folder).

Extending phpunit error message

I want to add log output to all test messages.
$this->assertTrue(FALSE, "This assertion is False.". myLog::GetErrors());
I tried extending the PHPUnit_Framework_TestCase::assertThat function with my appended message, but it doesn't seem to have an effect on it. I know the extended PHPUnit_Framework_TestCase works because I have several helper functions (random string generation) in there as well that I use for testing.
Any other thoughts? Could it be a customer listener?
All of the assertions are static methods from PHPUnit_Framework_Assert and cannot be overridden by a subclass of TestCase. You can define your own assertions that call the originals with an amended message, however.
public static function assertTrue($value, $message='') {
PHPUnit_Framework_Assert::assertTrue($value, $message . myLog::GetErrors());
}
All failed tests call onNotSuccessfulTest() with the exception as the only parameter. You could override this method and in some cases add your log errors to the exception's message. Some of the PHPUnit exceptions provide a second description in addition to the error message contained in the exception.
public function onNotSuccessfulTest(Exception $e) {
if ($e instanceof PHPUnit_Framework_ExpectationFailedException) {
$e->setCustomMessage(implode(PHP_EOL,
array($e->getCustomMessage(), myLog::GetErrors())));
}
parent::onNotSuccessfulTest($e);
}
Update: As Gregory Lo noted in a comment below, setCustomMessage() and getCustomMessage() were removed in PHPUnit 3.6. :(
In recent PHPUnit Versions it is not necessary anymore.
When you specify the error parameter in an $this->assertXXXX() it preceeds PHPUnit's original message.
Screenshot:

RInside: parseEvalQ 'Parse Error' causes each subsequent call to parseEvalQ to give a 'Parse Error' even if exception handled

My code, which tries to emulate an R shell via C++, allows a user to send R commands over a tcp connection which are then passed to the R instance through the RInside::parseEvalQ function, during runtime. I have to be able to handle badly formatted commands. Whenever a bad command is given as an argument to parseEvalQ I catch the runtime error thrown (looking at RInside.cpp my specific error is flagged with 'PARSE_ERROR' 'status' within the parseEval(const string&, SEXP) function), what() gives a "St9exception" exception.
I have two problems, the first more pressing than the second:
1a . After an initial Parse Error any subsequent call to parseEvalQ results in another Parse Error even if the argument is valid. Is the embedded R instance being corrupted in some way by the parse error?
1b . The RInside documentation recommends using Rcpp::Evaluator::run to handle R exceptions in C++ (which I suspect are being thrown somewhere within the R instance during the call to parseEval(const string&, SEXP), before it returns the error status 'PARSE_ERROR'). I have experimented trying to use this but can find no examples on the web of how to practically use Rcpp::Evaluator::run.
2 . In my program I re-route stdout and stderr (at C++ level) to the file descriptor of my tcp connection, any error messages from the RInside instance get sent to the console, however regular output does not. I send RInside the command 'sink(stderr(), type="output")' in an effort to re-route stdout to stderr (as stderr appears to be showing up in my console) but regular output is still not shown. 'print(command)' works but i'd like a cleaner way of passing stdout straight to the console as in a normal R shell.
Any help and/or thoughts would be much appreciated. A distilled version of my code is shown below:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using namespace std;
string request_cpp;
ostringstream oss;
int read(FILE* tcp_fd)
{
/* function to read input from FILE* into the 'request_cpp' string */
}
int write(FILE* tcp_fd, const string& response)
{
/* function to write a string to FILE* */
}
int main(int argc, char* argv[])
{
// create RInside object
RInside R(argc,argv);
//socket
int sd = socket(PF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(40650);
// set and accept connection on socket
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
bind(sd,(struct sockaddr*)&addr, sizeof(addr));
listen(sd,1);
int sd_i = accept(sd, 0, 0);
//re-route stdout and stderr to socket
close(1);
dup(sd_i);
close(2);
dup(sd_i);
// open read/write file descriptor to socket
FILE* fp = fdopen(sd_i,"r+");
// emulate R prompt
write(fp,"> ");
// (attempt to) redirect R's stdout to stderr
R.parseEvalQ("sink(stderr(),type=\"output\");");
// read from socket and pass commands to RInside
while( read(fp) )
{
try
{
// skip empty input
if(request_cpp == "")
{
write(fp, "> ");
continue;
}
else if(request_cpp == "q()")
{
break;
}
else
{
// clear string stream
oss.str("");
// wrap command in try
oss << "try(" << request_cpp << ");" << endl;
// send command
R.parseEvalQ(oss.str());
}
}
catch(exception e)
{
// print exception to console
write(fp, e.what());
}
write(fp, "> ");
}
fclose(fp);
close(sd_i);
exit(0);
}
I missed this weeks ago as you didn't use the 'r' tag.
Seems like you are re-implementing Simon's trusted rserver. Why not use that directly?
Otherwise, for Rcpp question, consider asking on our rcpp-devel list.

Resources