blob: 00a86bbc540c2775cf849fea821e437a9b72c98f [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
brians6ed722d2013-02-12 03:19:55 +000051
brians343bc112013-02-10 01:53:46 +000052void VDie(const char *format, va_list args_in) {
53 va_list args;
54
55 fputs("aos fatal: ERROR!! details following\n", stderr);
56 va_copy(args, args_in);
57 vfprintf(stderr, format, args);
58 va_end(args);
59 fputs("aos fatal: ERROR!! see stderr for details\n", stdout);
60
61 const std::string filename = GetFilename();
62 if (!filename.empty()) {
63 FILE *error_file = fopen(filename.c_str(), "w");
64 if (error_file != NULL) {
65 va_copy(args, args_in);
66 vfprintf(error_file, format, args);
67 va_end(args);
68 fclose(error_file);
69 } else {
70 fprintf(stderr, "aos fatal: fopen('%s', \"w\") failed with %d (%s)\n",
71 filename.c_str(), errno, strerror(errno));
72 }
73 }
74
75 abort();
76}
77
78} // namespace aos