Wednesday, November 19, 2008

    Writing a PIC32 wrapper function for malloc() and other system functions

    When debugging your MPLAB C Compiler for PIC32 MCUs project, have you ever wanted to wrap a system library function call in another function? You can with the linker's --wrap option.

    --wrap symbol
    Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to __wrap_symbol. Any undefined reference to __real_symbol will be resolved to symbol. This can be used to provide a wrapper for a system function. The wrapper function should be called __wrap_symbol. If it wishes to call the system function, it should call __real_symbol.
    Here is a trivial example:
    #include <stddef.h>
    #include <stdlib.h>
    extern void *__real_malloc (size_t);
    void *
    __wrap_malloc (int c)
    {
    printf ("malloc called with %ld\n", c);
    return __real_malloc (c);
    }
    If you link other code with this file using --wrap malloc, then all calls to malloc will call the function __wrap_malloc instead. The call to __real_malloc in __wrap_malloc will call the real malloc function. You may wish to provide a __real_malloc function as well, so that links without the --wrap option will succeed. If you do this, you should not put the definition of __real_malloc in the same file as __wrap_malloc; if you do, the assembler may resolve the call before the linker has a chance to wrap it to malloc.

    Microchip licenses this software to you solely for use with Microchip products. Microchip and its licensors retain all right, title and interest in and to the software. All rights reserved.

    This software and any accompanying information is for suggestion only. It shall not be deemed to modify Microchip’s standard warranty for its products. It is your responsibility to ensure that this software meets your requirements.

    SOFTWARE IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP OR ITS LICENSORS BE LIABLE FOR ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. The aggregate and cumulative liability of Microchip and its licensors for damages related to the use of the software will in no event exceed the amount you paid Microchip for the software.

    MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS. If you do not accept these terms, you must remove the software from your system.

    1 comment:

    Randy said...

    Fascinating. I wish I knew what I was doing well enough to actually take advantage of that.