source: to-imperative/trunk/runtime/pxx_heap.cc @ 287

Last change on this file since 287 was 287, checked in by orlov, 18 years ago

* empty log message *

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 2.0 KB
Line 
1// $Source$
2// $Revision: 287 $
3// $Date: 2002-12-18 23:53:37 +0000 (Wed, 18 Dec 2002) $
4
5#include "pxx_heap.hh"
6
7#include <sys/mman.h>
8#include <errno.h>
9
10namespace pxx
11{
12
13Heap::Heap (
14  void* const _start,
15  size_t const _max_size,
16  size_t _init_size /* = page_size */,
17  int _fd /* = 0 */,
18  bool _need_remap /* = true */
19) :
20  start (_start),
21  max_size (_max_size),
22  max_order (get_order(_max_size)),
23  current_size (_init_size),
24  current_order (get_order(_init_size)),
25  fd (_fd),
26  need_remap (_need_remap)
27{
28  if (rounds[max_order] != max_size)
29    FATAL("heap size is not a power of 2");
30  if (!aligned(_start, page_size))
31    FATAL("Heap start address is bad aligned");
32  if (current_size > max_size)
33    FATAL("Initial heap size greater than maximal size");
34  if (need_remap) {
35    void* res = mmap(
36      start, current_size,
37      PROT_READ | PROT_WRITE,
38      (fd == 0 ? MAP_PRIVATE | MAP_ANON : MAP_SHARED) | MAP_FIXED,
39      fd, 0
40    );
41    if (res == MAP_FAILED) {
42      FATAL("mmap() failed, errno = %d", errno);
43    }
44  }
45  if (fd) {
46    int res = ftruncate(fd, current_size);
47    if (res)
48      FATAL("ftruncate() failed, errno = %d", errno);
49  }
50}
51
52Heap::~Heap ()
53{
54  if (need_remap) {
55    int res = munmap(start, current_size);
56    if (res)
57      FATAL("munmap() failed, errno = %d", errno);
58  }
59}
60
61void Heap::expand (unsigned _order /* = 1 */)
62{
63  size_t new_size = current_size << _order;
64  if ((new_size > max_size) || (new_size == 0))
65    FATAL("Heap exhausted");
66  if (need_remap) {
67    void* res = mmap(
68      ptr_add(start, current_size),
69      new_size - current_size,
70      PROT_READ | PROT_WRITE,
71      (fd == 0 ? MAP_PRIVATE | MAP_ANON : MAP_SHARED) | MAP_FIXED,
72      fd, 0
73    );
74    if (res == MAP_FAILED) {
75      FATAL("mmap() failed, errno = %d", errno);
76    }
77    if (res != ptr_add(start, current_size))
78      FATAL("mmap() changed a heap start address");
79  }
80  current_order += _order;
81  current_size = new_size;
82  if (fd) {
83    int res = ftruncate(fd, current_size);
84    if (res)
85      FATAL("ftruncate() failed, errno = %d", errno);
86  }
87}
88
89}
Note: See TracBrowser for help on using the repository browser.