Page 1 of 1

Exception handling using longjmp()

Posted: Thu Feb 21, 2019 5:21 pm
by Cesare
Hello to everyone,

Today I was doing some experiments trying to simulate the exception construct available in many languages but not in C.
I found out that we can achieve it using setjmp() and longjmp(). Everything works in a single thread environment but not when using multiple threads.

I am thinking if it is possible to make a data structure in which I can store the thread pointer when setjmp() is called and when the exception occurs (in another thread) I change the scheduler using chSchWakeupS() and then calling longjmp().
In this way setjmp() and longjmp() should be called together in the same thread context.

Did anyone have to face this problem?

Thank you in advance for any tips.

Re: Exception handling using longjmp()

Posted: Thu Feb 21, 2019 6:15 pm
by Giovanni
Hi,

You should have a separate "env" structure for each thread, it should work.

Giovanni

Re: Exception handling using longjmp()

Posted: Fri Feb 22, 2019 11:55 am
by Cesare
Good morning Giovanni,

Yes I tried, if I have several 'env' structures for each thread it works.
My only doubt is if before calling longjmp() I should lock the kernel with chSysLock() and then after the 'env' context has been restored (the program counter will be at the next instruction after setjmp() ) I call chSysUnlock.

In theory it should not necessary but maybe I am missing some 'low level' details.

Thanks

Re: Exception handling using longjmp()

Posted: Fri Feb 22, 2019 3:13 pm
by Giovanni
The context saved by setjmp does not save some internal registers used by chSysLock/chSysUnlock (BASEPRI), you should not assume that the interrupts masking state is preserved/restored.

Giovanni