SC_METHOD Exception - systemc

I'm trying to use a SC_METHOD in my simulation. Here is the code:
gcrypt::gcrypt(sc_module_name name):
gcrypt_base(name)
{
SC_METHOD(on_clock_update);
sensitive << clock;
dont_initialize();
};
void gcrypt::on_clock_update()
{
if (clock.read() == 0)
{
SC_REPORT_WARNING(name(), "Invalid clock port value of 0");
_ns_per_cycle = 0;
return;
}
_ns_per_cycle = 1e9 / clock.read();
}
The gcrypt_base constructor is:
gcrypt_base::gcrypt_base(sc_module_name name) :
sc_module(name),
...
{
...
}
I get this exception thrown by SC_METHOD:
Exception thrown at 0x6FB78281 (vcruntime140d.dll) in
SystemCModuleTest.exe: 0xC0000005: Access violation reading location
0x115348EF.
I saw the __vfptr value was "Unable to read memory".
How to solve this problem?

I believe you haven't specified the /vmg option while compiling your code. The /vmg option is required because of the way SystemC implements method processes.

Related

Why does xQueueReceive throw an unhandled exception (LoadProhibited)?

I'm working on an esp32 FreeRTOS application with two tasks. Its purpose is to take UART messages received from a peripheral device and transmit them via mqtt to a central broker.
The first task reads input from Serial1, processes the contents into a message structure, and adds it to a FreeRTOS queue:
typedef struct {
int length;
char buffer[AZ_EL_MAX_MESSAGE_LENGTH];
} tag_message_t;
void uart_read_task(void * pvParameters){
BaseType_t xStatus;
tag_message_t tag_message;
while(true) {
while(Serial1.available())
{
first_char = Serial1.read();
if (first_char == '+') // Indicates the beginning of a message
{
for(int i = 0; i < AZ_EL_MAX_MESSAGE_LENGTH; i++)
{
message_buffer[i] = Serial1.read();
if (message_buffer[i] == '\n') // End of message received
{
ESP_LOGV(TAG, "Message found: %s", message_buffer);
strncpy(tag_message.buffer, message_buffer, i + 1);
tag_message.length = i + 1;
xStatus = xQueueSend(xMessagesToSendQueue, (void*) &tag_message, 0);
if (xStatus != pdPASS)
ESP_LOGW(TAG, "Failed to queue message.");
break;
}
}
}
}
vTaskDelay(pdMS_TO_TICKS(20)); // Wait the minimum BLE advertisement period for messages to come in, i.e. 20ms
}
}
The main loop() (which is technically the second FreeRTOS task) then attempts to receive from that queue and transmit over MQTT to a local broker:
void setup()
{
Serial.begin(115200);
// Configure and start WiFi
configure_network();
connect_network();
// Configure the MQTT connection
configure_mqtt_client();
// Configure and create the inter-task queues
xMessagesToSendQueue = xQueueCreate(100, sizeof(tag_message_t));
if (xMessagesToSendQueue == NULL) {
ESP_LOGE(TAG, "Unable to create messaging queue. Will not create UART handling message queue.");
delay(10000);
esp_restart();
} else {
ESP_LOGI(TAG, "Messaging queue generated");
configure_uart();
xTaskCreate(uart_read_task, "UART_Processing", 20000, NULL, 1, NULL);
}
}
void loop()
{
const TickType_t xTicksToWait = pdMS_TO_TICKS(100); // milliseconds to wait
tag_message_t received_message;
if (network_connected) {
connect_mqtt_client();
while(mqtt_client.connected())
{
mqtt_client.loop();
// Process messages on the xMessagesToSendQueue
if (xMessagesToSendQueue != NULL)
{
ESP_LOGI(TAG, "Processing message");
if (xQueueReceive(xMessagesToSendQueue, &received_message, xTicksToWait) == pdPASS)
{
ESP_LOGD(TAG, "Received message, transmitting.");
if(!mqtt_client.publish("aoa", received_message.buffer, received_message.length));
ESP_LOGW(TAG, "Failed transmission.");
}
else
{
vTaskDelay(pdMS_TO_TICKS(50));
}
}
else
{
ESP_LOGE(TAG, "Messages queue is null.");
}
}
} else {
ESP_LOGE(TAG, "WARNING Device not connected to the network. Reconnecting.");
connect_network();
}
delay(5000);
}
I've verified that the MQTT broker works, that it connects to WiFi, and it can properly read messages from Serial1. HOWEVER, the xQueueReceive() call in loop() throws a LoadProhibited exception every time it's called.
Can anyone tell me what I'm getting wrong here?
All, thank you for your help. It turns out this wasn't a FreeRTOS issue. After a little research (i.e. reading this and watching a more experienced engineer explain things: [link]https://hackaday.com/2017/08/17/secret-serial-port-for-arduinoesp32/) it turns out ESP32 Serial1 pins are connected to flash memory.
Every time I tried Serial1.read() or Serial1.readBytesUntil() the ESP32 crashed. Turns out reading the flash is taboo?
I replaced '''Serial1.read()''' with '''Serial2.read()''' and others. That fixed everything. Now I'm off to optimizing my queues!
You are trying to receive an address on the Queue without casting it.
2 solutions: You either declare received_message as a Pointer:
tag_message_t* received_message;
...
received_message = new tag_message_t;
if (xQueueReceive(xMessagesToSendQueue, received_message, xTicksToWait) == pdPASS)
and don't forget to delete it right after usage.
Or you can cast it after receiving :
if (xQueueReceive(xMessagesToSendQueue, &received_message, xTicksToWait) == pdPASS)
{
received_message = *(static_cast<tag_message_t*>(&received_message));
ESP_LOGD(TAG, "Received message, transmitting.");
if(!mqtt_client.publish("aoa", received_message.buffer, received_message.length));
ESP_LOGW(TAG, "Failed transmission.");
}
or any other sort of dereferencing you might wanna try.
There is also the possibility xQueueReceive is already doing that! So let's be sure of what is going on by adding this:
ESP_LOGD(TAG, "Received message, transmitting. %s", received_message.buffer);
Right after you get the message.
I don't think tag_message is being deleted inside the task, so if the struct is still valid and present, if you properly parse/cast its address, you should be able to acquire the message without any issues.

