From 02d04eac24f497e34ac9869bac5bfb1e044a6b62 Mon Sep 17 00:00:00 2001 From: Tom Tromey Date: Wed, 20 Jul 2022 12:46:08 -0600 Subject: Use strwinerror in gdb/windows-nat.c When working on windows-nat.c, it's useful to see an error message in addition to the error number given by GetLastError. This patch moves strwinerror from gdbserver to gdbsupport, and then updates windows-nat.c to use it. A couple of minor changes to strwinerror (constify the return type and use the ARRAY_SIZE macro) are also included. --- gdbsupport/errors.cc | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ gdbsupport/errors.h | 16 ++++++++++++++++ 2 files changed, 70 insertions(+) (limited to 'gdbsupport') diff --git a/gdbsupport/errors.cc b/gdbsupport/errors.cc index 703b221..b98d015 100644 --- a/gdbsupport/errors.cc +++ b/gdbsupport/errors.cc @@ -19,6 +19,9 @@ #include "common-defs.h" #include "errors.h" +#ifdef USE_WIN32API +#include +#endif /* USE_WIN32API */ /* See gdbsupport/errors.h. */ @@ -67,3 +70,54 @@ internal_warning (const char *file, int line, const char *fmt, ...) internal_vwarning (file, line, fmt, ap); va_end (ap); } + +#ifdef USE_WIN32API + +/* See errors.h. */ + +const char * +strwinerror (ULONGEST error) +{ + static char buf[1024]; + TCHAR *msgbuf; + DWORD lasterr = GetLastError (); + DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPTSTR) &msgbuf, + 0, + NULL); + if (chars != 0) + { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' + && msgbuf[chars - 1] == '\n') + { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > ARRAY_SIZE (buf) - 1) + { + chars = ARRAY_SIZE (buf) - 1; + msgbuf [chars] = 0; + } + +#ifdef UNICODE + wcstombs (buf, msgbuf, chars + 1); +#else + strncpy (buf, msgbuf, chars + 1); +#endif + LocalFree (msgbuf); + } + else + sprintf (buf, "unknown win32 error (%u)", (unsigned) error); + + SetLastError (lasterr); + return buf; +} + +#endif /* USE_WIN32API */ diff --git a/gdbsupport/errors.h b/gdbsupport/errors.h index 47965ea..9a671d3 100644 --- a/gdbsupport/errors.h +++ b/gdbsupport/errors.h @@ -91,4 +91,20 @@ extern void malloc_failure (long size) ATTRIBUTE_NORETURN; extern void flush_streams (); +#ifdef USE_WIN32API + +/* Map the Windows error number in ERROR to a locale-dependent error + message string and return a pointer to it. Typically, the values + for ERROR come from GetLastError. + + The string pointed to shall not be modified by the application, + but may be overwritten by a subsequent call to strwinerror + + The strwinerror function does not change the current setting + of GetLastError. */ + +extern const char *strwinerror (ULONGEST error); + +#endif /* USE_WIN32API */ + #endif /* COMMON_ERRORS_H */ -- cgit v1.1