VMALLOC(3)
π VMALLOC(3) π β from the Library Functions Manual, bestie π«Ά
β¨ NAME β¨
vmalloc β virtual memory allocation. That's the name, and honestly it's giving main-character memory energy π
.
π SYNOPSIS π
#include <vmalloc.h>
π Regions π
Vmalloc_t* vmopen(Vmdisc_t* disc, Vmethod_t* meth, int flags);
int vmclose(Vmalloc_t*);
int vmclear(Vmalloc_t*);
int vmcompact(Vmalloc_t* region);
int vmset(Vmalloc_t* region, int flags, int type);
Vmalloc_t* Vmheap;
Vmdisc_t* vmdisc(Vmalloc_t* region, Vmdisc_t* disc);
Vmalloc_t* vmmopen(char* file, int project, ssize_t size);
Void_t* vmmvalue(Vmalloc_t* vm, int key, Void_t* value, int op);
Void_t* vmmcleanup(Vmalloc_t* vm);
Void_t* vmmaddress(size_t size);
πΈ Allocation functions πΈ
Void_t* vmalloc(Vmalloc_t* region, size_t size);
Void_t* vmalign(Vmalloc_t* region, size_t size, size_t align);
Void_t* vmresize(Vmalloc_t* region, Void_t* addr, size_t size, int type);
int vmfree(Vmalloc_t* region, Void_t* addr);
Void_t* vmnewof(Vmalloc_t* region, Void_t* addr, type, size_t n, size_t x);
Void_t* vmoldof(Vmalloc_t* region, Void_t* addr, type, size_t n, size_t x);
Void_t* vmgetmem(Vmalloc_t* region, Void_t* addr, size_t size);
π¦ Debugging π¦
int vmdebug(int);
int vmdbcheck(Vmalloc_t* vm);
int vmdbwatch(Void_t* addr);
static void vmdbwarn(Vmalloc_t*, char* mesg, int n);
β Profiling β
void vmprofile(Vmalloc_t* vm, int fd);
π₯ Information and statistics π₯
int vmbusy(Vmalloc_t* region);
Vmalloc_t* vmregion(Void_t* addr);
Void_t* vmsegment(Vmalloc_t* region, Void_t* addr);
int vmwalk(Vmalloc_t* region, int(*walkf)(Vmalloc_t*, Void_t*, size_t, Vmdisc_t*);
long vmaddr(Vmalloc_t* region, Void_t* addr);
long vmsize(Vmalloc_t* region, Void_t* addr);
int vmstat(Vmalloc_t* vm, Vmstat_t* statb);
int vmtrace(int fd);
int vmtrbusy(Vmalloc_t* vm);
Void_t* vmdata(Vmalloc_t* vm);
π Malloc-compatible functions π
Void_t* malloc(size_t size);
Void_t* realloc(Void_t* addr, size_t size);
Void_t* calloc(size_t n_obj, size_t s_obj);
int cfree(Void_t* addr);
void free(Void_t* addr);
Void_t* memalign(size_t align, size_t size);
Void_t* valloc(size_t size);
int setregmax(int regmax);
π DESCRIPTION π
Okay so these functions for dynamic storage allocation work in regions of memory. Each region has an allocation method for parceling out blocks of storage and a memory discipline for obtaining raw space. Automatic locking prevents interference by reentrant access to a region.
Pointers to space have type Void_t* where Void_t is #defined as void if possible, otherwise char. Space is counted in type size_t. That's the setup, and it's lowkey iconic β¨.
π Regions π
Regions have type Vmalloc_t. Two predefined regions are pointed to by:
Vmheapβ a general-purpose region, with best-fit allocation, and system memory disciplineVmdcsystem.
These functions manipulate regions:
vmopenβ creates a region with memory disciplinedisc, allocation methodmeth, and a setting for control flags. It returns a pointer to the region on success andNULLon failure. The flags, represented by bit values or-ed together, are:VM_SHAREβ this region may be accessed concurrently by multiple threads or processes.VM_TRACEβ place tracing messages for each allocation event on the tracing file established byvmtrace.VM_DBCHECK,VM_DBABORTβ see Debugging below.
vmcloseβ closes a region and releases all associated memory according to the region's discipline. The first segment obtained from the discipline'smemoryffunction (seeDisciplinesbelow) will be the last released.vmclosereturns-1on failure and a non-negative value otherwise.vmclearβ frees all allocated blocks inregionregardless of methods. It returns-1on failure and a non-negative value otherwise.vmcompactβ releases as much of a region's free space to its discipline'smemoryffunction as possible. It returns a nonnegative value on success and-1on failure.vmsetβ adjusts and queries a region's flags. The indicated flags are turned on iftypeis nonzero, off if zero.vmsetreturns the previous value of all flags. Thus,vmset(region,0,0)queries the flags without changing them. In addition to the settable flags, one ofVM_MTBEST,VM_MTDEBUG,VM_MTPROFILE,VM_MTPOOL, orVM_MTLASTis returned to indicate the method used in creating the region.vmdiscβ changes the discipline ofregionto the given new disciplinediscifdiscis notNULLand itsmemoryffunction is the same as the current discipline. If the current discipline has anexceptffunction, it will be called with eventVM_DISC. This function always returns the current discipline.vmmopenβ creates a region to allocate memory obtained via eithermmap(2)whenproject < 0orshmget(2)whenproject >= 0. The region is built from a single memory segment guaranteed to be at least as large assize. Whenproject >= 0,fileandprojectare used in a call toftok(3)to get a key suitable for getting a shared memory segment viashmget(2). Otherwise,fileis the backing store for the mapped data. In this case, not only the region may be used concurrently by different processes, it is also persistent. That is, process could even exit, move the file to a different but similar machine then restart and open the same region to continue working.
Note that Vmalloc can protect concurrent accesses only on region entry and exit for memory allocation operations. This means that at the time when regions are being opened or closed, there will be no protection for the memory segments being attached into or detached from process memory space. This limitation has a special impact on vmmopen() as follows.
A shared memory segment opened via vmmopen() corresponds uniquely to a combination of the file and project parameters. Thus, if multiple vmmopen() calls are done in the same process using a same combination of file and project, the joined behavior of such regions will be unpredictable when opening and closing are done concurrently with other memory allocation operations. Beware that this effect can be subtle with library functions that may attempt to create their own memory allocation regions.
vmmvalueβ manages pairs of key and value in a region opened viavmopen(). IfopisVM_MMGET, the value associated withkeyis returned. IfopisVM_MMSET, the value associated withkeywill be set tovalue. IfopisVM_MMADD, the value associated withkeywill be treated as a signed long value to whichval(also treated as a signed long value) will be added. The call always returns the updated data value associated withkey.vmmcleanupβ setsregionup to remove backing store orshmidon closing.vmmaddressβ computes an address suitable for attaching a shared memory segment or memory mapping a segment of file data of the givensize. The address is chosen with hope to minimize collision with other activities related to memory such as growth of stack space or space used for dynamically linked libraries, etc.
π§ Allocation functions π§
vmallocβ returns a pointer to a block of the requestedsizein aregion, aligned to the strictest alignment that is suitable for the needs of any basic data type. It returnsNULLon failure.vmalignβ works likevmalloc, but returns a block aligned to a common multiple ofalignand the strictest alignment.vmresizeβ attempts to change the length of the block pointed to byaddrto the specifiedsize. If that is impossible andtypehas at least one ofVM_RSMOVEandVM_RSCOPY, a new block is allocated and the old block is freed. The bitVM_RSCOPYalso causes the new block to be initialized with as much of the old contents as will fit. When a resized block gets larger, the new space will be cleared iftypehas the bitVM_RSZERO.vmresizereturns a pointer to the final block, orNULLon failure. IfaddrisNULL,vmresizebehaves likevmalloc; otherwise, ifsizeis0, it behaves likevmfree.vmfreeβ makes the currently allocated block pointed to byaddravailable for future allocations in itsregion. IfaddrisNULL,vmfreedoes nothing. It returns-1on error, and nonnegative otherwise.vmnewofβ is a macro function that attempts to change the length of the block pointed to byaddrto the sizen*sizeof(type)+x. If the block is moved, new space will be initialized with as much of the old content as will fit. Additional space will be set to zero.vmoldofβ is similar tovmnewofbut it neither copies data nor clears space.vmgetmemβ provides a handy function to creat/close regions and allocate/free memory based on chunks of memory obtained from the heap regionVmheap.vmgetmem(0,0,0)β this call opens a new region.vmgetmem(region, 0, 0)β this call closes the given region.vmgetmem(region,0,n)β this call allocates a block of lengthnand clears it to zeros.vmgetmem(region,p,0)β this call frees the blockp.vmgetmem(region,p,n)β this call resizes the blockpto lengthnand clears the new memory to zeros if the block grows. The block may be moved as deemed necessary by the allocator.
π¦ Memory disciplines π¦
Memory disciplines have type Vmdisc_t, a structure with these members:
Void_t* (*memoryf)(Vmalloc_t *region, Void_t* obj,
size_t csz, size_t nsz, Vmdisc_t *disc);
int (*exceptf)(Vmalloc_t *region, int type, Void_t* obj, Vmdisc_t *disc);
int round;
roundβ if this value is positive, all size arguments to thememoryffunction will be multiples of it.memoryfβ points to a function to get or release segments of space for the region.exceptfβ if this pointer is notNULL, the function it points to is called to announce events in a region.
There are two standard disciplines, both with round being 0 and exceptf being NULL.
Vmdcsystemβ a discipline whosememoryffunction gets space from the operation system via different available methods which includemmap(2),sbrk(2)and functions from the WIN32 API. For historical reason,Vmdcsbrkis also available and functions likeVmdcsystem.Vmdcheapβ a discipline whosememoryffunction gets space from the regionVmheap. A region withVmdcheapdiscipline andVmlastallocation is good for building throwaway data structures.
A memoryf function returns a pointer to a memory segment on success, and NULL on failure. When nsz >= 0 and csz > 0, the function first attempts to change the current segment addr to fit nsz (for example, nsz == 0 means deleting the segment addr). If this attempt is successful, it should return addr. Otherwise, if nsz > csz, the function may try to allocate a new segment of size nsz-csz. If successful, it should return the address of the new segment. In all other cases, it should return NULL.
Okay so, the exceptf function is called for events identified by type, and the coding is literally this:
VM_OPENβ this event is raised at the start of the process to open a new region. Argumentobjwill be a pointer to an object of typeVoid_t*initialized toNULLbefore the call. The return value ofexceptfis significant as follows:- On a negative return value,
vmopenwill terminate with failure. - On a zero return value,
exceptfmay set*((Void_t**)obj)to some non-NULLvalue to tellvmopento allocate the region handle itself viamemoryf. Otherwise, the region handle will be allocated from theVmheapregion. - On a positive return value, the new region is being reconstructed based on existing states of some previous region. In this case,
exceptfshould set*(Void_t**)objto point to the fieldVmalloc_t.dataof the corresponding previous region (seeVM_CLOSEbelow). If the handle of the previous region was allocated viamemoryfas discussed above in the case of the zero return value, then it will be exactly restored. Otherwise, a new handle will be allocated fromVmheap. The ability to create regions sharing the same states allows for managing shared and/or persistent memory.
- On a negative return value,
VM_ENDOPENβ this event is raised at the end of the process to open a new region. The return value ofexceptfwill be ignored.VM_CLOSEβ this event is raised at the start of the process to close a region. The return value ofexceptfis significant as follows:- On a negative return value,
vmcloseimmediately returns with failure. - On a zero return value,
vmcloseproceeds normally by callingmemoryfto free all allocated memory segments and also freeing the region itself. - On a positive return value,
vmclosewill only free the region without deallocating the associated memory segments. That is, the fieldVmalloc_t.dataof the region handle remains intact. This is useful for managing shared and/or persistent memory (seeVM_OPENabove).
- On a negative return value,
VM_ENDCLOSEβ this event is raised at the end of the process to close a region. The return value ofexceptfwill be ignored.VM_NOMEMβ an attempt to extend the region by the amount(size_t)objfailed. The region is unlocked, so theexceptffunction may free blocks. If the function returns a positive value the memory request will be repeated.VM_DISCβ the discipline structure is being changed.
πΈ ALLOCATION METHODS πΈ
Methods are of type Vmethod_t*.
Vmbestβ an approximately best-fit allocation strategy.Vmlastβ a strategy for building structures that are only deleted in whole. Only the latest allocated block can be freed. This means that as soon as a blockais allocated,vmfreecalls on blocks other than
bestie, that Vmlast sentence really does stop right there β no cap, Iβm not hiding the rest from you π
Vmpoolβ a strategy for blocks of one size, set by the firstvmalloccall aftervmopenorvmclear.Vmdebugβ an allocation strategy with extra-stringent checking and locking. It is useful for finding misuses of dynamically allocated memory, such as writing beyond the boundary of a block, or freeing a block twice.Vmprofileβ an allocation method that records and prints summaries of memory usage.
π DEBUGGING π
The method Vmdebug is used to debug common memory violation problems. When a problem is found, a warning message is written to file descriptor 2 (standard error). In addition, if flag VM_DBABORT is on, the program is terminated by calling abort(2). Each message is a line of self-explanatory fields separated by colons. The optional flag -DVMFL, if used during compilation, enables recording of file names and line numbers. The following functions work with method Vmdebug.
vmdebugβ resets the file descriptor to write out warnings to the given argument. By default, this file descriptor is 2, the standard error.vmdebugreturns the previous file descriptor.vmdbcheckβ checks a region usingVmdebugorVmbestfor integrity. IfVmdebug, this also checks for block overwriting errors. On errors,vmdbwarnis called. If flagVM_DBCHECKis on,vmdbcheckis called at each invocation ofvmalloc,vmfree, orvmresize.vmdbwatchβ causes addressaddrto be watched, and reported whenever met invmalloc,vmresizeorvmfree. The watch list has finite size and if it becomes full, watches will be removed in a first-in-first-out fashion. IfaddrisNULL, all current watches are canceled.vmdbwatchreturns the watch bumped out due to an insertion into a full list orNULLotherwise.vmdbwarnβ is an internal function that processes warning messages for discovered errors. It canβt be called from outside thevmallocpackage, but is a good place to plant debugger traps because control goes there at every trouble.
π PROFILING π
The method Vmprofile is used to profile memory usage. Profiling data are maintained in private memory of a process so Vmprofile should be avoided from regions manipulating persistent or shared memory. The optional flag -DVMFL, if used during compilation, enables recording of file names and line numbers.
vmprofile prints memory usage summary. The summary is restricted to region vm if vm is not NULL; otherwise, it is for all regions created with Vmprofile. Summary records are written to file descriptor fd as lines with colon-separated fields. Here are some of the fields:
n_alloc,n_free: number of allocation and free calls respectively. Note that a resize operation is coded as a free and an allocation.s_alloc,s_free: total amounts allocated and freed. The difference between these numbers is the amount of space not yet freed.max_busy,extent: these fields are only with the summary record for region. They show the maximum busy space at any time and the extent of the region.
π INFORMATION AND STATISTICS π
vmbusyβ returns the busy status of a region. A region is busy if some allocation operation is accessing it.vmregionβ returns the region to which the block pointed to byaddrbelongs. This works only in regions that allocate withVmbest,VmdebugorVmprofile.vmsegmentβ finds if some segment of memory in region contains the addressaddr. It returns the address of a found segment orNULLif none found.vmwalkβ walks all segments in region or if region isNULL, all segments in all regions. At each segment,(*walkf)(vm,addr,size,disc)is called wherevmis the region,addris the segment,sizeis the size of the segment, anddiscis the regionβs discipline. Ifwalkfreturns a negative value, the walk stops and returns the same value. On success,vmwalkreturns 0; otherwise, it returns -1.vmaddrβ checks whetheraddrpoints to an address within some allocated block of the given region. If not, it returns -1. If so, it returns the offset from the beginning of the block. The function does not work for aVmlastregion except on the latest allocated block.vmsizeβ returns the size of the allocated block pointed to byaddr. It returns -1 ifaddrdoes not point to a valid block in the region. Sizes may be padded beyond that requested; in particular no block has size 0. The function does not work for aVmlastregion except on the latest allocated block.vmstatβ gathers statistics on the given region. If region isNULL, it computes statistics for theMalloccalls. This may include summing statistics from more than one regions constructed to avoid blocking due to parallel or asynchronous operations. Ifstatbis notNULL,vmstatcomputes and stores the statistics instatbthen returns 0. IfstatbisNULL, no statistics will be computed and the returned value is either 1 if the region is busy, i.e., being accessed by some allocation call or 0 otherwise.
A Vmstat_t structure has at least these members:
int n_busy; /* # of busy blocks */
int n_free; /* # of free blocks */
size_t s_busy; /* total busy space */
size_t s_free; /* total free space */
size_t m_busy; /* maximum busy block size */
size_t m_free; /* maximum free block size */
int n_seg; /* count of segments */
size_t extent; /* memory extent of region */
int n_region; /* total Malloc regions */
int n_open; /* non-blocked operations */
int n_lock; /* blocked operations */
int n_probe; /* region searches */
Bookkeeping overhead is counted in extent, but not in s_busy or s_free.
vmtrace establishes file descriptor fd as the trace file and returns the previous value of the trace file descriptor. The trace descriptor is initially invalid. Output is sent to the trace file by successful allocation events when flag VM_TRACE is on.
Tools for analyzing traces are described in mtreplay(1). The trace record for an allocation event is a line with colon-separated fields, four numbers and one string.
oldβ zero for a fresh allocation; the address argument for freeing and resizing.newβ zero for freeing; the address returned by allocation or resizing.sizeβ the size argument for allocation or resizing; the size freed by freeing. Sizes may differ due to padding for alignment.regionβ the address of the affected region.methodβ a string that tells the regionβs method:best,last,pool,profile, ordebug.
vmtrbusy outputs a trace of all currently busy blocks in region vm. This only works with the Vmbest, Vmdebug and Vmprofile methods.
vmdata returns the core data of the given region. The core data hold the data structures for allocated and free blocks. Depending on the region discipline, the core data of a region may be in shared or persistent memory even if the region pointer created with vmopen is always in private process memory.
ποΈ MALLOC-COMPATIBLE FUNCTIONS ποΈ
This set of functions implement malloc(3). They allocate via the Vmregion region which is initially set to be Vmheap.
Concurrent accesses are supported unless an application change Vmregion to something other than Vmheap. New regions may be created on the fly to avoid blocking. The maximum number of regions that can be created this way is set to 64 by default. An application could reduce this number by calling setregmax(regmax) to set the maximum number of these extra regions to regmax. setregmax() always returns the previous value.
These functions are instrumented for run-time debugging, profiling and tracing β it's giving built-in detective mode πβ¨. For accurate reporting of files and line numbers, application code should include vmalloc.h and compile with -DVMFL. The VMALLOC_OPTIONS environment variable is checked once before the first memory allocation and controls the memory allocation method, debugging and tracing; its value is a comma or space separated list of [no]name[=value] options. The options are:
abortβ ifVmregion==VmdebugthenVM_DBABORTis set; otherwise_BLD_DEBUGenabled assertionsabort()on failure. πbreakβ trysbrk()block allocator first.checkβ ifVmregion==Vmbestthen the region is checked every op. πfreeβ disableaddfreelist().keepβ disable free β if code works with this enabled then it probably accesses freed data. bestie, that's a red flag π©method=methodβ setsVmregion=methodif not defined; method (Vm prefix optional) may be one of{ best debug last profile }.mmapβ trymmap()block allocator first ifbreakis not set.period=nβ setsVmregion=Vmdebugif not defined; ifVmregion==Vmdebugthe region is checked every n ops.profile=fileβ setsVmregion=Vmprofileif not set; ifVmregion==Vmprofilethen profile info printed to file file.start=nβ setsVmregion=Vmdebugif not defined; ifVmregion==Vmdebugregion checking starts after n ops.trace=fileβ enables tracing to file file.warn=fileβ setsVmregion=Vmdebugif not defined; ifVmregion==Vmdebugthen warnings printed to file file.watch=addressβ setsVmregion=Vmdebugif not defined; ifVmregion==Vmdebugthen address is watched.
Output files are created if they don't exist. &n and /dev/fd/n name the file descriptor n which must be open for writing. The pattern %p in a file name is replaced by the process ID. π«Ά
VMALLOC_OPTIONS combines the features of these obsolete environment variables: { VMCHECK VMDEBUG VMETHOD VMPROFILE VMTRACE }. the oldies but goodies π§πΎ
π¦ RECENT CHANGES π¦
Vmlast: allocated blocks are now allowed to be resized (09/1998). slay, resizing rights β
π SEE ALSO π
mtreplay(1)malloc(3)
πΈ AUTHOR πΈ
Kiem-Phong Vo, kpv@research.att.com π
Okay that's the whole page, bestie π β source/version VMALLOC(3), dated 1 May 1998, signing off β¨π
π¦ where this page comes from
- opensuse-leap 16.0: ksh-devel 93vu-bp160.1.33 Β· CPL-1.0
- opensuse-leap 16.0: ksh-devel 93vu-bp160.1.33 Β· CPL-1.0
- opensuse-leap 16.0: ksh-devel 93vu-bp160.1.33 Β· CPL-1.0
- opensuse-leap 16.0: ksh-devel 93vu-bp160.1.33 Β· CPL-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms