Around the inbuilt functions in MPLAB

Around the inbuilt functions in MPLAB

MPLAB is an IDE that is very popular among the engineers who are using Microchip products. If you are an MPLAB user you should know the XC compilers.

If you have worked with XC assembly, you should know by now that using some of the assembly codes in the datasheets, exactly as it is won’t bring you the required outcome. In other words, it won’t work as expected.

So they have provided some inbuilt functions to do these tasks. But haven’t you wanted what inside these functions that are not in the datasheet? So let’s reverse engineer a function and see.

Setting up the environment

First of all, open a new project in the MPLAB IDE. Once the project is created, go to Window -> Target Memory Views -> Program Memory to open the program memory of your project.

 

Program Memory Open
Program Memory

And you will get the memory view for your MCU. In this memory view, the most important thing is the disassembly part.

Memory View
Memory View

Memory view shows you the entire assembly code of your program. What you have to do is filter the code for the inbuilt function from this. So let’s move on to that.

Reverse Engineering the Function

First of all, let’s put an inbuilt simple function in the code.

#include "xc.h"

int main(void) {
    __builtin_enable_interrupts();

    return 0;
}

Now if you compile this code, the assembly code of the inbuilt function used here should be in the memory view. But the problem is how to filter exact assembly lines from the huge pile of assembly codes.

In that case, what I do is that I put a known assembly code just before and after the function. This small trick will save the day.

#include "xc.h"

int main(void) {

    asm("GOTO 0x4800");
    __builtin_enable_interrupts();
    asm("GOTO 0x4800");

    return 0;
}

Now compile the code again and search for the assembly code that we just entered.

Search for Assembly Code
Search for Assembly Code

As you can see, in between two GOTO instructions that I put, a code segment is trapped. Now this trapped code is the assembly code of the inbuilt function. Now you could get the idea of what is happening really inside the inbuilt function.

So that’s it

You can compare the code you have just found with the one given in the datasheet to identify what’s missing there. If you have any suggestions or questions, comment here or email them to me.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top