summaryrefslogtreecommitdiff
path: root/src/lib/eina/eina_safepointer.c
blob: 9016aab27a58cf5027baf61728d154facf9eff6a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#ifdef HAVE_VALGRIND
# include <valgrind.h>
# include <memcheck.h>
#endif

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <inttypes.h>

#ifdef _WIN32
# include <evil_private.h> /* mmap */
#else
# include <sys/mman.h>
#endif

#include "eina_config.h"
#include "eina_private.h"

#define _EINA_INTERNAL_SAFEPOINTER
#include "eina_safepointer.h"
#include "eina_mempool.h"
#include "eina_trash.h"
#include "eina_log.h"
#include "eina_lock.h"

typedef struct _Eina_Memory_Header Eina_Memory_Header;

#ifdef ERR
#undef ERR
#endif
#define ERR(...) EINA_LOG_DOM_ERR(_eina_sp_log_dom, __VA_ARGS__)

#ifdef DBG
#undef DBG
#endif
#define DBG(...) EINA_LOG_DOM_DBG(_eina_sp_log_dom, __VA_ARGS__)

/* Macro used to compose an Eo id */
#define SP_COMPOSE_PARTIAL_ID(MID_TABLE, TABLE)                         \
  ( \
    ((Eina_Sp_Id)(MID_TABLE & EINA_MASK_MID_TABLE_ID) << EINA_SHIFT_MID_TABLE_ID)   |  \
    ((Eina_Sp_Id)(TABLE & EINA_MASK_TABLE_ID) << EINA_SHIFT_TABLE_ID) \
    )

#define SP_COMPOSE_FINAL_ID(PARTIAL_ID, ENTRY, GENERATION)     \
    (PARTIAL_ID                                             |  \
     ((ENTRY & EINA_MASK_ENTRY_ID) << EINA_SHIFT_ENTRY_ID)            |  \
     ((GENERATION & EINA_MASK_GENERATIONS) << EINA_SHIFT_GENERATION))

struct _Eina_Memory_Header
{
   EINA_MAGIC;
   size_t size;
};

EAPI Eina_Memory_Table **_eina_sp_ids_tables[EINA_MAX_MID_TABLE_ID] = { NULL };
EAPI int _eina_sp_log_dom = -1;

/* Spare empty table */
static Eina_Memory_Table *empty_table = NULL;

// We are using a Spinlock even with the amount of syscall we do as it shouldn't
// take that long anyway.
static Eina_Spinlock sl;

#define MEM_PAGE_SIZE 4096
#define SAFEPOINTER_MAGIC 0x7DEADC03

static void *
_eina_safepointer_calloc(int number, size_t size)
{
#ifdef HAVE_MMAP
# ifdef HAVE_VALGRIND
   if (RUNNING_ON_VALGRIND) return calloc(number, size);
   else
# endif
     {
        Eina_Memory_Header *header;
        size_t newsize;

        size = size * number + sizeof (Eina_Memory_Header);
        newsize = ((size / MEM_PAGE_SIZE) +
                   (size % MEM_PAGE_SIZE ? 1 : 0))
          * MEM_PAGE_SIZE;

        header = mmap(NULL, newsize, PROT_READ | PROT_WRITE,
                      MAP_PRIVATE | MAP_ANON, -1, 0);
        if (header == MAP_FAILED)
          {
             ERR("mmap of Eina_Safepointer table region failed.");
             return NULL;
          }

        header->size = newsize;
        EINA_MAGIC_SET(header, SAFEPOINTER_MAGIC);

        return (void *)(header + 1);
     }
#else
   return calloc(number, size);
#endif
}

static void
_eina_safepointer_free(void *pointer)
{
#ifdef HAVE_MMAP
# ifdef HAVE_VALGRIND
   if (RUNNING_ON_VALGRIND) free((void *)((uintptr_t) pointer & ~0x3));
   else
# endif
     {
        Eina_Memory_Header *header;

        if (!pointer) return;

        header = (Eina_Memory_Header*)(pointer) - 1;
        if (!EINA_MAGIC_CHECK(header, SAFEPOINTER_MAGIC))
          EINA_MAGIC_FAIL(header, SAFEPOINTER_MAGIC);

        EINA_MAGIC_SET(header, 0);
        munmap(header, header->size);
     }
#else
   free((void *)((uintptr_t) pointer & ~0x3));
#endif
}