error: expected type 'type' -- while trying to return error from an error set

I'm new to Zig and am trying to learn how error-handling and error sets work.
If I run
const erro = error{Oops};
fn failingFunction() erro.Oops!void {
return erro.Oops;
}
test "returning an error" {
failingFunction() catch |err| {
try expect(err == erro.Oops);
return;
};
}
I get an error:
error: expected type 'type', found 'erro'
fn failingFunction() erro.Oops!void {
^
./test.zig:45:31: note: referenced here
fn failingFunction() erro.Oops!void {
^
./test.zig:50:5: note: referenced here
failingFunction() catch |err| {
But when i use erro!void instead of erro.Oops!void as the funtion return type, the tests pass. Why is this so?
Please help. How do error unions work in the language? Thank You.
EDIT: The above is a modified function. The original function is
fn failingFunction() error{Oops}!void {
return error.Oops;
}
from this article: https://ziglearn.org/chapter-1/ in the "Errors" section. I wanted to experiment and so out of curiosity I did the above.
in failingFunction exception you have passed an error option (Oops) not error type. that's useless and wrong. overwrite your function with:
fn failingFunction() erro!void {
return erro.Oops;
}

Null pointer Exception at the end of draw processing3

I get a Null Pointer Exception, and the trace tells me it is inside a function that I have. This function runs every frame and does some calculations and stuff. Anyway, the problem is that when I go to debug, stepping through each line, the function runs fine, and the error only comes up at the end of the draw loop.
This error only recently came up, and the changes I made don't have much to do with the function in question so...
The function mentioned in the trace detects if the object touches something, and acts on it.
Also, the trace gives a line number that does not exist, I'm guessing that's because of the Processing compiling.
I am using Processing 4 if that matters.
Here's the trace:
java.lang.NullPointerException
at ants$Ant.sense(ants.java:190)
at ants$Ant.go(ants.java:220)
at ants.draw(ants.java:44)
at processing.core.PApplet.handleDraw(PApplet.java:2201)
at processing.awt.PSurfaceAWT$10.callDraw(PSurfaceAWT.java:1422)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:354)
Thanks!
Edit:
More info: This is an ant simulator, and it crashes at food pickup. This used to work and broke while adding (seemingly) unrelated stuff. It crashes at food pickup, which is managed by the sense() function. The Food class only has a position and a render function.
Here is some code:
void sense() { // The problematic function
if (!detectFood && !carryFood) {
float closest = viewRadius;
Food selected = null;
for (Food fd : foods){
float foodDist = position.dist(fd.position);
if(foodDist <= viewRadius) {
if(foodDist < closest) {
selected = fd;
closest = foodDist;
}
}
}
if (selected != null){
detectFood = true;
foodFocused = selected;
}
} else {
if(position.dist(foodFocused.position) < 2*r) {
takeFood();
detectFood = false;
}
}
}
void draw() { // draw loop
background(51);
for (Food food : foods) {
food.render();
}
for (Ant ant : ants) {
ant.go();
}
for (int i=0; i < trails.size(); i++) {
Trail trail = trails.get(i);
if (trail.strenght <= 0)
trails.remove(trail);
else
trail.go();
}
}
The problem is not the trail, as it still crashes without it,

ASSERT_THROW: error: void value not ignored as it ought to be

I am beginner to gtest. I trying to use ASSERT_THROW will compilation fail. Could anyone help on this:
class my_exp {};
int main(int argc, char *argv[])
{
EXPECT_THROW(throw my_exp(), my_exp); // this will pass
// This will through below compilation error
ASSERT_THROW(throw my_exp(), my_exp);
return 0;
}
Compilation output:
ERROR :
In file included from /usr/include/gtest/gtest.h:57:0,
from gtest.cpp:1:
gtest.cpp: In function ‘int main(int, char**)’:
gtest.cpp:12:3: error: void value not ignored as it ought to be
ASSERT_THROW(throw my_exp(), my_exp);
^
Short version
You write test in the wrong way, to write test you should put assertion inside test (macro TEST) or test fixtures (macro TEST_F).
Long version
1 . What's really happens?
To find out the real problem is not easy because the Google Testing Framework use macros which hide real code. To see code after macro substitution is required to perform preprocessing, something like this:
g++ -E main.cpp -o main.p
The result of preprocessing when using ASSERT_THROW will be looks like this (after formatting):
class my_exp {};
int main(int argc, char *argv[])
{
switch (0)
case 0:
default:
if (::testing::internal::ConstCharPtr gtest_msg = "") {
bool gtest_caught_expected = false;
try {
if (::testing::internal::AlwaysTrue () ) {
throw my_exp ();
};
} catch (my_exp const &) {
gtest_caught_expected = true;
} catch (...) {
gtest_msg.value = "Expected: throw my_exp() throws an exception of type my_exp.\n Actual: it throws a different type.";
goto gtest_label_testthrow_7;
} if (!gtest_caught_expected) {
gtest_msg.value = "Expected: throw my_exp() throws an exception of type my_exp.\n Actual: it throws nothing.";
goto gtest_label_testthrow_7;
}
}
else
gtest_label_testthrow_7:
return ::testing::internal::AssertHelper (::testing::TestPartResult::kFatalFailure, "main.cpp", 7, gtest_msg.value) = ::testing::Message ();
return 0;
}
For EXPECT_THROW result will be the same except some difference:
else
gtest_label_testthrow_7:
::testing::internal::AssertHelper (::testing::TestPartResult::kNonFatalFailure, "main.cpp", 7, gtest_msg.value) = ::testing::Message ();
2 . OK, the reason of different behaviour is found, let's continue.
In the file src/gtest.cc can be found AssertHelper class declaration including assignment operator which return void:
void AssertHelper::operator=(const Message& message) const
So now reason of the compiler complain is clarified.
3 . But why this problem is caused is not clear. Try realise why for ASSERT_THROW and EXPECT_THROW different code was generated. The answer is the macro from file include/gtest/internal/gtest-internal.h
#define GTEST_FATAL_FAILURE_(message) \
return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
#define GTEST_NONFATAL_FAILURE_(message) \
GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
which contain return for fatal case.
4 . But now is question why this assertions usually works well?
To answer of this question try investigate code snipped which written in correct way when assertion is placed inside test:
#include <gtest/gtest.h>
class my_exp {};
TEST (MyExp, ThrowMyExp)
{
ASSERT_THROW (throw my_exp (), my_exp);
}
To exclude pollution of the answer I just notice that in such case the return statement for ASSERT_THROW also exist, but it is placed inside method:
void MyExp_ThrowMyExp_Test::TestBody ()
which return void! But in your example assertions are placed inside main function which return int. Looks like this is source of problem!
Try prove this point with simple snippet:
void f1 () {};
void f2 () {return f1();};
//int f2 () {return f1();}; // error here!
int main (int argc, char * argv [])
{
f2;
return 0;
}
5 . So the final answer is: the ASSERT_THROW macro contain return statement for expression which evaluates to void and when such expression is placed into function which return non void value the gcc complain about error.
P.S. But anyway I have no idea why for one case return is used but for other case is not.
Update: I've asked this question on GitHub and got the following answer:
ASSERT_XXX is used as a poor man's exception to allow it to work in
environments where exceptions are disabled. It does a return; instead.
It is meant to be used from within the TEST() methods, which return
void.
Update: I've just realised that this question described in the official documentation:
By placing it in a non-void function you'll get a confusing compile error > like "error: void value not ignored as it ought to be".

Objective-C Exception Handling: "Divided by Zero Exception" is not getting caught

I have the following code in my program.
#try {
float result = 4 / 0; // LINE 1
} #catch (NSException *e) {
NSLog(#"Exception : %#", e);
return 0;
}
I expected an exception to be caught in LINE 1 and thrown to the #catch block. But the execution aborts at LINE 1 showing EXC_ARITHMETIC in console.
What am I doing wrong here? What necessary things I have to do to do exception handling?
EXC_ARITHMETIC is a type of low-level exception known as a "signal". The only way to catch them is to register a signal handler, for example:
#include<signal.h>
void handler(int signal) {
if (signal == FPE_FLTDIV)
printf("Divide by 0 exception\n");
}
signal(SIGFPE, handler);
However, the only safe thing to do in such a handler is clean up any resources and exit cleanly.
Divide by zero is not an NSException.
Give this a try (I never tried though):
#try {
float result = 4 / 0; // LINE 1
} #catch (NSException *e) {
NSLog(#"Exception : %#", e);
return 0;
}
#catch (id ue) {
//DIVIDE BY ZERO ATTEMPT MAY ENDUP HERE
NSLog(#"Exception : %#", ue);
return 0;
}
====== EDIT =======
Turns out divide by zero is not a obj-c exception. But seems you can catch such exceptions globally.
How do I catch global exceptions?
Exceptions List and division by zero isn't a predefined exception. Also, to know the type of exception, you should send name message to the exception object.
NSLog(#"Exception : %#", [ e name ] );
Actually float result = 4 / 0; would never raise any kind of signal or exception (xcode, LLVM). No idea why it just silently returns inf into result.
"4 / 0" is an expression with known literals, which can be very easily computed by compile time -- therefore there will be no runtime exception on that...
I am using the LLVM 5.1 compiler. In a *.m file just tried the line
float result = 4 / 0;
and
int result = 4 / 0;
and both give the result to be zero. But, because both contain the expression 4 / 0 which is integer division by zero regardless of the variable definition type, the compiler only gives a warning. All other compilers that I have used would have given an error from this expression.
The C language only specifies that integer division by zero is undefined. The compilers used in this case apparently define the result to be zero. This is a good example of why you should never depend on undefined behavior behaving the way you expect.