Brew Extensions: How They Work and When to Use Them

xtensions are tricky objects. They behave similarly to C++ classes except they’re ruthlessly complicated to implement. They give Brew developers, usually limited to C code, a chance to stretch their legs into the wonderful world of objects and obfuscation. Extensions, when mastered, give nearly all the benefits of C++ style with a few drawbacks. In this article, I hope to do three things:

  1. I will bore you, at length, with an explanation of Brew’s extension architecture.
  2. I will demonstrate how to create, use and destroy a custom Brew extension.
  3. I will explain how to take advantage of C++ code from within a C only extension.

I’ve written a very simple object that reverses strings for the purpose of demonstration. It’s not a particularly useful or complicated object, but it should serve to demonstrate the topic at hand. Hopefully, you’ll finish with a strong understanding of Brew’s extensions and the experience to put that architecture to work in your own projects.

Extensions in Context
Before diving into the nuts and bolts, let’s quickly discuss how Brew extensions function from a somewhat academic standpoint. If you’re reading this article for more practical purposes, feel free to skip down to the next section.

In a single sentence, Brew extensions can be described as macro-accessed virtual tables.

Let’s break that down a little. At the heart of each extension lies a structure containing a series of function pointers. Here’s an example from the IReversal header file:

struct IReversalClsVtbl{	uint32 (*fnRelease)(IReversalCls *pIRevCls);	uint32 (*fnAddRef)(IReversalCls *pIRevCls);	uint32 (*fnSetString)(IReversalCls *pIRevCls, char *szStringData);	uint32 (*fnGetString)(IReversalCls *pIRevCls, char **ppszResult);	uint32 (*fnGetWideString)(IReversalCls *pIRevCls, AECHAR **ppszResult);};typedef struct IReversalClsVtbl IReversalClsVtbl;

In the above code, you can see that the structure contains a pointer to all the functions I’ll be fleshing out later in the extension. It is allocated and filled in at run-time to contain the addresses for every method in the object. To the public world outside the extension, the object appears to contain nothing more than the aforementioned table. In fact, here’s the public declaration for the IReversal extension also from IReversal.h:

struct _IReversalCls{	struct IReversalClsVtbl *pvt;};typedef struct _IReversalCls IReversalCls;

This simple one item structure is the public interface object that gives the rest of the applications on the phone access to your methods. It should be noted that the structure of this extension is slightly out-dated. It is possible to use AEEVTBL and other macros, provided by Qualcomm, to handle some of this busy work. For the purposes of clarity and ease of explanation, I’ll use the older technique. Here’s the internal version of the IReversal:

