Skip to main content
summaryrefslogtreecommitdiffstats
blob: b802785d168dab352cd3e3034ada20a382357013 (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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/*******************************************************************************
 * Copyright (c) 2007, 2010 Wind River Systems, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 * The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 * You may elect to redistribute this code under either of these licenses.
 *
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/

/*
 * This module defines agent error codes in addition to system codes defined in errno.h
 */

#include <tcf/config.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <time.h>
#include <tcf/framework/mdep-inet.h>
#include <tcf/framework/errors.h>
#include <tcf/framework/events.h>
#include <tcf/framework/exceptions.h>
#include <tcf/framework/streams.h>
#include <tcf/framework/myalloc.h>
#include <tcf/framework/json.h>
#include <tcf/framework/trace.h>

#define ERR_MESSAGE_MIN         (STD_ERR_BASE + 100)
#if MEM_USAGE_FACTOR <= 2
#define ERR_MESSAGE_MAX         (STD_ERR_BASE + 129)
#else
#define ERR_MESSAGE_MAX         (STD_ERR_BASE + 199)
#endif

#define MESSAGE_CNT             (ERR_MESSAGE_MAX - ERR_MESSAGE_MIN + 1)

#ifdef WIN32
#  define ERR_WINDOWS_MIN       (STD_ERR_BASE + 0x10000)
#  define ERR_WINDOWS_MAX       (ERR_WINDOWS_MIN + 0xffff)
#  define ERR_WINDOWS_CNT       (ERR_WINDOWS_MAX - ERR_WINDOWS_MIN + 1)
#endif

#define SRC_GAI     2
#define SRC_MESSAGE 3
#define SRC_REPORT  4

typedef struct ReportBuffer {
    ErrorReport pub; /* public part of error report */
    int refs;
    int gets;
} ReportBuffer;

typedef struct ErrorMessage {
    int source;
    int error;
    char * text;
    ReportBuffer * report;
} ErrorMessage;

static ErrorMessage msgs[MESSAGE_CNT];
static int msgs_pos = 0;

static char * msg_buf = NULL;
static size_t msg_max = 0;
static size_t msg_len = 0;

static void realloc_msg_buf(void) {
    assert(is_dispatch_thread());
    if (msg_max <= msg_len + 128 || msg_max > msg_len + 2048) {
        msg_max = msg_len + 256;
        msg_buf = (char *)loc_realloc(msg_buf, msg_max);
    }
}

static void release_report(ReportBuffer * report) {
    if (report == NULL) return;
    assert(report->refs > report->gets);
    report->refs--;
    if (report->refs == 0) {
        while (report->pub.props != NULL) {
            ErrorReportItem * i = report->pub.props;
            report->pub.props = i->next;
            loc_free(i->name);
            loc_free(i->value);
            loc_free(i);
        }
        while (report->pub.param_cnt > 0) {
            loc_free(report->pub.params[--report->pub.param_cnt]);
        }
        loc_free(report->pub.params);
        loc_free(report->pub.format);
        loc_free(report);
    }
}

static ErrorMessage * alloc_msg(int source) {
    ErrorMessage * m = msgs + msgs_pos;
    assert(is_dispatch_thread());
    errno = ERR_MESSAGE_MIN + msgs_pos++;
    if (msgs_pos >= MESSAGE_CNT) msgs_pos = 0;
    release_report(m->report);
    loc_free(m->text);
    m->source = source;
    m->error = 0;
    m->report = NULL;
    m->text = NULL;
    return m;
}

#ifdef WIN32

static char * system_strerror(DWORD win32_error_code) {
    WCHAR * buf = NULL;
    assert(is_dispatch_thread());
    msg_len = 0;
    if (FormatMessageW(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS |
            FORMAT_MESSAGE_MAX_WIDTH_MASK,
            NULL,
            win32_error_code,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
            (LPWSTR)&buf, 0, NULL)) {
        msg_len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
        if (msg_len > 0) {
            realloc_msg_buf();
            msg_len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, msg_buf, msg_max, NULL, NULL);
        }
    }
    if (msg_len == 0) {
        realloc_msg_buf();
        msg_len = snprintf(msg_buf, msg_max, "System error code 0x%lx", (unsigned long)win32_error_code);
    }
    if (buf != NULL) LocalFree(buf);
    while (msg_len > 0 && msg_buf[msg_len - 1] <= ' ') msg_len--;
    if (msg_len > 0 && msg_buf[msg_len - 1] == '.') msg_len--;
    msg_buf[msg_len] = 0;
    return msg_buf;
}

