L4Re - L4 Runtime Environment
examples/libs/l4re/c++/mem_alloc/ma+rm.cc

Coarse grained memory allocation, in C++.

/*
* (c) 2009 Adam Lackorzynski <adam@os.inf.tu-dresden.de>
* economic rights: Technische Universit├Ąt Dresden (Germany)
*
* This file is part of TUD:OS and distributed under the terms of the
* GNU General Public License 2.
* Please see the COPYING-GPL-2 file for details.
*/
#include <l4/re/mem_alloc>
#include <l4/re/rm>
#include <l4/re/env>
#include <l4/re/dataspace>
#include <l4/sys/err.h>
#include <cstdio>
#include <cstring>
static int allocate_mem(unsigned long size_in_bytes, unsigned long flags,
void **virt_addr)
{
int r;
/* Allocate a free capability index for our data space */
if (!d.is_valid())
return -L4_ENOMEM;
size_in_bytes = l4_trunc_page(size_in_bytes);
/* Allocate memory via a dataspace */
if ((r = L4Re::Env::env()->mem_alloc()->alloc(size_in_bytes, d, flags)))
return r;
/* Make the dataspace visible in our address space */
*virt_addr = 0;
if ((r = L4Re::Env::env()->rm()->attach(virt_addr, size_in_bytes,
return r;
/* Done, virtual address is in virt_addr */
return 0;
}
static int free_mem(void *virt_addr)
{
int r;
/* Detach memory from our address space */
if ((r = L4Re::Env::env()->rm()->detach(virt_addr, &ds)))
return r;
/* Release and return capability slot to allocator */
/* All went ok */
return 0;
}
int main(void)
{
void *virt;
/* Allocate memory: 16k Bytes (usually) */
if (allocate_mem(4 * L4_PAGESIZE, 0, &virt))
return 1;
printf("Allocated memory.\n");
/* Do something with the memory */
memset(virt, 0x12, 4 * L4_PAGESIZE);
printf("Touched memory.\n");
/* Free memory */
if (free_mem(virt))
return 2;
printf("Freed and done. Bye.\n");
return 0;
}