11 #define POOL_SIZE 16777216
12 #define BLOCK_SIZE 512
14 #define NUM_BLOCKS (POOL_SIZE / BLOCK_SIZE)
15 #define BITMAP_SIZE (NUM_BLOCKS / 32)
17 static bool is_allocated(int block_number);
18 static int addr_to_block(unsigned char *addr);
19 static unsigned char *block_to_addr(int block_number);
20 static void alloc_blocks(int block_pos, int num_blocks);
21 static void free_blocks(int block_pos, int num_blocks);
23 static void print_stats();
25 static unsigned char *pool;
26 static std::map<int, int> alloc_sizes; //starting block -> number of blocks
28 // 0 means not allocated 1 means allocated
29 static uint32_t bitmap[BITMAP_SIZE];
38 static Statistics stats;
40 bool init_shared_memory()
42 if(!(pool = (unsigned char *)malloc(POOL_SIZE))) {
46 for(int i=0; i<BITMAP_SIZE; i++) {
51 memset(&stats, 0, sizeof stats);
56 void destroy_shared_memory()
62 void *sh_malloc(size_t bytes)
68 int num_blocks = (bytes + BLOCK_SIZE - 1) / BLOCK_SIZE;
72 for(int i=0; i<NUM_BLOCKS; i++) {
73 if(!is_allocated(i)) {
83 if(ctr == num_blocks) {
84 alloc_blocks(free_block, num_blocks);
85 return block_to_addr(free_block);
92 void sh_free(void *ptr)
94 int block = addr_to_block((unsigned char*)ptr);
95 std::map<int, int>::iterator it;
96 if((it = alloc_sizes.find(block)) != alloc_sizes.end()) {
97 int num_blocks = it->second;
98 free_blocks(block, num_blocks);
99 alloc_sizes.erase(it);
102 fprintf(stderr, "Attempt to free non-existent blocks from: %d\n", block);
106 static bool is_allocated(int block_number)
108 int idx = block_number / 32;
109 int bit_num = block_number % 32;
111 if((bitmap[idx] >> bit_num) & 1) {
118 static int addr_to_block(unsigned char *addr)
120 assert(addr >= pool);
121 assert(addr < pool + POOL_SIZE);
123 return (addr - pool) / BLOCK_SIZE;
126 static unsigned char *block_to_addr(int block_number)
128 assert(block_number >= 0);
129 assert(block_number < NUM_BLOCKS);
131 return pool + block_number * BLOCK_SIZE;
134 static void alloc_blocks(int block_pos, int num_blocks)
136 for(int i=0; i<num_blocks; i++) {
137 int block_number = i + block_pos;
138 int idx = block_number / 32;
139 int bit_num = block_number % 32;
141 bitmap[idx] |= ((uint32_t)1 << bit_num); // or pow(2, i)
144 alloc_sizes[block_pos] = num_blocks;
147 stats.alloc_memsize += BLOCK_SIZE * num_blocks;
150 static void free_blocks(int block_pos, int num_blocks)
152 for(int i=0; i<num_blocks; i++) {
153 int block_number = i + block_pos;
154 int idx = block_number / 32;
155 int bit_num = block_number % 32;
157 bitmap[idx] &= ~((uint32_t)1 << bit_num);
161 stats.free_memsize += BLOCK_SIZE * num_blocks;
164 static void print_stats()
166 printf("Total allocated memory: %d\n", stats.alloc_memsize);
167 printf("Total deallocated memory: %d\n", stats.free_memsize);
168 printf("Number of allocations: %d\n", stats.alloc_num);
169 printf("Number of deallocations: %d\n", stats.free_num);