int set_win32_errno(DWORD win32_error_code) {
    if (win32_error_code == 0) return errno = 0;
    if (win32_error_code >= ERR_WINDOWS_CNT) return errno = ERR_OTHER;
    return errno = ERR_WINDOWS_MIN + win32_error_code;
}

#elif defined(__SYMBIAN32__)

#include <e32err.h>

static char * system_strerror(int err) {
    static char static_error[32];
    switch (err) {
    case KErrNotFound:
        return "item not found";
    case KErrNotSupported:
        return "functionality is not supported";
    case KErrBadHandle:
        return "an invalid handle";
    case KErrAccessDenied:
        return "access to a file is denied";
    case KErrAlreadyExists:
        return "an object already exists";
    case KErrWrite:
        return "error in write operation";
    case KErrPermissionDenied:
        return "permission denied";
    case KErrBadDescriptor:
        return "bad descriptor";
    default:
        snprintf(static_error, sizeof(static_error), "Error code %d", err);
        return static_error;
    }
}

#endif

static void append_format_parameter(char * type, char * style, char * param) {
    /* Note: 'param' is UTF-8 encoded JSON text */
    char str[64];
    if (param != NULL && (*param == '"' || strcmp(type, "number") == 0)) {
        Trap trap;
        ByteArrayInputStream buf;
        InputStream * inp = create_byte_array_input_stream(&buf, param, strlen(param));
        if (set_trap(&trap)) {
            if (*param == '"') {
                char * x = json_read_alloc_string(inp);
                if (x != NULL) {
                    char * s = x;
                    while (*s) {
                        realloc_msg_buf();
                        msg_buf[msg_len++] = *s++;
                    }
                    loc_free(x);
                }
                param = NULL;
            }
            else {
                double x = json_read_double(inp);
                if (strcmp(style, "percent") == 0) {
                    snprintf(str, sizeof(str), "%ld%%", (long)(x * 100));
                }
                else if (strcmp(style, "integer") == 0) {
                    snprintf(str, sizeof(str), "%ld", (long)x);
                }
                else {
                    snprintf(str, sizeof(str), "%g", x);
                }
                param = str;
            }
            clear_trap(&trap);
        }
    }
    if (param != NULL) {
        while (*param) {
            realloc_msg_buf();
            msg_buf[msg_len++] = *param++;
        }
    }
}

static const char * format_error_report_message(const char * fmt, char ** params, int param_cnt) {
    int fmt_pos = 0;
    int in_quotes = 0;

    msg_len = 0;
    while (fmt[fmt_pos]) {
        char ch = fmt[fmt_pos++];
        realloc_msg_buf();
        if (in_quotes && ch == '\'') {
            in_quotes = 0;
        }
        else if (in_quotes) {
            msg_buf[msg_len++] = ch;
        }
        else if (ch == '\'' && fmt[fmt_pos] == '\'') {
            msg_buf[msg_len++] = ch;
            fmt_pos++;
        }
        else if (ch =='\'') {
            in_quotes = 1;
        }
        else if (ch == '{') {
            size_t j = 0;
            int index = 0;
            char type[16];
            char style[16];
            type[0] = style[0] = 0;
            while (fmt[fmt_pos] >= '0' && fmt[fmt_pos] <= '9') {
                index = index * 10 + (fmt[fmt_pos++] - '0');
            }
            if (fmt[fmt_pos] == ',') {
                fmt_pos++;
                j = 0;
                while (fmt[fmt_pos] >= 'a' && fmt[fmt_pos] <= 'z') {
                    ch = fmt[fmt_pos++];
                    if (j < sizeof(type) - 1) type[j++] = ch;
                }
                type[j++] = 0;
                if (fmt[fmt_pos] == ',') {
                    fmt_pos++;
                    j = 0;
                    while (fmt[fmt_pos] >= 'a' && fmt[fmt_pos] <= 'z') {
                        ch = fmt[fmt_pos++];
                        if (j < sizeof(style) - 1) style[j++] = ch;
                    }
                    style[j++] = 0;
                }
            }
            if (index < param_cnt) append_format_parameter(type, style, params[index]);
            while (fmt[fmt_pos] && fmt[fmt_pos] != '}') fmt_pos++;
            if (fmt[fmt_pos] == '}') fmt_pos++;
        }
        else {
            msg_buf[msg_len++] = ch;
        }
    }
    realloc_msg_buf();
    msg_buf[msg_len++] = 0;
    return msg_buf;
}

