aboutsummaryrefslogtreecommitdiff
path: root/client/libacron/private/helpers.c
blob: a859e80472caf59ff5c9218e6062f610363cd32a (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
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
/*
 * 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>

#ifdef _WIN32
#include <windows.h>
#endif

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;
}

#ifdef _WIN32
static _Thread_local LPTSTR err_buf = NULL;
#else
static _Thread_local char err_buf[1024];
#endif

char *strerror2(int errnum) {
#ifdef _WIN32
    if (err_buf) {
        LocalFree(err_buf);
        err_buf = NULL;
    }
    FormatMessage(
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            errnum,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &err_buf,
            0,
            NULL);
    if (!err_buf) {
        return "Unknown error";
    }
#else
    int r;
    if ((r = strerror_r(errnum, err_buf, sizeof(err_buf) / sizeof(char)))) {
        snprintf(err_buf, 1024, "%d (%d)", errnum, r);
    }
#endif
    return err_buf;
}

void helpers_cleanup(void) {
#ifdef _WIN32
    if (err_buf) {
        LocalFree(err_buf);
        err_buf = NULL;
    }
#endif
}