I'm working on an embedded system that has CMSIS FreeRtos with heap4 as memory management scheme.
Now I'm trying to port the mbedTls to my system and I must provide dynamic allocation functions like alloc and free.
mbedTLS require two function to allocate and free memory.
These are the function prototypes required by mbedTLS:
void * (*mbedtls_calloc)( size_t, size_t ) = MBEDTLS_PLATFORM_STD_CALLOC;
void (*mbedtls_free)( void * ) = MBEDTLS_PLATFORM_STD_FREE;
int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
void (*free_func)( void * ) )
Which is the best way to use correctly the heap provided by FreeRTOS?
Memory pool for example.
Heap4 does not provide function like calloc and free. So, which function should I wrap to allow mbedTls to allocate memory?
Thanks in advance for the help.
Federico
STEP 1:
Make a wrapper of calloc and free functions in your source as shown below.
void *pvWrap_mbedtls_calloc( size_t sNb, size_t sSize )
{
void *vPtr = NULL;
if (sSize > 0) {
vPtr = pvPortMalloc(sSize * sNb); // Call FreeRTOS or other standard API
if(vPtr)
memset(vPtr, 0, (sSize * sNb)); // Must required
}
return vPtr;
}
void vWrap_mbedtls_free( void *vPtr )
{
if (vPtr) {
vPortFree(vPtr); // Call FreeRTOS or other standard API
}
}
STEP 2: Register these API at initialization time of you application as shown below.
void Custom_MBEDTLS_Init(void)
{
mbedtls_platform_set_calloc_free(&pvWrap_mbedtls_calloc, &vWrap_mbedtls_free);
}
Related
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.
I am trying to write a general wrapper for Windows 10 notifications as a DLL. I've managed to write a DLL that does almost everything the API offers, except I can't get the notification to move to the Action Center. From what I can tell, I need to have a registered COM INotificationActivationCallback for a notification to stay in the Action Center, although I can't understand why.
I want this library to be accessible from an older MinGW-compiled code base, and as such have made an API based on accessing a C++ class using C-style functions. The backing implementation is as follows, with some error handling and other niceties omitted for brevity.
using namespace winrt::Windows;
using namespace UI;
class Win10NotificationManager {
public:
Win10NotificationManager(NotificationCallback, const wchar_t * appUserModelID, void * userdata);
virtual ~Win10NotificationManager();
void createNotification(const wchar_t * xml);
void clearNotifications();
private:
void toast_Failed(const Notifications::ToastNotification &, const Notifications::ToastFailedEventArgs & args);
void toast_Dismissed(const Notifications::ToastNotification &, const Notifications::ToastDismissedEventArgs & args);
void toast_Activated(const Notifications::ToastNotification &, const Foundation::IInspectable & object);
std::wstring appUserModelID_;
NotificationCallback cb_;
void * userdata_;
};
Win10NotificationManager::Win10NotificationManager(NotificationCallback cb, const wchar_t * appUserModelID, void * userdata)
: appUserModelID_(appUserModelID)
, cb_(cb)
, userdata_(userdata)
{
}
Win10NotificationManager::~Win10NotificationManager() {
}
void Win10NotificationManager::createNotification(const wchar_t * xml) {
// Create an XmlDocument from string
Xml::Dom::XmlDocument xmlDoc;
xmlDoc.LoadXml(xml);
// Create a toast object
Notifications::ToastNotification toast(xmlDoc);
// register event handlers
toast.Dismissed(Foundation::TypedEventHandler<Notifications::ToastNotification, Notifications::ToastDismissedEventArgs>(this, &Win10NotificationManager::toast_Dismissed));
toast.Failed(Foundation::TypedEventHandler<Notifications::ToastNotification, Notifications::ToastFailedEventArgs>(this, &Win10NotificationManager::toast_Failed));
toast.Activated(Foundation::TypedEventHandler<Notifications::ToastNotification, Foundation::IInspectable>(this, &Win10NotificationManager::toast_Activated));
// show
auto notifier = Notifications::ToastNotificationManager::CreateToastNotifier(appUserModelID_);
notifier.Show(toast);
}
void Win10NotificationManager::toast_Failed(const Notifications::ToastNotification &, const Notifications::ToastFailedEventArgs & args) {
HRESULT hr = args.ErrorCode();
winrt::check_hresult(hr);
}
void Win10NotificationManager::toast_Dismissed(const Notifications::ToastNotification &, const Notifications::ToastDismissedEventArgs &) {
cb_(nullptr, userdata_);
}
void Win10NotificationManager::toast_Activated(const Notifications::ToastNotification &, const Foundation::IInspectable & object) {
Notifications::IToastActivatedEventArgs args = winrt::unbox_value<Notifications::IToastActivatedEventArgs>(object);
cb_(args.Arguments().begin(), userdata_);
}
void Win10NotificationManager::clearNotifications() {
auto history = Notifications::ToastNotificationManager::History();
history.Clear(appUserModelID_);
}
This works quite well, except for the mentioned missing Action Center persistence. As the DLL is meant to be general (not specific to my one application) I'd like to avoid baking COM activation into the DLL. I don't need to have notifications persisted beyond the lifetime of the calling process, but it would be nice if the notifications weren't gone forever after 5 seconds.
If desired, I could create a gist with a Visual Studio 2017 solution.
In order to use the notification API from the desktop it requires both a registered COM server as well as a shell shortcut. I have no idea why this is necessary, but as far as I can tell that's the only way to make it work. This question comes up fairly often so I wrote a simple C++/WinRT example here:
https://gist.github.com/kennykerr/d983767262118ae0366ef1ec282e428a
Hope that helps.
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
}
};
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.
Is there any way to use the Interlocked.CompareExchange(); and Interlocked.Increment(); methods against values stored in a memory-mapped file?
I'd like to implement a multi-threaded service that will store its data in a memory-mapped file, but since it's multi-threaded I need to prevent conflicting writes, therefore I wonder about the Interlocked operations rather than using explicit locks.
I know it's possible with native code, but can it be done in managed code on .NET 4.0?
OK, this is how you do it! We had to figure this out, and I figured we could give some back to stackoverflow!
class Program
{
internal static class Win32Stuff
{
[DllImport("kernel32.dll", SetLastError = true)]
unsafe public static extern int InterlockedIncrement(int* lpAddend);
}
private static MemoryMappedFile _mmf;
private static MemoryMappedViewStream _mmvs;
unsafe static void Main(string[] args)
{
const int INT_OFFSET = 8;
_mmf = MemoryMappedFile.CreateOrOpen("SomeName", 1024);
// start at offset 8 (just for example)
_mmvs = _mmf.CreateViewStream(INT_OFFSET, 4);
// Gets the pointer to the MMF - we dont have to worry about it moving because its in shared memory
var ptr = _mmvs.SafeMemoryMappedViewHandle.DangerousGetHandle();
// Its important to add the increment, because even though the view says it starts at an offset of 8, we found its actually the entire memory mapped file
var result = Win32Stuff.InterlockedIncrement((int*)(ptr + INT_OFFSET));
}
}
This does work, and works across multiple processes! Always enjoy a good challenge!
TravisWhidden, actually you can use Interlocked.Increment Static method as dan-gph said, you just have to be careful with pointer casting and operator priority, plus parenthesis usage, in facts...
You'll cast a memory pointer (plus the desired offset), into a pointer to an int variable, then you'll use that pointer as a variable. Then you'll have to use it as a variable reference.
Below you'll find the corresponding snippet of yours using .net library instead of external static import.
P&L
class Program
{
private static MemoryMappedFile _mmf;
private static MemoryMappedViewStream _mmvs;
static void Main(string[] args)
{
const int INT_OFFSET = 8;
_mmf = MemoryMappedFile.CreateOrOpen("SomeName", 1024);
_mmvs = _mmf.CreateViewStream(INT_OFFSET, 4);
unsafe
{
IntPtr ptr = _mmvs.SafeMemoryMappedViewHandle.DangerousGetHandle();
Interlocked.Increment(ref (*((int*)(ptr + INT_OFFSET)))
}
}
}