#ifdef EINA_DEBUG_MALLOC
static void
_eina_safepointer_protect(void *pointer, Eina_Bool may_not_write)
{
#ifdef HAVE_MMAP
# ifdef HAVE_VALGRIND
   if (RUNNING_ON_VALGRIND) { (void) pointer; }
   else
# endif
     {
        Eina_Memory_Header *header;

        if (!pointer) return;

        header = (Eina_Memory_Header*)(pointer) - 1;
        if (!EINA_MAGIC_CHECK(header, SAFEPOINTER_MAGIC))
          EINA_MAGIC_FAIL(header, SAFEPOINTER_MAGIC);

        mprotect(header, header->size, PROT_READ | ( may_not_write ? 0 : PROT_WRITE));
     }
#else
   (void) pointer;
#endif
}

#define   PROTECT(Ptr) _eina_safepointer_protect(Ptr, EINA_TRUE)
#define UNPROTECT(Ptr) _eina_safepointer_protect(Ptr, EINA_FALSE)

#else

#define   PROTECT(Ptr)
#define UNPROTECT(Ptr)

#endif

static Eina_Memory_Table *
_eina_safepointer_table_new(Eina_Table_Index mid_table_id,
                            Eina_Table_Index table_id)
{
   Eina_Memory_Table *table;

   if (empty_table)
     {
        /* Recycle the available empty table */
        table = empty_table;
        empty_table = NULL;
        UNPROTECT(table);
     }
   else
     {
        table = _eina_safepointer_calloc(1, sizeof (Eina_Memory_Table));
        if (!table)
          {
             ERR("Failed to allocate leaf table at [%i][%i]", mid_table_id, table_id);
             return NULL;
          }
     }

   table->partial_id = SP_COMPOSE_PARTIAL_ID(mid_table_id,
                                             table_id);
   PROTECT(table);
   UNPROTECT(_eina_sp_ids_tables[mid_table_id]);
   _eina_sp_ids_tables[mid_table_id][table_id] = table;
   PROTECT(_eina_sp_ids_tables[mid_table_id]);

   return table;
}

static Eina_Memory_Table *
_eina_safepointer_table_find(void)
{
   Eina_Table_Index mid_table_id;

   for (mid_table_id = 0; mid_table_id < EINA_MAX_MID_TABLE_ID; mid_table_id++)
     {
        Eina_Table_Index table_id;

        if (!_eina_sp_ids_tables[mid_table_id])
          {
             _eina_sp_ids_tables[mid_table_id] = _eina_safepointer_calloc(EINA_MAX_TABLE_ID, sizeof (Eina_Memory_Table*));
          }
        if (!_eina_sp_ids_tables[mid_table_id])
          {
             ERR("Failed to allocate mid table at [%i]", mid_table_id);
             return NULL;
          }

        for (table_id = 0; table_id < EINA_MAX_TABLE_ID; table_id++)
          {
             Eina_Memory_Table *table;

             table = _eina_sp_ids_tables[mid_table_id][table_id];

             if (!table)
               table = _eina_safepointer_table_new(mid_table_id, table_id);

             if (!table) return NULL;

             if (table->trash ||
                 table->start < EINA_MAX_ENTRY_ID)
               return table;
          }
     }

   return NULL;
}

static Eina_Memory_Entry *
_eina_safepointer_entry_find(Eina_Memory_Table *table)
{
   Eina_Memory_Entry *entry = NULL;

   if (table->trash)
     {
        entry = eina_trash_pop(&table->trash);
     }
   else if (table->start < EINA_MAX_ENTRY_ID)
     {
        entry = &(table->entries[table->start]);
        table->start++;
     }
   else
     {
        ERR("Impossible to find an entry in %" PRIxPTR ".", table->partial_id);
     }

   return entry;
}

