Exception handling using longjmp()

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
User avatar
Cesare
Posts: 38
Joined: Tue Jul 11, 2017 11:51 am
Has thanked: 4 times
Been thanked: 4 times

Exception handling using longjmp()

Post 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.
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Exception handling using longjmp()

Post by Giovanni »

Hi,

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

Giovanni
User avatar
Cesare
Posts: 38
Joined: Tue Jul 11, 2017 11:51 am
Has thanked: 4 times
Been thanked: 4 times

Re: Exception handling using longjmp()

Post 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
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Exception handling using longjmp()

Post 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
Post Reply