Brew Extensions: How They Work and When to Use Them

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.

devx-admin

devx-admin

Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted