[Table of Contents] [Next] [Previous]

Chapter 9

Application Programming Interface


This chapter is a complete reference to the Memory Advisor API, as defined by the memadv.h header file.

Introduction
Memory Advisor API Variables and Macros
Configuration Option Names
The Memory Advisor Operating Mode
The MA_CHK_READ and MA_CHK_WRITE Constants
The _ma_errno Variable
Thread States
The Memory Advisor Error File Descriptor
The Memory Advisor Historical IDs
Overriding Memory Advisor's Internal Allocator
Integrating a User-Defined Memory Allocator
Miscellaneous Variables
Commonly Used Functions
Functions for Memory Leak Reports
Functions for Other Reports
Functions for Controlling Memory Advisor
Functions for Memory Advisor Watchpoints
Functions for Checking Data Access
Functions for Getting Stack Trace Information
Macros for Implementing Discretionary Debugging
Functions for Integrating User-Defined Memory Allocators
Function Descriptions
MaAllocChainCheck()
MaAllocChainList()
MaAllocFreeFifoFlush()
MACL()
MADBG()
MADBG_CODE()
MADBG_LOC()
MaLeakBase()
MaLeakClearAll()
MaLeakPtrNoLeakSearch()
MaLeakPtrNotALeak()
MaLeakShowAll()
MaLeakShowNew()
MaOptionGet()
MaOptionSet()
MaOptionShowAll()
MaOutputHandler()
MaOutputInfoMsg()
MaOutputString()
MaProcAbort()
MaProcExit()
MaProcFuncList()
MaProcInitLibrary()
MaProcReadSyms()
MaPtrCheckData()
MaPtrCheckString()
MaPtrCheckStringCh()
MaPtrCheckStringLen()
MaPtrDataSize()
MaPtrInfo()
MaPtrSetMode()
MaReportAddressMap()
MaReportAllocations()
MaReportFdLeaks()
MaStackGet()
MaStackGetCaller()
MaStackGetCurrent()
MaStackGetEntry()
MaStackGetLevel()
MaStackWriteToFd()
MaStackWriteToFile()
MaStop()
MaThreadWhoHasLock()
MaUsrAllocArenaDelete()
MaUsrAllocArenaExtend()
MaUsrAllocArenaNew()
MaUsrAllocSegFifoAdd()
MaUsrAllocSegFree()
MaUsrAllocSegReg()
MaUsrAllocSegRegister()
MaUsrAllocSegRelease()
MaWatchAdd()
MaWatchCheckAll()
MaWatchnRead()
MaWatchnReadWrite()
MaWatchnWrite()
MaWatchRemove()
MaWatchRemoveAll()
MaWatchShowAll()

Introduction

The functions in the API provide you with tools to access dynamic memory and stack context information. Using these functions, you can set Memory Advisor configuration options during program execution so that you can enable, modify, and disable error-checking for portions of your program. These functions also let you report memory and stack information at any point in your program, not just at Memory Advisor default points.

To use Memory Advisor functions, variables, and macros:

The following sections discuss the various parts of the Memory Advisor API as described in memadv.h.


Memory Advisor API Variables and Macros

Configuration Option Names

To use the MaOptionSet() and MaOptionGet() functions to retrieve or set the value of configuration options from your program, you must supply a string naming the option. The following constants, one for each option, are a convenience and will help isolate your code from changes to option names. The names of the constants are the same as the names of the options:

MA_BOUNDARY_POST
MA_BOUNDARY_PRE
...
MA_WARN_ZERO_BYTE
MA_WATCHPOINT_SAVE

The Memory Advisor Operating Mode

The _ma_operating_mode variable is set according to the mode in which Memory Advisor is running, so that you can make run-time determinations about which course of action to follow. The -mode command-line option to the memadvise command governs the Memory Advisor operating mode. The values are:

See Memory Advisor Operating Modes for a complete description of the Memory Advisor operating modes.

We have provided the following macros for your ease in determining the Memory Advisor operating mode. We recommend you use these macros rather than interrogating the _ma_operating_mode variable directly.

Each of the following macros returns a boolean value indicating whether Memory Advisor is operating in the named mode:

The following macro returns a boolean value indicating whether Memory Advisor is operating in the mode (MA_IS_XXX) that you supply as an argument:

int MA_MODE_CHECK(mode)
int mode;
For example:

if( MA_MODE_CHECK(MA_IS_MADBG_ONLY) == TRUE )

The MA_CHK_READ and MA_CHK_WRITE Constants

Use one of the following constants in calling the MaPtrCheckData() function to determine whether you have access to a given memory location:

The _ma_errno Variable

