1/*
2 * Copyright 2017, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(DATA61_BSD)
11 */
12
13#include <camkes/error.h>
14#include <stdio.h>
15#include <utils/util.h>
16#include <inttypes.h>
17
18/* The default error handler that is invoked if no other error handler is
19 * registered.
20 */
21static camkes_error_action_t default_error_handler(camkes_error_t *error)
22{
23    fprintf(stderr, "-- %s --\n", error->instance);
24    switch (error->type) {
25
26    case CE_BUFFER_LENGTH_EXCEEDED:
27        fprintf(stderr, "Error: about to exceed buffer length by writing "
28                "up to %u bytes\n", error->target_length);
29        break;
30
31    case CE_INVALID_METHOD_INDEX:
32        fprintf(stderr, "Error: invalid method index of %"PRIu64"\n",
33                error->invalid_index);
34        break;
35
36    case CE_MALFORMED_RPC_PAYLOAD:
37        fprintf(stderr, "Error: Malformed RPC payload\n");
38        break;
39
40    case CE_SYSCALL_FAILED:
41        fprintf(stderr, "Error: syscall failed\n");
42        break;
43
44    case CE_ALLOCATION_FAILURE:
45        fprintf(stderr, "Error: allocation failed\n");
46        break;
47
48    default:
49        UNREACHABLE();
50    }
51    fprintf(stderr, "Occurred at %s:%lu\n", error->filename, error->lineno);
52    fprintf(stderr, "Details: %s\n", error->description);
53
54    return CEA_HALT;
55}
56
57/* Currently active error handler. */
58static camkes_error_handler_t err = default_error_handler;
59
60camkes_error_action_t camkes_error(camkes_error_t *e)
61{
62    return err(e);
63}
64
65camkes_error_handler_t camkes_register_error_handler(camkes_error_handler_t handler)
66{
67    camkes_error_handler_t old = err;
68    err = handler;
69    return old;
70}
71