ngx_errno.c revision e18a033b
1
2/*
3 * Copyright (C) Igor Sysoev
4 * Copyright (C) Nginx, Inc.
5 */
6
7
8#include <ngx_config.h>
9#include <ngx_core.h>
10
11
12/*
13 * The strerror() messages are copied because:
14 *
15 * 1) strerror() and strerror_r() functions are not Async-Signal-Safe,
16 *    therefore, they cannot be used in signal handlers;
17 *
18 * 2) a direct sys_errlist[] array may be used instead of these functions,
19 *    but Linux linker warns about its usage:
20 *
21 * warning: `sys_errlist' is deprecated; use `strerror' or `strerror_r' instead
22 * warning: `sys_nerr' is deprecated; use `strerror' or `strerror_r' instead
23 *
24 *    causing false bug reports.
25 */
26
27
28static ngx_str_t  *ngx_sys_errlist;
29static ngx_str_t   ngx_unknown_error = ngx_string("Unknown error");
30
31
32u_char *
33ngx_strerror(ngx_err_t err, u_char *errstr, size_t size)
34{
35    ngx_str_t  *msg;
36
37    msg = ((ngx_uint_t) err < NGX_SYS_NERR) ? &ngx_sys_errlist[err]:
38                                              &ngx_unknown_error;
39    size = ngx_min(size, msg->len);
40
41    return ngx_cpymem(errstr, msg->data, size);
42}
43
44
45ngx_int_t
46ngx_strerror_init(void)
47{
48    char       *msg;
49    u_char     *p;
50    size_t      len;
51    ngx_err_t   err;
52
53    /*
54     * ngx_strerror() is not ready to work at this stage, therefore,
55     * malloc() is used and possible errors are logged using strerror().
56     */
57
58    len = NGX_SYS_NERR * sizeof(ngx_str_t);
59
60    ngx_sys_errlist = malloc(len);
61    if (ngx_sys_errlist == NULL) {
62        goto failed;
63    }
64
65    for (err = 0; err < NGX_SYS_NERR; err++) {
66        msg = strerror(err);
67        len = ngx_strlen(msg);
68
69        p = malloc(len);
70        if (p == NULL) {
71            goto failed;
72        }
73
74        ngx_memcpy(p, msg, len);
75        ngx_sys_errlist[err].len = len;
76        ngx_sys_errlist[err].data = p;
77    }
78
79    return NGX_OK;
80
81failed:
82
83    err = errno;
84    ngx_log_stderr(0, "malloc(%uz) failed (%d: %s)", len, err, strerror(err));
85
86    return NGX_ERROR;
87}
88