The functions in the API set the _ma_errno variable when they exit on an error condition. See the memadv.h file for a complete list and description of the error conditions, MA_ERR_*. The documentation for each function will list the appropriate values of _ma_errno that the function can set, if applicable.

Thread States

The _ma_is_threaded variable indicates whether Memory Advisor support for multithreaded programs is linked into the executing program. This variable may have one of the following values:

The Memory Advisor Error File Descriptor

You may use the special constant, MA_ERROR_FD, which represents the open file descriptor for the file that the MA_ERROR_FILE option names, in any of the API functions that require open file descriptors to cause output to go the error file. Examples of such functions are MaLeakShowNew() and MaOptionShowAll().

The Memory Advisor Historical IDs

Memory Advisor tracks the number of times certain events occur during execution of a program. It keeps an array of counters (unsigned long) that you can access for statistics about your program. The counters reside in the _ma_historical_ids[] array, and the following is a list of indices into the array:

realloc() free counter
MA_ID_MALLOC malloc() counter
MA_ID_REALLOC realloc() counter
MA_ID_CALLOC calloc() counter
MA_ID_XTMALLOC XtMalloc() counter
MA_ID_XTREALLOC XtRealloc() counter
MA_ID_XTCALLOC XtCalloc() counter
MA_ID_ALIGNED memalign() counter
MA_ID_NEW C++ new operator counter
MA_ID_GETOPT MaOptionGet() counter
MA_ID_SBRK sbrk() counter
MA_ID_STRDUP strdup() counter
MA_ID_HIST total allocation counter
MA_ID_INTERCEPT total intercept counter
MA_ID_USRALLOC user-defined memory allocator counter
MA_ID_FREE free() counter
MA_ID_CFREE cfree() counter
MA_ID_XTFREE XtFree() counter
MA_ID_REALLOC_FREE
MA_ID_XTREALLOC_FREE XtRealloc() free counter
MA_ID_DELETE C++ delete operator counter
MA_ID_USRFREE user free counter
An example of accessing this historical data is:

printf("Number of total allocations:\t%u\n",
	   _ma_historical_ids[MA_ID_HIST]);

Overriding Memory Advisor's Internal Allocator

Memory Advisor provides a variable, _ma_GetDataFunc(), that is a pointer to a function. Memory Advisor uses this function to allocate and free memory for its own use. To override the default function, you may set this variable to point to a function with the following profile:

void		*(*_ma_GetDataFunc)(int, long, void *);

where:

Integrating a User-Defined Memory Allocator

You use the following constants and type definitions in interacting with the Memory Advisor user-defined memory allocator API functions, MaUsrAlloc*(). Chapter 18, User-Defined Memory Allocators, discusses integrating user-defined memory allocators in detail.

The following are the access modes to which Memory Advisor sets memory. Although Memory Advisor generally handles setting access modes itself, you can set memory directly by calling MaPtrSetMode(), supplying one of the following modes:

MaUsrAllocSegRegister() can take the MA_UA_USE_DFLT_FROM_ARENA constant as the value for either or both the prebound or the postbound argument, indicating that the value for the argument should come from the default associated with the arena.

Additionally, MaUsrAllocSegFifoAdd() takes as a parameter a function pointer of type UAFreeFunc_t whose profile is:

void		(*UAFreeFunc_t)(void *, void *);

Miscellaneous Variables

Memory Advisor provides the following variables for your use:


Commonly Used Functions

This section describes some common scenarios in which you might want to use Memory Advisor API functions. In each case, we provide a list of relevant functions. For full details, see the discussion of that particular function.

Functions for Memory Leak Reports

This function prints a report of all leaks since your program began:

MaLeakShowAll()
This function prints a report of all leaks since the last leak report:

MaLeakShowNew()
This function clears the history of the last leak report, so that the next report lists all leaks:

MaLeakClearAll()
This function causes Memory Advisor to ignore all allocations prior to this function call when looking for leaks:

MaLeakBase()
This function prevents Memory Advisor from considering a memory segment as a leak:

MaLeakPtrNotALeak()

Functions for Other Reports

This function reports your program's memory allocations:

MaReportAllocations()
This function reports all file descriptors that are open at the time of this function call:

MaReportFdLeaks()

Functions for Controlling Memory Advisor

This function sets Memory Advisor configuration options:

MaOptionSet()
These functions retrieve the values of Memory Advisor configuration options:

MaOptionGet()
MaOptionShowAll()
This function provides a convenient place to have the debugger stop after Memory Advisor issues a message:

MaStop()
These functions start up and shut down Memory Advisor:

MaProcInitLibrary()
MaProcExit()

Functions for Memory Advisor Watchpoints

These functions add a Memory Advisor watchpoint:

MaWatchAdd()
MaWatchnRead()
MaWatchnReadWrite()
MaWatchnWrite()
These functions remove Memory Advisor watchpoints:

MaWatchRemoveAll()
MaWatchRemove()
This function causes Memory Advisor to check all of its watchpoints:

MaWatchCheckAll()
This function displays all active Memory Advisor watchpoints:

MaWatchShowAll()

Functions for Checking Data Access

These functions check access to your program's memory areas:

MaPtrCheckData()
MaPtrCheckString()
MaPtrCheckStringCh()
MaPtrCheckStringLen()
These functions print information about an allocated memory area:

MaPtrDataSize()
MaPtrInfo()

Functions for Getting Stack Trace Information

These functions get information about the current function's calling stack:

MaStackGetCaller()
MaStackGetCurrent()
These functions convert calling stack information into a printable string:

MaStackGet()
MaStackGetEntry()
These functions print calling stack information:

MaStackWriteToFile()
MaStackWriteToFd()

Macros for Implementing Discretionary Debugging

These macros compile debugging statements into your program, which you can activate as needed with Memory Advisor configuration options:

MADBG()
MADBG_CODE()
MADBG_LOC()
This macro provides multiple classes of debugging statements in your program:

MACL()
For a detailed discussion, see Chapter 17, Discretionary Debugging.

Functions for Integrating User-Defined Memory Allocators

These functions let you integrate your own allocator (referred to as a user-defined memory allocator) with Memory Advisor. The functions operate on two distinct data types: arenas and memory segments.

This function creates a new arena:

MaUsrAllocArenaNew()
This function deletes an arena and the record of segments allocated from that arena:

MaUsrAllocArenaDelete()
This function adds memory to an arena:

MaUsrAllocArenaExtend()
These functions register a segment from an arena with Memory Advisor:

MaUsrAllocSegRegister()
MaUsrAllocSegReg()
This function frees a segment and adds it to Memory Advisor's free queue:

MaUsrAllocSegFifoAdd()
This function sets the access mode of a segment:

MaPtrSetMode()
For a detailed discussion on integrating your own allocator with Memory Advisor, see Chapter 18, User-Defined Memory Allocators.


Function Descriptions

MaAllocChainCheck()

Description
The MaAllocChainCheck() function verifies that the allocation chain is intact and that your program has not corrupted it.

Syntax
The syntax for this function is:

#include <memadv.h>
int MaAllocChainCheck(todo)
int todo;
where the todo argument specifies the action Memory Advisor takes if it discovers an error. Valid values for todo are:

Depending on the value of the MA_FATAL_LEVEL option, this function may not return any information if it encounters a fatal error and you have set todo to 1.

In the following example, the program calls MaAllocChainCheck() to validate the current allocation chain and print an error message, if necessary. If the program encounters an error, it calls its own cleanup routine and exits.

if (MaAllocChainCheck(1)){
	do_cleanup();
	exit(1);
}

Returns
Memory Advisor returns a 0 (zero) if it does not find any errors. If it does find errors, it returns a nonzero value.

MaAllocChainList()

Description
The MaAllocChainList() function reports the memory segments currently in the allocation chain to the file you specify.

Syntax
The syntax for this function is:

#include <memadv.h>
void MaAllocChainList(fd, stackflg)
int fd;
int stackflg;
where:

In the following example, Memory Advisor opens a log file called memadvise.log and writes the allocation chain list to it.

int fd;

fd = open("memadvise.log", O_CREAT | O_TRUNC);
MaAllocChainList(fd,1);

An example of a report produced by MaAllocChainList() is:

****************** MemAdvise: Dump of Malloc Chain ******************

Data                                                    Which    Data
Address                     Location                    Call   Length
-------- --------------------------------------------- ------ ------

0x12D8D8 malloc()                                          2nd   1024
         calcfunc()      [calc.c:318]
         timesheet()     [calc.c:16]
         main()          [calc.c:216]

0x12E004 malloc()                                          3rd     24
         sum()           [math.c:831]
         timesheet()     [calc.c:16]
         main()          [calc.c:216]

Returns
This function does not return any information.

MaAllocFreeFifoFlush()

Description
The MaAllocFreeFifoFlush() function flushes the free FIFO queue so that space is available for new allocations.

Syntax
The syntax for this function is:

#include <memadv.h>
void MaAllocFreeFifoFlush()
An example of MaAllocFreeFifoFlush() is:

MaAllocFreeFifoFlush();

Returns
This function does not return any information.