const char * errno_to_str(int err) {
    switch (err) {
    case ERR_ALREADY_STOPPED:   return "Already stopped";
    case ERR_ALREADY_EXITED:    return "Already exited";
    case ERR_ALREADY_RUNNING:   return "Already running";
    case ERR_JSON_SYNTAX:       return "JSON syntax error";
    case ERR_PROTOCOL:          return "Protocol format error";
    case ERR_INV_CONTEXT:       return "Invalid context";
    case ERR_INV_ADDRESS:       return "Invalid address";
    case ERR_EOF:               return "End of file";
    case ERR_BASE64:            return "Invalid BASE64 string";
    case ERR_INV_EXPRESSION:    return "Invalid expression";
    case ERR_SYM_NOT_FOUND:     return "Symbol not found";
    case ERR_ALREADY_ATTACHED:  return "Already attached";
    case ERR_BUFFER_OVERFLOW:   return "Buffer overflow";
    case ERR_INV_FORMAT:        return "Format is not supported";
    case ERR_INV_NUMBER:        return "Invalid number";
    case ERR_IS_RUNNING:        return "Execution context is running";
    case ERR_INV_DWARF:         return "Error reading DWARF data";
    case ERR_UNSUPPORTED:       return "Unsupported command";
    case ERR_CHANNEL_CLOSED:    return "Channel closed";
    case ERR_COMMAND_CANCELLED: return "Command canceled";
    case ERR_UNKNOWN_PEER:      return "Unknown peer";
    case ERR_INV_DATA_SIZE:     return "Invalid data size";
    case ERR_INV_DATA_TYPE:     return "Invalid data type";
    case ERR_INV_COMMAND:       return "Command is not recognized";
    case ERR_INV_TRANSPORT:     return "Invalid transport name";
    case ERR_CACHE_MISS:        return "Invalid data cache state";
    case ERR_NOT_ACTIVE:        return "Context is not active";
    default:
        if (err == 0) return "Success";
        if (err >= ERR_MESSAGE_MIN && err <= ERR_MESSAGE_MAX) {
            if (is_dispatch_thread()) {
                ErrorMessage * m = msgs + (err - ERR_MESSAGE_MIN);
                if (m->report != NULL && m->report->pub.format != NULL) {
                    return format_error_report_message(m->report->pub.format, m->report->pub.params, m->report->pub.param_cnt);
                }
                switch (m->source) {
                case SRC_GAI:
                    return loc_gai_strerror(m->error);
                case SRC_MESSAGE:
                    return m->text;
                case SRC_REPORT:
                    return errno_to_str(m->error);
                }
            }
            else {
                return "cannot get error message text: errno_to_str() must be called from the main thread";
            }
        }
#ifdef WIN32
        if (err >= ERR_WINDOWS_MIN && err <= ERR_WINDOWS_MAX) {
            return system_strerror(err - ERR_WINDOWS_MIN);
        }
#endif
#ifdef __SYMBIAN32__
        if (err < 0) {
            return system_strerror(err);
        }
#endif
        return strerror(err);
    }
}

int set_errno(int no, const char * msg) {
    errno = no;
    if (no != 0 && msg != NULL) {
        ErrorMessage * m = alloc_msg(SRC_MESSAGE);
        /* alloc_msg() assigns new value to 'errno',
         * need to be sure it does not change until this function exits.
         */
        int err = errno;
        m->error = get_error_code(no);
        if (no == ERR_OTHER) {
            m->text = loc_strdup(msg);
        }
        else {
            const char * text0 = errno_to_str(no);
            size_t len = strlen(msg) + strlen(text0) + 4;
            char * text1 = (char *)loc_alloc(len);
            snprintf(text1, len, "%s. %s", msg, text0);
            m->text = text1;
        }
        errno = err;
    }
    return errno;
}

int set_fmt_errno(int no, const char * fmt, ...) {
    va_list vaList;
    char * buf = NULL;
    size_t len = 100;
    int err, n;

    while (1) {
        buf = (char *)loc_realloc(buf, len);
        va_start(vaList, fmt);
        n = vsnprintf(buf, len, fmt, vaList);
        va_end(vaList);
        if (n < (int)len) break;
        len = n + 1;
    }
    err = n <= 0 ? no : set_errno(no, buf);
    loc_free(buf);
    return errno = err;
}

int set_gai_errno(int no) {
    errno = no;
    if (no != 0) {
        ErrorMessage * m = alloc_msg(SRC_GAI);
        m->error = no;
    }
    return errno;
}

int set_error_report_errno(ErrorReport * r) {
    errno = 0;
    if (r != NULL) {
        ReportBuffer * report = (ReportBuffer *)((char *)r - offsetof(ReportBuffer, pub));
        ErrorMessage * m = alloc_msg(SRC_REPORT);
        m->error = report->pub.code + STD_ERR_BASE;
        m->report = report;
        report->refs++;
    }
    return errno;
}

int get_error_code(int no) {
    while (no >= ERR_MESSAGE_MIN && no <= ERR_MESSAGE_MAX) {
        ErrorMessage * m = msgs + (no - ERR_MESSAGE_MIN);
        assert(is_dispatch_thread());
        switch (m->source) {
        case SRC_REPORT:
        case SRC_MESSAGE:
            no = m->error;
            continue;
        }
        return ERR_OTHER;
    }
    return no;
}

static void add_report_prop(ReportBuffer * report, const char * name, ByteArrayOutputStream * buf) {
    ErrorReportItem * i = (ErrorReportItem *)loc_alloc(sizeof(ErrorReportItem));
    i->name = loc_strdup(name);
    get_byte_array_output_stream_data(buf, &i->value, NULL);
    i->next = report->pub.props;
    report->pub.props = i;
}

static void add_report_prop_int(ReportBuffer * report, const char * name, unsigned long n) {
    ByteArrayOutputStream buf;
    OutputStream * out = create_byte_array_output_stream(&buf);
    json_write_ulong(out, n);
    write_stream(out, 0);
    add_report_prop(report, name, &buf);
}

static void add_report_prop_str(ReportBuffer * report, const char * name, const char * str) {
    ByteArrayOutputStream buf;
    OutputStream * out = create_byte_array_output_stream(&buf);
    json_write_string(out, str);
    write_stream(out, 0);
    add_report_prop(report, name, &buf);
}

ErrorReport * get_error_report(int err) {
    ErrorMessage * m = NULL;
    if (err >= ERR_MESSAGE_MIN && err <= ERR_MESSAGE_MAX) {
        assert(is_dispatch_thread());
        m = msgs + (err - ERR_MESSAGE_MIN);
        if (m->report != NULL) {
            m->report->refs++;
            m->report->gets++;
            return &m->report->pub;
        }
    }
    if (err != 0) {
        ReportBuffer * report = (ReportBuffer *)loc_alloc_zero(sizeof(ReportBuffer));
        struct timespec timenow;

        if (clock_gettime(CLOCK_REALTIME, &timenow) == 0) {
            report->pub.time_stamp = (uint64_t)timenow.tv_sec * 1000 + timenow.tv_nsec / 1000000;
        }

        report->pub.format = loc_strdup(errno_to_str(err));

#ifdef WIN32
        if (err >= ERR_WINDOWS_MIN && err <= ERR_WINDOWS_MAX) {
            add_report_prop_int(report, "AltCode", err - ERR_WINDOWS_MIN);
            add_report_prop_str(report, "AltOrg", "WIN32");
            err = ERR_OTHER;
        }
#endif

        if (m != NULL) {
            if (m->source == SRC_MESSAGE) {
                err = m->error;
            }
            else {
                err = ERR_OTHER;
            }
        }

        if (err < STD_ERR_BASE || err > ERR_MESSAGE_MAX) {
            add_report_prop_int(report, "AltCode", err);
#if defined(_MSC_VER)
            add_report_prop_str(report, "AltOrg", "MSC");
#elif defined(_WRS_KERNEL)
            add_report_prop_str(report, "AltOrg", "VxWorks");
#elif defined(__CYGWIN__)
            add_report_prop_str(report, "AltOrg", "CygWin");
#elif defined(__linux__)
            add_report_prop_str(report, "AltOrg", "Linux");
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__)
            add_report_prop_str(report, "AltOrg", "BSD");
#elif defined(__SYMBIAN32__)
            add_report_prop_str(report, "AltOrg", "Symbian");
#else
            add_report_prop_str(report, "AltOrg", "POSIX");
#endif
            err = ERR_OTHER;
        }

        assert(err >= STD_ERR_BASE);
        assert(err < ERR_MESSAGE_MIN);

        report->pub.code = err - STD_ERR_BASE;
        report->refs = 1;
        report->gets = 1;
        if (m != NULL) {
            assert(m->report == NULL);
            m->report = report;
            report->refs++;
        }
        return &report->pub;
    }
    return NULL;
}

ErrorReport * create_error_report(void) {
    ReportBuffer * report = (ReportBuffer *)loc_alloc_zero(sizeof(ReportBuffer));
    report->refs = 1;
    report->gets = 1;
    return &report->pub;
}

void release_error_report(ErrorReport * r) {
    if (r != NULL) {
        ReportBuffer * report = (ReportBuffer *)((char *)r - offsetof(ReportBuffer, pub));
        assert(is_dispatch_thread());
        assert(report->gets > 0);
        report->gets--;
        release_report(report);
    }
}

int compare_error_reports(ErrorReport * x, ErrorReport * y) {
    int i;
    if (x == y) return 1;
    if (x == NULL || y == NULL) return 0;
    if (x->code != y->code) return 0;
    if (x->format != y->format) {
        if (x->format == NULL || y->format == NULL) return 0;
        if (strcmp(x->format, y->format)) return 0;
    }
    if (x->param_cnt != y->param_cnt) return 0;
    for (i = 0; i < x->param_cnt; i++) {
        char * px = x->params[i];
        char * py = y->params[i];
        if (px != py) {
            if (px == NULL || py == NULL) return 0;
            if (strcmp(px, py)) return 0;
        }
    }
    if (x->props != y->props) {
        ErrorReportItem * px = x->props;
        ErrorReportItem * py = x->props;
        while (px != NULL || py  != NULL) {
            if (px != py) {
                if (px == NULL || py == NULL) return 0;
                if (strcmp(px->name, py->name)) return 0;
                if (strcmp(px->value, py->value)) return 0;
            }
            px = px->next;
            py = py->next;
        }
    }
    return 1;
}

#ifdef NDEBUG

void check_error(int error) {
    if (error == 0) return;
#if ENABLE_Trace
    trace(LOG_ALWAYS, "Fatal error %d: %s", error, errno_to_str(error));
    trace(LOG_ALWAYS, "  Exiting agent...");
    if (log_file == stderr) exit(1);
#endif
    fprintf(stderr, "Fatal error %d: %s", error, errno_to_str(error));
    fprintf(stderr, "  Exiting agent...");
    exit(1);
}

#else /* NDEBUG */

void check_error_debug(const char * file, int line, int error) {
    if (error == 0) return;
#if ENABLE_Trace
    trace(LOG_ALWAYS, "Fatal error %d: %s", error, errno_to_str(error));
    trace(LOG_ALWAYS, "  At %s:%d", file, line);
    trace(LOG_ALWAYS, "  Exiting agent...");
    if (log_file == stderr) exit(1);
#endif
    fprintf(stderr, "Fatal error %d: %s", error, errno_to_str(error));
    fprintf(stderr, "  At %s:%d", file, line);
    fprintf(stderr, "  Exiting agent...");
    exit(1);
}

#endif /* NDEBUG */

Back to the top