EAPI const Eina_Safepointer *
eina_safepointer_register(const void *target)
{
   Eina_Memory_Table *table;
   Eina_Memory_Entry *entry = NULL;
   Eina_Sp_Id id = 0;
   unsigned int gen;

   // We silently handle NULL
   if (!target) return NULL;

   eina_spinlock_take(&sl);

   table = _eina_safepointer_table_find();
   if (!table) goto no_table;

   UNPROTECT(table);
   entry = _eina_safepointer_entry_find(table);
   if (!entry) goto on_error;

   entry->ptr = (void*) target;
   entry->active = 1;
   gen = entry->generation + 1;
   entry->generation = (gen == EINA_MAX_GENERATIONS) ? 1 : gen;

   id = SP_COMPOSE_FINAL_ID(table->partial_id,
                            (entry - table->entries),
                            entry->generation);

 on_error:
   PROTECT(table);
 no_table:
   eina_spinlock_release(&sl);

   return (void*) id;
}

EAPI void
eina_safepointer_unregister(const Eina_Safepointer *safe)
{
   Eina_Memory_Table *table;
   Eina_Memory_Entry *entry;
   Eina_Table_Index entry_id;

   // We silently handle NULL
   if (!safe) return ;

   entry = _eina_safepointer_entry_get(safe, &table);
   if (!entry) return ;

   eina_spinlock_take(&sl);

   // In case of a race condition during a double free attempt
   // The entry could have been unactivated since we did found it
   // So check again.
   if (!entry->active) goto on_error;

   UNPROTECT(table);
   entry->active = 0;
   eina_trash_push(&table->trash, entry);
   PROTECT(table);

   entry_id = entry - table->entries;
   if (entry_id == EINA_MAX_ENTRY_ID - 1)
     {
        Eina_Table_Index i;

        for (i = entry_id; i >= 0; i--)
          {
             if (table->entries[i].active)
               break ;
          }

        // No more active entry
        // Could be speed up by tracking the
        // number of allocated entries, but
        // with all the syscall around, not sure
        // it is worth it.
        if (i == -1)
          {
             Eina_Table_Index mid_table_id, table_id;

             mid_table_id = (table->partial_id >> EINA_SHIFT_MID_TABLE_ID) & EINA_MASK_MID_TABLE_ID;
             table_id = (table->partial_id >> EINA_SHIFT_TABLE_ID) & EINA_MASK_TABLE_ID;
             UNPROTECT(_eina_sp_ids_tables[mid_table_id]);
             _eina_sp_ids_tables[mid_table_id][table_id] = NULL;
             PROTECT(_eina_sp_ids_tables[mid_table_id]);
             if (!empty_table)
               empty_table = table;
             else
               _eina_safepointer_free(table);
          }
     }

 on_error:
   eina_spinlock_release(&sl);
}

Eina_Bool
eina_safepointer_init(void)
{
   eina_magic_string_set(SAFEPOINTER_MAGIC, "Safepointer");
   _eina_sp_log_dom = eina_log_domain_register("eina_safepointer",
                                               EINA_LOG_COLOR_DEFAULT);
   if (_eina_sp_log_dom < 0)
     {
        EINA_LOG_ERR("Could not register log domain: eina_safepointer.");
        return EINA_FALSE;
     }

   eina_spinlock_new(&sl);

   DBG("entry[Size, Align] = { %zu, %u }",
       sizeof (Eina_Memory_Entry), eina_mempool_alignof(sizeof (Eina_Memory_Entry)));
   DBG("table[Size, Align] = { %zu, %u }",
       sizeof (Eina_Memory_Table), eina_mempool_alignof(sizeof (Eina_Memory_Table)));

   return EINA_TRUE;
}

Eina_Bool
eina_safepointer_shutdown(void)
{
   eina_spinlock_free(&sl);

   return EINA_TRUE;
}