>From a38f201f7972d583d9007f924db348c26f00385a Mon Sep 17 00:00:00 2001 From: Brand Huntsman Date: Wed, 17 Jan 2018 14:08:47 -0700 Subject: [PATCH] restore terminal for segfaults and assertions Signed-off-by: Brand Huntsman --- src/nano.c | 24 +++++++++++++++++++++--- src/nano.h | 8 +++++++- src/proto.h | 1 + 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/nano.c b/src/nano.c index a21625cf..87765364 100644 --- a/src/nano.c +++ b/src/nano.c @@ -549,6 +549,13 @@ void say_there_is_no_help(void) } #endif +/* Make nano exit semi-gracefully during a crash. */ +void crash_finish(void) +{ + endwin(); + tcsetattr(0, TCSANOW, &oldterm); +} + /* Make nano exit gracefully. */ void finish(void) { @@ -1890,8 +1897,22 @@ void do_output(char *output, size_t output_len, bool allow_cntrls) update_line(openfile->current, openfile->current_x); } +static const char segfault_msg[] = "Segmentation fault\n"; +static void segfault_handler(int nothing) +{ + crash_finish(); + IGNORE_CALL_RESULT(write(2, segfault_msg, sizeof(segfault_msg))); + exit(1); +} + int main(int argc, char **argv) { + /* Initialize segfault handler. */ + signal(SIGSEGV, segfault_handler); + + /* Back up the terminal settings so that they can be restored. */ + tcgetattr(0, &oldterm); + int stdin_flags, optchr; #if defined(ENABLED_WRAPORJUSTIFY) && defined(ENABLE_NANORC) bool fill_used = FALSE; @@ -1985,9 +2006,6 @@ int main(int argc, char **argv) console = (getenv("DISPLAY") == NULL); #endif - /* Back up the terminal settings so that they can be restored. */ - tcgetattr(0, &oldterm); - /* Get the state of standard input and ensure it uses blocking mode. */ stdin_flags = fcntl(0, F_GETFL, 0); if (stdin_flags != -1) diff --git a/src/nano.h b/src/nano.h index 55abf1e8..2abd22e0 100644 --- a/src/nano.h +++ b/src/nano.h @@ -120,7 +120,13 @@ #include #include #include -#include +#include + +#define assert(expr) if(!(expr)){ \ + crash_finish(); \ + fprintf(stderr, "Assertion (%s) failed: %s %s() %d\n", #expr, __FILE__, __func__, __LINE__); \ + exit(1); \ +} /* If we aren't using an ncurses with mouse support, exclude any * mouse routines, as they are useless then. */ diff --git a/src/proto.h b/src/proto.h index 77ffc05c..db36b391 100644 --- a/src/proto.h +++ b/src/proto.h @@ -420,6 +420,7 @@ void show_restricted_warning(void); #ifndef ENABLE_HELP void say_there_is_no_help(void); #endif +void crash_finish(void); void finish(void); void die(const char *msg, ...); void die_save_file(const char *die_filename, struct stat *die_stat); -- 2.13.6