typedef struct _IReversal IReversal;struct _IReversal{	//VTable must be the first member of the structure	IReversalClsVtbl *pvt;	//Private data	IShell *pIShell;	IModule *pIModule;	uint16 nRefs;	//C++ object	void *m_pRevpp;};

To cast the external object to the internal one without crashing the handset, the public structure must be a subset of the private one. This means the vTable must be the first element in every extension. Once that first entry is out of the way, the order of the other elements doesn’t matter. Any number of private data types can follow.

Macros, published in the public header, reference the members of the vtable structure you saw earlier. Those references allow the rest of the world access to your extension. Because the above examples and explanation could be a little confusing, perhaps an example from the Brew API will better illustrate the point. For instance, Brew’s IDisplay extension is one of most important extensions a mobile engineer will interact with. It handles most of the display rendering done on the screen.

What exactly happens when someone calls IDISPLAY_Release? IDISPLAY_Release is a macro with the following definition:

#define IDISPLAY_Release(p)   AEEGETPVTBL(p,IDisplay)->Release(p)

This macro identifies a memory location. At the end of that pointer, the compiler will find the location of the “Release” function for the IDisplay object in memory, just as it would in the IReversal object. Runtime then jumps to that address in memory and executes. Ever wonder why the phone will crash and burn if you call IDISPLAY_Release on a null or junk pointer? The program executes from an off-set of address 0. This causes the stack to jump to an illegal location in the heap, hence the “Memory Access Error” crash that Brew programmers have come to hate so much.

From a practical standpoint, these custom extensions can be used anywhere that it would make sense to use a C++ class. Due to their complexity, programmers on a deadline tend to shy away from building generic extensions. This is a shame, as they allow for easy extensibility, reliability, portability, and obfuscation. Any extension you write for yourself can be easily packaged up and licensed to another company, another department, or given to your co-workers with a simple and easy interface. Again, Brew extensions have functionality nearly identical to a C++ class full of virtual functions. Almost any argument for the class is an argument for Brew extensions. Brew’s API is also a series of extensions; if you follow the directions laid out in this article, you can write an object to extend the functionality of a Brew object.

Digging Deeper
Enough theory, let’s look past the header at some source code and explore how it works. In order to get at the implementation of an extension, you’ll need to start with how Brew knows where to find it: the MIF file.

The first step in accessing your own custom extension (and the sample extension in this article) is to obtain a new class ID from Qualcomm’s Web site. This requires a login to the Brew extranet. Qualcomm will issue you a unique class ID for your extension. This hexadecimal number is unique to your object. Once your string reversal extension is installed on a phone, any Brew application with the correct permissions can call ISHELL_CreateInstance, pass in this unique ID, and your AEEClassCreateInstance function will be called. The MIF file makes this transaction possible by tying the unique class ID to your specific function within your module file. Here is what the creation function looks like:

int AEEClsCreateInstance(AEECLSID ClsId,IShell * pIShell,IModule * pMod,void ** ppObj){   *ppObj = NULL;   if(ClsId == AEECLSID_IREVERSAL)   {        if(AEEClsNew_Reversal(pIShell, pMod, ppObj))        {            return SUCCESS;        }   }   return EFAILED;}

In the above listing, your AEEClsCreateInstance is called, and you respond by returning the result of your constructor. It’s important to return true only when your function is called with the correct class ID. You now know how Brew finds your code to build a new extension, so you can look at how the process of building a new extension takes place (see Listing 1).

Let’s break down what’s happening in Listing 1. Once you’ve declared your structures and verified what’s been passed in, you’ll need to start grabbing memory. Your extension will need enough memory for the private structure and the vtable. You’ll allocate enough for both at the same time and set the vtbl pointer to the end of the private function. After you know there’s enough memory for the object and the vtable, you need to set the vtbl pointer to the appropriate location: the block of memory after your private object. Accomplish this with the following line:

vtbl = (IReversalClsVtbl *) ( (byte *)pMe + sizeof(IReversal));

Now, with memory in hand and the basic pointers in place, it’s possible to set up all the individual functions and fill in the vtable. From this point on, the process is fairly straight-forward. Set all the variables in the vtable to their corresponding functions and tie the vtable into the private object using INIT_VTBL. Then stash aside the module and shell pointers for later use, set up the return pointer, initialize any internal variables, and return Success.

Tip: The Brew heap manager (in Brew 3.x and greater) knows your extension is de-allocated when the reference count of module objects in your application reaches zero. If you don’t keep a reference for your module or leak it, you’ll find the handset crashing in some very creative ways. Additionally, if you don’t release your module pointer Brew will think your application is still open and won’t validate your heap. If this happens, in the simulator, you will not get memory leak reports. Be very careful with the module pointer count.

Now that you’ve got a fully functional extension, you can move on to at how it’s used. To quickly recap:

  • A user will call ISHELL_CreateInstance and pass in your class ID.
  • In turn, you will have your AEEClsCreateInstance function called and return an instance of your extension.
  • With that object, the user may then use your accessor macros to execute your functions.
  • These macros look up the location of your functions in memory, pass in the correct parameters, and you’re locked and loaded.

Take a look at a simple function GetString:

static uint32 IReversal_GetString(IReversalCls *pIRevCls, char **ppszResult){	IReversal *pMe = (IReversal *)pIRevCls;	if(STRLEN(pMe->szString))	{		*ppszResult = (char *)MALLOC(STRLEN(pMe->szString) + 1);		if(*ppszResult)		{			STRCPY(*ppszResult, pMe->szString);			return SUCCESS;		}		return ENOMEMORY;	}	return EBADSTATE;}

The first line of any extension function is going to be a pointer cast. It converts the single item structure containing only the vtable to the internal function containing all your private data. Recall that, in order for this cast to work, the vtable must be the first element in both structures. Once you have access to your pMe pointer, this function should be straight forward. You’re simply returning the string kept inside the private data.

Recall, from your C programming book gathering dust on the shelf, that functions declared static can only be referenced from within the file in which they’re defined. This piece of C lore, in combination with the vtable, is what makes obfuscation with extensions possible. Users cannot reference your functions by name directly, but you can reference them as you set their addresses up in the vtable. This is the secret sauce that allows the user to access the static functions from outside the file in which they’re defined.

Your last challenge is to release the module without setting off the memory leak alarm. This is the release function for your example extension:

static uint32 IReversal_Release(IReversalCls *pIRevCls){	IReversal *pMe = (IReversal *)pIRevCls;	//Check our Reference count.  If it's not at one we should just	//decrement the count and return	if(pMe->nRefs > 1)	{		pMe->nRefs--;		return pMe->nRefs;	}	if(pMe->pIShell)		ISHELL_Release(pMe->pIShell);	if(pMe->pIModule)		IMODULE_Release(pMe->pIModule);	//Release C++ object	IReversalpp_Release(pMe->m_pRevpp);	return 0;}

The purpose of the function listed above should be clear: if you have more than reference and the user calls release, you’ll decrement the reference count and return. Otherwise, you’ll clean up the internal data and release the object.

Tip: Notice that you return the current reference count on release and only de-allocate if the count is at 0. This behavior is consistent with all Brew objects. If you’re having trouble tracking down a leak and you think it might be an extension (Brew object, widget, or otherwise) check the number returned from the last time you’ve called release. If it isn’t 0, there’s still a reference floating around and you’ve just found the source of your problem.

As you can see, the process of creating, managing, and releasing a new object is fairly complex, but in reality the task changes very little from extension to extension. When working on your own, I would recommend that you copy this example as a template and fill in your own functions over mine. I’ve found it to be the easiest way to crank these things out.

Adventures in C++
On to the bonus round! As the ARM compiler has gotten better at correctly interpreting C++ code, many Brew programmers have decided to take that route for handset development. This makes it impossible, however, to have custom extensions since C++ compilers do not play nice with vtables and the guts of the Brew extensions architecture. Let’s take a look at how to make these two languages play nice with each other; along the way you’ll make a basic C++ class and explore how to tie these divergent objects together.

Obviously, the Brew Extension is a C only affair. This forces you to ‘wrap’ all the C++ class methods in C style function calls. Let’s see how this applies to the fictitious extension IReversal. IReversal.cpp contains a simple class with one function: Reverse. To get access to this class method from within the C extension, you’re going to have to do some preprocessor wizardry. The following code shows the mess you’ll have to declare in the header file (IReversal.h) to access the constructor, destructor, and method of the example C++ class:

#ifdef __cplusplusextern "C" {#endifboolean IReversalpp_New(IShell *pShell, void **ppCppObj);char * IReversalpp_Reverse(void *pObject, char *szString);void IReversalpp_Delete(void * pObject);#ifdef __cplusplus}#endif

What’s going on in the above declaration? This file is going to be included in both a C and C++ compile which means it’ll have to be palatable to both. If you’re doing a C++ compile, the precompiler flag __cplusplus will be true which extern the declarations as “C” style functions. This tells the C++ compiler to apply C style preprocessor and linking rules to them. When the compiler comes through IReversal.h from your extension file IReversal.c, these extern commands will be ignored and the functions will be linked normally as C functions. Here’s the trick: the functions themselves have to be within a C++ file so they have access to the C++ lexicon of class interactions. By now, you probably have a pretty good idea what these C functions are going to look like. They’re small, so take a look at them one at a time. Again, they’d be defined in IReversal.cpp:

boolean IReversalpp_New(IShell *pShell, void **ppCppObj){	//Set up the new pointer and pass in the IShell object.	*ppCppObj = (void *) new IReversalpp(pShell);	if(*ppCppObj)		return TRUE;	else		return FALSE;}

This function is really nothing more than a wrapper around the “new” function. It allocates and passes back a pointer to this new object. Remember that the C++ class must be stored by the C extension as a void pointer because a C compiler would have no idea what a “class” is. This is what the wrapper itself would look like:

char *IReversalpp_Reverse(void *pObject, char *szString){	IReversalpp pMe = (IReversalpp *) pObject;		return pMe->reverse(szString);}

The above code simply casts the void pointer to your class object and calls into the reversal method. As for the actual implementation of the string reversal method, ask any CS 101 student to help you out with that one. Now, you can take a look at the final function in this simple example, the destructor:

void IReversalpp_Delete(void *pObject){	IReversalpp pMe = (IReversalpp *) pObject;	delete pMe;}

Again, remember that your version of these should also be within the C++ file. It’s what allows them to access C++ syntax while at the same time letting them link into the C code. Using the tricks I’ve outlined above, you should be on your way to writing an extension wrapping a C++ class. Armed with this knowledge, you could also write your extension in C++ (using any number of classes) and pass that functionally back through BREW’s extension methodology.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet