aboutsummaryrefslogtreecommitdiff
path: root/client/libacron/private/helpers.c
blob: 5a23e34f154dcda8d35231a84b8a327a1dbb8314 (plain)
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
/*
 * Created by yuuta on 7/19/22.
 */

#include "win32.h"
#include "helpers.h"
#include "log.h"
#include "common.h"

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

int alloc(void *existing,
            unsigned int count,
            unsigned int bytes,
            bool zero_out,
            void **out) {
    const unsigned int size = count * bytes;
    void *ptr;
    if (!(ptr = realloc(existing, size))) {
        const int e = errno;
        LOGEV("Cannot %sallocate %d bytes of memory: %s (%d).",
                existing ? "re" : "",
                size,
                strerror2(e),
                e);
        return AC_E_MEMORY_ALLOCATION;
    }
    if (!existing && zero_out) {
        memset(ptr, 0, size);
    }
    *out = ptr;
    return AC_E_OK;
}

int strdup2(const char *str, char **out) {
    char *str2;
    if (!(str2 = strdup(str))) {
        const int e = errno;
        LOGEV("Cannot duplicate string '%s': %s (%d).",
                str,
                strerror2(e),
                e);
        return AC_E_MEMORY_ALLOCATION;
    }
    *out = str2;
    return AC_E_OK;
}

static _Thread_local char err_buf[1024];

char *strerror2(int errnum) {
#ifdef WIN32
    /* Win32 strerror(3) is thread-safe. */
    return strerror(errnum);
#else
    int r;
    if ((r = strerror_r(errnum, err_buf, sizeof(err_buf) / sizeof(char)))) {
        snprintf(err_buf, 1024, "%d (%d)", errnum, r);
    }
    return err_buf;
#endif
}