I'm developing software for an ARM Cortex M3 (NXP LPC1769) microncontroller. At the moment I'm searching for a mechansim to detect if my function is called within an ISR. I asume that I have to check a register. Based on this information I would like to call difficult functions.
I already checked the reference manual, if there is a register containing the necessary information.
For example I tried to detect if I'm called from an ISR (I used SysTick-ISR) based on the "Interrupt Active Bit Register" (IABR) register. This register should be != 0 if an ISR is active. But the value was 0x00000000. This implies that no interrupt is active. Besides this test I checked the NVIC and SC register in the reference manual searching for a register containing the necessary flag but I didn't found one.
Does anybody know a suitable register / mechanism for my problem?
You need to test the VECTACTIVE field of the Interrupt Control State Register.
I use the following:
//! Test if in interrupt mode
inline bool isInterrupt()
{
return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0 ;
}
SCM and SCB_ICSR_VECTACTIVE_Msk are defined in the CMSIS (core_cm3.h), which I imagine would be included indirectly by your part specific header (lpc17xx.h or similar I guess). I am using C++, including stdbool.h in C will get you a bool type, or change to an int or typedef of your own.
It is then used thus for example:
void somefunction( char ch )
{
if( isInterrupt() )
{
// Do not block if ISR
send( ch, NO_WAIT ) ;
}
else
{
send( ch, TIMEOUT ) ;
}
}
If a solution is required that assumes no knowledge of the architecture consider the following:
volatile int interrupt_nest_count = 0 ;
#define ENTER_ISR() interrupt_nest_count++
#define EXIT_ISR() interrupt_nest_count--
#define IN_ISR() (interrupt_nest_count != 0)
void isrA()
{
ENTER_ISR() ;
somefunction( 'a' ) ;
EXIT_ISR() ;
}
void isrB()
{
ENTER_ISR() ;
somefunction( 'b' ) ;
EXIT_ISR() ;
}
void somefunction( char ch )
{
if( IN_ISR() )
{
// Do not block if ISR
send( ch, NO_WAIT ) ;
}
else
{
send( ch, TIMEOUT ) ;
}
}
However the question refers to safely detecting the interrupt context, and this relies on the enter/exit macros being added to all ISRs.
After some discussion and more searching I found the right register:
Interrupt Program Status Register: The IPSR contains the exception type number of
the current Interrupt Service Routine (ISR). See the register summary in Table 626 for
its attributes.
If a function isn't called from an isr the value of the register is IPSR == 0
The simplest method is to pass the context as a parameter to the function. It is also platform independent.
typedef enum _context {
normal_context = 0,
isr_context = 1
} context;
Call to the function from ISR:
func(param1, param2, isr_context);
Call to the function from normal code:
func(param1, param2, normal_context);
If the ISR code is not under your control and you are just passing a function pointer, then just use two different wrapper functions. One that passes isr_context and another that passes normal_context as a parameter to the function.
The best way is probably to make two different functions: one that is called from the ISR and another that is called from the rest of the program.
If that isn't an option, then you could determine the caller with pure standard C, no registers needed:
inline void my_func (const char* caller);
static void isr (void)
{
my_func(__func__);
}
inline void my_func (const char* caller)
{
if(strcmp(caller, "isr")==0)
{
// was called from isr
}
else
{
// called from elsewhere
}
}
If you give your ISRs smart names, the above code will be quick enough to run from an isr.
Related
RANT-BEGIN
Before jumping right into already answered band wagon, please read this paper about SE outdated answers https://ieeexplore.ieee.org/document/8669958
Things changes after a time, and I am afraid Computer science is one of the most if not the most field out there where APIs and Interfaces change radically very very fast. Needless to say that a solution that might worked last month might not after latest feature added to a platform/framework. I humbly request you to not mark this question as answered with decade old post when many mainstream things did not even existed. If you dont know latest solution dont bother about it and leave question for someone else who might.
For a community representative of Computer Science where innovations is everyday thing, it is very toxic, new comer unfriendly and conservative.
END-RANT
This question has already been answered by me and will be accepted tomorrow (SE policy). Thank you for your interest.
Many times you have function pointers in unmanaged context which are called by some kind of events, We will see how it can be achieved with Top-Level Functions and also with member functions of a managed class.
Again, Please dont mark it as answered by linking to a decade old posts.
PS:
So many edits due to unstable internet in third world country, yeah bite me!
unmanaged.cpp
#pragma unmanaged
// Declare an unmanaged function type that takes one int arguments and callbacks
// our function after incrementing it by 1
// Note the use of __stdcall for compatibility with managed code
// if your unmanaged callback uses any other calling convention you can
// UnmanagedFunctionPointerAttribute (check msdn for more info) on your delegate
typedef int(__stdcall* ANSWERCB)(int);//Signature of native callback
int TakesCallback(ANSWERCB fp, int a) {
if (fp) {
return fp(a+1);//Native Callback
}
// This code will be executed when passed without fp
return 0;
}
#pragma managed
managed.cpp
using namespace System;
using namespace System::Runtime::InteropServices;
namespace Callbacks {
// Following delegate is for unmanaged code and must match its signature
public delegate void MyNativeDelegate(int i);
// This delegate is for managed/derived code and ideally should have only managed parameters
public delegate void MyManagedDelegate(int i);
public ref class TestCallback {// Our demo Managed class
private:
GCHandle gch;// kept reference so that it can be freed once we are done with it
void NativeCallbackListener(int i);//unmanaged code will call this function
public:
void TriggerCallback(int i); // Its here for demo purposes, usually unmanaged code will call automatically
event MyManagedDelegate^ SomethingHappened;//plain old event
~TestCallback();//free gch in destructor as its managed.
};
};
void Callbacks::TestCallback::NativeCallbackListener(int i) {
// Callback from Native code,
// If you need to transform your arguments do it here, like transforming void* to somekind of native structure.
// and then pass SomethingHappened::raise with Managed Class/Struct
return SomethingHappened::raise(i); // similar to SomethingHappened.Invoke() in c#
}
void Callbacks::TestCallback::TriggerCallback(int i)
{
MyNativeDelegate^ fp = gcnew MyNativeDelegate(this, &TestCallback::NativeCallbackListener);
// use this if your nativecallback function is not a member function MyNativeDelegate^ fp = gcnew MyNativeDelegate(&NativeCallbackListener);
gch = GCHandle::Alloc(fp);
IntPtr ip = Marshal::GetFunctionPointerForDelegate(fp);
ANSWERCB cb = static_cast<ANSWERCB>(ip.ToPointer());// (ANSWERCB)ip.ToPointer(); works aswell
// Simulating native call, it should callback to our function ptr NativeCallbackListener with 2+1;
// Ideally Native code keeps function pointer and calls back without pointer being provided every time.
// Most likely with a dedicated function for that.
TakesCallback(cb, i);
}
void Callbacks::TestCallback::~TestCallBack() {
gch.Free();//Free GCHandle so GC can collect
}
implementation.cpp
using namespace System;
void OnSomethingHappened(int i);
int main(array<System::String^>^ args)
{
auto cb = gcnew Callbacks::TestCallback();
cb->SomethingHappened += gcnew Callbacks::MyManagedDelegate(&OnSomethingHappened);
cb->TriggerCallback(1);
return 0;
}
void OnSomethingHappened(int i)
{
Console::WriteLine("Got call back with " + i);
}
Is there a way i can enable an automatic warning for my SystemC simulation whenever a fixed point variable overflows?
I already discovered the overflow_flag() function, but that one have to be check manually for every time i write to a signal in my code. Also, as I interpret the documentation, this flag does not discern between overflowing and precision loss?
Is there a way i can enable an automatic warning for my SystemC simulation whenever a fixed point variable overflows?
Not in a centralized, standard way.
If you want to monitor a fixed set of variables, you may be able to use the sc_fxnum_observer extension available in some SystemC implementations.
To use it, you have to #define SC_ENABLE_OBSERVERS before including SystemC (ideally from your compiler command-line). The allows you to "attach" an observer to your sc_fixed<...> (and related) classes, which is notified upon the following events:
class sc_fxnum_observer
{
public:
virtual void construct( const sc_fxnum& );
virtual void destruct( const sc_fxnum& );
virtual void read( const sc_fxnum& );
virtual void write( const sc_fxnum& );
};
You can then for example check the overflow_flag in a custom observer's write function:
struct overflow_observer : sc_dt::sc_fxnum_observer
{
virtual void write( const sc_fxnum& v )
{
if( v.overflow_flag() )
// ...
}
};
During construction of a variable, you can pass a pointer to the observer then:
overflow_observer my_overflow_observer;
sc_dt::sc_fixed<...> f( &my_overflow_observer );
For a signal, the easiest solution is to derive a specialized signal and check for the overflow flag inside an overridden update function.
template <int W, int I,
sc_q_mode Q = SC_DEFAULT_Q_MODE_,
sc_o_mode O = SC_DEFAULT_O_MODE_, int N = SC_DEFAULT_N_BITS_>
class fixed_signal : public sc_core::sc_signal< sc_dt::sc_fixed<W,I,Q,O,N> >
{
typedef sc_core::sc_signal< sc_dt::sc_fixed<W,I,Q,O,N> > base_type;
public:
// constructor, etc.
// ...
using base_type::operator=;
protected:
void update()
{
base_type::update();
if( read().overflow_flag() )
// ...
}
};
Also, as I interpret the documentation, this flag does not discern between overflowing and precision loss?
Yes.
So in class, we learned about semaphores and stuff and our professor let us know that this code below would be handy to learn for our exam. Unfortunately our exam is on Friday, and whole list of excuses, i just need to be able to understand this code for the exam and for future cases. I understand that the mutex_t is a lock system and the cond_t is a condition system in which signals get passed through sema_P and sema_V (if the value is 0, race condition occurs and the thread is locked out by cond_wait until another thread increases the value and is unlocked by cond_signal), but why does a lock need to get passed around? Why is there a mutex_lock and mutex_unlock in both decrementer P() and incrementer V()? How does this work with the threads and the conditions (cont_t)?
typedef struct
{
pthread_mutex_t lock;
pthread_cond_t wait;
int value;
} sema;
void pthread_sema_init(sema *s, int count)
{
s->value = count;
pthread_cond_init(&(s->wait),NULL);
pthread_mutex_init(&(s->lock),NULL);
return;
}
void pthread_sema_P(sema *s)
{
pthread_mutex_lock(&(s->lock));
s->value--;
if(s->value < 0) {
pthread_cond_wait(&(s->wait),&(s->lock));
}
pthread_mutex_unlock(&(s->lock));
return;
}
void pthread_sema_V(sema *s)
{
pthread_mutex_lock(&(s->lock));
s->value++;
if(s->value <= 0) {
pthread_cond_signal(&(s->wait));
}
pthread_mutex_unlock(&(s->lock));
}
The mutex sema.lock is there to protect the shared variable sema.value, ensuring that only one thread accesses that value at a time. Both pthread_sema_P() and pthread_sema_V() must take the lock because they both access sema.value.
That implementation of sempahores is buggy, by the way - it doesn't handle spurious wakeups (a "spurious wakeup" is where pthread_cond_wait() wakes up despite not being signalled - this is allowed by the spec).
A more traditional implementation might be:
void pthread_sema_P(sema *s)
{
pthread_mutex_lock(&s->lock);
while (s->value < 1) {
pthread_cond_wait(&s->wait, &s->lock);
}
s->value--;
pthread_mutex_unlock(&s->lock);
}
void pthread_sema_V(sema *s)
{
pthread_mutex_lock(&s->lock);
s->value++;
pthread_cond_signal(&s->wait);
pthread_mutex_unlock(&s->lock);
}
In the past, we've had some trouble with uninitialized data in C-code. I've tried two different static code analysis tools on the code example below. None of them complain about passing a pointer to uninitialized data. Are you aware of any tool that would catch this?
Thank you in advance!
static int useByVal(const int int_val)
{
return int_val + 1;
}
static void useByRef(int* const int_ptr)
{
if (int_ptr != (void*)0)
{
(*int_ptr)++;
}
}
int main(void)
{
int i;
int k;
/*** GOOD: The tool detects error: Using value of uninitialized automatic object 'i' */
i = useByVal(i);
/*** BAD: The tool does not catch uninitialized object 'k' when passed by reference */
useByRef(&k);
/*** BAD: Since call to 'useByRef(&k)', the tool now consider 'k' as initialized */
return i+k;
}
No I'm not aware if any tool that would catch that. The reason is that they usually analyze on a function-by-function basis. In other words, while analyzing main tools would not analyze useByVal or useByRef, but make reasonable assumptions about them (like they expect an uninitialized object).
Additionally, if they did generate messages in this case, then you would need to add comments / pragmas to remove them and say "this usage is OK; don't emit a message any more". Because of the nature and frequency of pointer-passing, your program would be full of them.
Better implement some dynamic technique and catch the problem during testing.
I have a vendor supplied .DLL and an online API that I am using to interact with a piece of radio hardware; I am using JNA to access the exported functions through Java (because I don't know C/C++). I can call basic methods and use some API structures successfully, but I am having trouble with the callback structure. I've followed the TutorTutor guide here and also tried Mr. Wall's authoritative guide here, but I haven't been able to formulate the Java side syntax for callbacks set in a structure correctly.
I need to use this exported function:
BOOL __stdcall SetCallbacks(INT32 hDevice,
CONST G39DDC_CALLBACKS *Callbacks, DWORD_PTR UserData);
This function references the C/C++ Structure:
typedef struct{
G39DDC_IF_CALLBACK IFCallback;
//more omitted
} G39DDC_CALLBACKS;
...which according to the API has these Members (Note this is not an exported function):
VOID __stdcall IFCallback(CONST SHORT *Buffer, UINT32 NumberOfSamples,
UINT32 CenterFrequency, WORD Amplitude,
UINT32 ADCSampleRate, DWORD_PTR UserData);
//more omitted
I have a G39DDCAPI.java where I have loaded the DLL library and reproduced the API exported functions in Java, with the help of JNA. Simple calls to that work well.
I also have a G39DDC_CALLBACKS.java where I have implemented the above C/C++ structure in a format works for other API structures. This callback structure is where I am unsure of the syntax:
import java.util.Arrays;
import java.util.List;
import java.nio.ShortBuffer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.BaseTSD.DWORD_PTR;
import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
public class G39DDC_CALLBACKS extends Structure {
public G39DDC_IF_CALLBACK IFCallback;
//more omitted
protected List getFieldOrder() {
return Arrays.asList(new String[] {
"IFCallback","DDC1StreamCallback" //more omitted
});
}
public static interface G39DDC_IF_CALLBACK extends StdCallCallback{
public void invoke(ShortBuffer _Buffer,int NumberOfSamples,
int CenterFrequency, short Amplitude,
int ADCSampleRate, DWORD_PTR UserData);
}
}
Edit: I made my arguments more type safe as Technomage suggested. I am still getting a null pointer exception with several attempts to call the callback. Since I'm not sure of my syntax regarding the callback structure above, I can't pinpoint my problem in the main below. Right now the relevant section looks like this:
int NumberOfSamples=65536;//This is usually 65536.
ShortBuffer _Buffer = ShortBuffer.allocate(NumberOfSamples);
int CenterFrequency=10000000;//Specifies center frequency (in Hz) of the useful band
//in received 50 MHz wide snapshot.
short Amplitude=0;//The possible value is 0 to 32767.
int ADCSampleRate=100;//Specifies sample rate of the ADC in Hz.
DWORD_PTR UserData = null;
G39DDC_CALLBACKS callbackStruct= new G39DDC_CALLBACKS();
lib.SetCallbacks(hDevice,callbackStruct,UserData);
//hDevice is a handle for the hardware device used-- works in other uses
//lib is a reference to the library in G39DDCAPI.java-- works in other uses
//The UserData is a big unknown-- I don't know what to do with this variable
//as a DWORD_PTR
callbackStruct.IFCallback.invoke(_Buffer, NumberOfSamples, CenterFrequency,
Amplitude, ADCSampleRate, UserData);
EDIT NO 2:
I have one callback working somewhat, but I don't have control over the buffers. More frustratingly, a single call to invoke the method will result in several runs of the custom callback, usually with multiple output files (results vary drastically from run to run). I don't know if it is because I am not allocating memory correctly on the Java side, because I cannot free the memory on the C/C++ side, or because I have no cue on which to tell Java to access the buffer, etc. Relevant code looks like:
//before this, main method sets library, starts DDCs, initializes some variables...
//API call to start IF
System.out.print("Starting IF... "+lib.StartIF(hDevice, Period)+"\n")
G39DDC_CALLBACKS callbackStructure = new G39DDC_CALLBACKS();
callbackStructure.IFCallback = new G39DDC_IF_CALLBACK(){
#Override
public void invoke(Pointer _Buffer, int NumberOfSamples, int CenterFrequency,
short Amplitude, int ADCSampleRate, DWORD_PTR UserData ) {
//notification
System.out.println("Invoked IFCallback!!");
try {
//ready file and writers
File filePath = new File("/users/user/G39DDC_Scans/");
if (!filePath.exists()){
System.out.println("Making new directory...");
filePath.mkdir();
}
String filename="Scan_"+System.currentTimeMillis();
File fille= new File("/users/user/G39DDC_Scans/"+filename+".txt");
if (!fille.exists()) {
System.out.println("Making new file...");
fille.createNewFile();
}
FileWriter fw = new FileWriter(fille.getAbsoluteFile());
//callback body
short[] deBuff=new short[NumberOfSamples];
int offset=0;
int arraySize=NumberOfSamples;
deBuff=_Buffer.getShortArray(offset,arraySize);
for (int i=0; i<NumberOfSamples; i++){
String str=deBuff[i]+",";
fw.write(str);
}
fw.close();
} catch (IOException e1) {
System.out.println("IOException: "+e1);
}
}
};
lib.SetCallbacks(hDevice, callbackStructure,UserData);
System.out.println("Main, before callback invocation");
callbackStructure.IFCallback.invoke(s_Pointer, NumberOfSamples, CenterFrequency, Amplitude, ADCSampleRate, UserData);
System.out.println("Main, after callback invocation");
//suddenly having trouble stopping DDCs or powering off device; assume it has to do with dll using the functions above
//System.out.println("StopIF: " + lib.StopIF(hDevice));//API function returns boolean value
//System.out.println("StopDDC2: " + lib.StopDDC2( hDevice, Channel));
//System.out.println("StopDDC1: " + lib.StopDDC1( hDevice, Channel ));
//System.out.println("test_finishDevice: " + test_finishDevice( hDevice, lib));
System.out.println("Program Exit");
//END MAIN METHOD
You need to extend StdCallCallback, for one, otherwise you'll likely crash when the native code tries to call the Java code.
Any place you see a Windows type with _PTR, you should use a PointerType - the platform package with JNA includes definitions for DWORD_PTR and friends.
Finally, you can't have a primitive array argument in your G39DDC_IF_CALLBACK. You'll need to use Pointer or an NIO buffer; Pointer.getShortArray() may then be used to extract the short[] by providing the desired length of the array.
EDIT
Yes, you need to initialize your callback field in the callbacks structure before passing it into your native function, otherwise you're just passing a NULL pointer, which will cause complaints on the Java or native side or both.
This is what it takes to create a callback, using an anonymous instance of the declared callback function interface:
myStruct.callbackField = new MyCallback() {
public void invoke(int arg) {
// do your stuff here
}
};