File: ch_malloc.c

package info (click to toggle)
389-ds-base 1.4.0.21-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 50,776 kB
  • sloc: ansic: 303,582; python: 59,673; cpp: 10,380; perl: 5,807; sh: 2,654; makefile: 2,457; yacc: 806; xml: 376; lex: 366; java: 50
file content (377 lines) | stat: -rw-r--r-- 10,118 bytes parent folder | download | duplicates (2)
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
/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 *
 * License: GPL (version 3 or any later version).
 * See LICENSE for details.
 * END COPYRIGHT BLOCK **/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

/* slapi_ch_malloc.c - malloc routines that test returns from malloc and friends */

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strdup */
#include <sys/types.h>
#include <sys/socket.h>
#include "slap.h"

#define OOM_PREALLOC_SIZE 65536
static void *oom_emergency_area = NULL;
static PRLock *oom_emergency_lock = NULL;

#define SLAPD_MODULE "memory allocator"

static const char *const oom_advice =
    "\nThe server has probably allocated all available virtual memory. To solve\n"
    "this problem, make more virtual memory available to your server, or reduce\n"
    "one or more of the following server configuration settings:\n"
    "  nsslapd-cachesize        (Database Settings - Maximum entries in cache)\n"
    "  nsslapd-cachememsize     (Database Settings - Memory available for cache)\n"
    "  nsslapd-dbcachesize      (LDBM Plug-in Settings - Maximum cache size)\n"
    "  nsslapd-import-cachesize (LDBM Plug-in Settings - Import cache size).\n"
    "Can't recover; calling exit(1).\n";

static void
create_oom_buffer(void)
{
    /* ensure that we have space to allow for shutdown calls to malloc()
     * from should we run out of memory.
     */
    if (oom_emergency_area == NULL) {
        oom_emergency_area = malloc(OOM_PREALLOC_SIZE);
        oom_emergency_lock = PR_NewLock();
    }
}

/* called when we have just detected an out of memory condition, before
 * we make any other library calls.  Note that slapi_log_err() calls malloc,
 * indirectly.  By making 64KB free, we should be able to have a few
 * mallocs' succeed before we shut down.
 */
void
oom_occurred(void)
{
    int tmp_errno = errno; /* callers will need the error from malloc */
    if (oom_emergency_lock == NULL) {
        return;
    }

    PR_Lock(oom_emergency_lock);
    if (oom_emergency_area) {
        free(oom_emergency_area);
        oom_emergency_area = NULL;
    }
    PR_Unlock(oom_emergency_lock);
    errno = tmp_errno;
}

static void
log_negative_alloc_msg(const char *op, const char *units, unsigned long size)
{
    slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                  "cannot %s %lu %s;\n"
                  "trying to allocate 0 or a negative number of %s is not portable and\n"
                  "gives different results on different platforms.\n",
                  op, size, units, units);
}

char *
slapi_ch_malloc(
    unsigned long size)
{
    char *newmem;

    if (size <= 0) {
        log_negative_alloc_msg("malloc", "bytes", size);
        return 0;
    }

    if ((newmem = (char *)malloc(size)) == NULL) {
        int oserr = errno;

        oom_occurred();
        slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                      "malloc of %lu bytes failed; OS error %d (%s)%s\n",
                      size, oserr, slapd_system_strerror(oserr), oom_advice);
        exit(1);
    }
    /* So long as this happens once, we are happy, put it in ch_malloc. */
    create_oom_buffer();

    return (newmem);
}

/* See slapi-plugin.h */
char *
slapi_ch_memalign(uint32_t size, uint32_t alignment)
{
    char *newmem;

    if (posix_memalign((void **)&newmem, alignment, size) != 0) {
        int oserr = errno;

        oom_occurred();
        slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                      "malloc of %" PRIu32 " bytes failed; OS error %d (%s)%s\n",
                      size, oserr, slapd_system_strerror(oserr), oom_advice);
        exit(1);
    }

    return (newmem);
}

char *
slapi_ch_realloc(
    char *block,
    unsigned long size)
{
    char *newmem;

    if (block == NULL) {
        return (slapi_ch_malloc(size));
    }

    if (size <= 0) {
        log_negative_alloc_msg("realloc", "bytes", size);
        return block;
    }

    if ((newmem = (char *)realloc(block, size)) == NULL) {
        int oserr = errno;

        oom_occurred();
        slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                      "realloc of %lu bytes failed; OS error %d (%s)%s\n",
                      size, oserr, slapd_system_strerror(oserr), oom_advice);
        exit(1);
    }

    return (newmem);
}

char *
slapi_ch_calloc(
    unsigned long nelem,
    unsigned long size)
{
    char *newmem;

    if (size <= 0) {
        log_negative_alloc_msg("calloc", "bytes", size);
        return 0;
    }

    if (nelem <= 0) {
        log_negative_alloc_msg("calloc", "elements", nelem);
        return 0;
    }

    if ((newmem = (char *)calloc(nelem, size)) == NULL) {
        int oserr = errno;

        oom_occurred();
        slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                      "calloc of %lu elems of %lu bytes failed; OS error %d (%s)%s\n",
                      nelem, size, oserr, slapd_system_strerror(oserr), oom_advice);
        exit(1);
    }

    return (newmem);
}

char *
slapi_ch_strdup(const char *s1)
{
    char *newmem;

    /* strdup pukes on NULL strings...bail out now */
    if (NULL == s1)
        return NULL;
    newmem = strdup(s1);
    if (newmem == NULL) {
        int oserr = errno;
        oom_occurred();
        slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                      "strdup of %lu characters failed; OS error %d (%s)%s\n",
                      (unsigned long)strlen(s1), oserr, slapd_system_strerror(oserr),
                      oom_advice);
        exit(1);
    }

    return newmem;
}

struct berval *
slapi_ch_bvdup(const struct berval *v)
{
    struct berval *newberval = ber_bvdup((struct berval *)v);
    if (newberval == NULL) {
        int oserr = errno;

        oom_occurred();
        slapi_log_err(SLAPI_LOG_ERR, SLAPD_MODULE,
                      "ber_bvdup of %lu bytes failed; OS error %d (%s)%s\n",
                      (unsigned long)v->bv_len, oserr, slapd_system_strerror(oserr),
                      oom_advice);
        exit(1);
    }
    return newberval;
}

struct berval **
slapi_ch_bvecdup(struct berval **v)
{
    struct berval **newberval = NULL;
    if (v != NULL) {
        size_t i = 0;
        while (v[i] != NULL)
            ++i;
        newberval = (struct berval **)slapi_ch_malloc((i + 1) * sizeof(struct berval *));
        newberval[i] = NULL;
        while (i-- > 0) {
            newberval[i] = slapi_ch_bvdup(v[i]);
        }
    }
    return newberval;
}

/*
 *  Function: slapi_ch_free
 *
 *  Returns: nothing
 *
 *  Description: frees the pointer, and then sets it to NULL to
 *               prevent free-memory writes.
 *               Note: pass in the address of the pointer you want to free.
 *               Note: you can pass in null pointers, it's cool.
 */
void
slapi_ch_free(void **ptr)
{
    /* Man 3 free
     * If ptr is NULL, no operation is performed. We only need to check ptr
     * has a value so that *ptr won't SIGSEGV
     */
    if (ptr == NULL) {
        return;
    }

    free(*ptr);
    *ptr = NULL;
    return;
}


/* just like slapi_ch_free, takes the address of the struct berval pointer */
void
slapi_ch_bvfree(struct berval **v)
{
    if (v == NULL || *v == NULL)
        return;

    slapi_ch_free((void **)&((*v)->bv_val));
    slapi_ch_free((void **)v);

    return;
}

/* just like slapi_ch_free, but the argument is the address of a string
   This helps with compile time error checking
*/
void
slapi_ch_free_string(char **s)
{
    slapi_ch_free((void **)s);
}

/*
  This function is just like PR_smprintf.  It works like sprintf
  except that it allocates enough memory to hold the result
  string and returns that allocated memory to the caller.  The
  caller must use slapi_ch_free_string to free the memory.
  It should only be used in those situations that will eventually free
  the memory using slapi_ch_free_string e.g. allocating a string
  that will be freed as part of pblock cleanup, or passed in to create
  a Slapi_DN, or things of that nature.  If you have control of the
  flow such that the memory will be allocated and freed in the same
  scope, better to just use PR_smprintf and PR_smprintf_free instead
  because it is likely faster.
*/
/*
  This implementation is the same as PR_smprintf.
  The above comment does not apply to this function for now.
  see [150809] for more details.
  WARNING - with this fix, this means we are now mixing PR_Malloc with
  slapi_ch_free.  Which is ok for now - they both use malloc/free from
  the operating system.  But if this changes in the future, this
  function will have to change as well.
*/
char *
slapi_ch_smprintf(const char *fmt, ...)
{
    char *p = NULL;
    va_list ap;

    if (NULL == fmt) {
        return NULL;
    }

    va_start(ap, fmt);
    p = PR_vsmprintf(fmt, ap);
    va_end(ap);

    return p;
}

/* Constant time memcmp. Does not shortcircuit on failure! */
/* This relies on p1 and p2 both being size at least n! */
int32_t
slapi_ct_memcmp(const void *p1, const void *p2, size_t n1, size_t n2)
{
    int result = 0;
    const unsigned char *_p1 = (const unsigned char *)p1;
    const unsigned char *_p2 = (const unsigned char *)p2;

    if (_p1 == NULL || _p2 == NULL) {
        return 2;
    }

    if (n1 == n2) {
        for (size_t i = 0; i < n1; i++) {
            if (_p1[i] ^ _p2[i]) {
                result = 1;
            }
        }
    } else {
        const unsigned char *_pa;
        const unsigned char *_pb;
        size_t nl;
        if (n2 > n1) {
            _pa = _p2;
            _pb = _p2;
            nl = n2;
        } else {
            _pa = _p1;
            _pb = _p1;
            nl = n1;
        }
        /* We already fail as n1 != n2 */
        result = 3;
        for (size_t i = 0; i < nl; i++) {
            if (_pa[i] ^ _pb[i]) {
                /*
                 * If we don't mutate result here, dead code elimination
                 * we remove for loop.
                 */
                result = 4;
            }
        }
    }
    return result;
}