blob: 195df45807986be925a326b7b4ef308d5b5489cb [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include "aos/common/die.h"
2
3#include <stdlib.h>
4#include <stdio.h>
5#include <errno.h>
6#include <sys/types.h>
7#include <unistd.h>
8#include <string.h>
9#ifdef __VXWORKS__
10#include <taskLib.h>
11// Have to re-declare it with __attribute__((noreturn)).
12extern "C" void abort() __attribute__((noreturn));
13#endif
14
15#include <string>
16
17#include "aos/aos_stdint.h"
18
19namespace aos {
20
21void Die(const char *format, ...) {
22 va_list args;
23 va_start(args, format);
24 VDie(format, args);
25}
26
27namespace {
28// Calculates the filename to dump the message into.
29const std::string GetFilename() {
30#ifdef __VXWORKS__
31 const char *name = taskName(0); // get the name of this task
32 if (name == NULL) name = "<unknown>";
33 const std::string first_part = "/aos_fatal_error.";
34 return first_part + std::string(name);
35#else
36 char *filename;
37 if (asprintf(&filename, "/tmp/aos_fatal_error.%jd",
38 static_cast<intmax_t>(getpid())) > 0) {
39 std::string r(filename);
40 free(filename);
41 return r;
42 } else {
43 fprintf(stderr, "aos fatal: asprintf(%p, \"thingie with %%jd\", %jd)"
44 " failed with %d (%s)\n", &filename,
45 static_cast<intmax_t>(getpid()), errno, strerror(errno));
46 return std::string();
47 }
48#endif
49}
50} // namespace
51void VDie(const char *format, va_list args_in) {
52 va_list args;
53
54 fputs("aos fatal: ERROR!! details following\n", stderr);
55 va_copy(args, args_in);
56 vfprintf(stderr, format, args);
57 va_end(args);
58 fputs("aos fatal: ERROR!! see stderr for details\n", stdout);
59
60 const std::string filename = GetFilename();
61 if (!filename.empty()) {
62 FILE *error_file = fopen(filename.c_str(), "w");
63 if (error_file != NULL) {
64 va_copy(args, args_in);
65 vfprintf(error_file, format, args);
66 va_end(args);
67 fclose(error_file);
68 } else {
69 fprintf(stderr, "aos fatal: fopen('%s', \"w\") failed with %d (%s)\n",
70 filename.c_str(), errno, strerror(errno));
71 }
72 }
73
74 abort();
75}
76
77} // namespace aos