error: De-duplicate code creating Error objects

Duplicated when commit 680d16d added error_set_errno(), and again when
commit 20840d4 added error_set_win32().

Make the original copy in error_set() reusable by factoring out
error_setv(), then rewrite error_set_errno() and error_set_win32() on
top of it.

Backports commit 552375088a832fd5945ede92d01f98977b4eca13 from qemu
This commit is contained in:
Markus Armbruster 2018-02-15 11:23:02 -05:00 committed by Lioncash
parent 191786d055
commit c2a61848d6
No known key found for this signature in database
GPG key ID: 4E3C3CC1031BA9C7

View file

@ -21,10 +21,10 @@ struct Error
Error *error_abort; Error *error_abort;
void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...) static void error_setv(Error **errp, ErrorClass err_class,
const char *fmt, va_list ap)
{ {
Error *err; Error *err;
va_list ap;
int saved_errno = errno; int saved_errno = errno;
if (errp == NULL) { if (errp == NULL) {
@ -34,9 +34,7 @@ void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...)
err = g_malloc0(sizeof(*err)); err = g_malloc0(sizeof(*err));
va_start(ap, fmt);
err->msg = g_strdup_vprintf(fmt, ap); err->msg = g_strdup_vprintf(fmt, ap);
va_end(ap);
err->err_class = err_class; err->err_class = err_class;
if (errp == &error_abort) { if (errp == &error_abort) {
@ -48,38 +46,36 @@ void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...)
errno = saved_errno; errno = saved_errno;
} }
void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
error_setv(errp, err_class, fmt, ap);
va_end(ap);
}
void error_set_errno(Error **errp, int os_errno, ErrorClass err_class, void error_set_errno(Error **errp, int os_errno, ErrorClass err_class,
const char *fmt, ...) const char *fmt, ...)
{ {
Error *err;
char *msg1;
va_list ap; va_list ap;
char *msg;
int saved_errno = errno; int saved_errno = errno;
if (errp == NULL) { if (errp == NULL) {
return; return;
} }
assert(*errp == NULL);
err = g_malloc0(sizeof(*err));
va_start(ap, fmt); va_start(ap, fmt);
msg1 = g_strdup_vprintf(fmt, ap); error_setv(errp, err_class, fmt, ap);
if (os_errno != 0) {
err->msg = g_strdup_printf("%s: %s", msg1, strerror(os_errno));
g_free(msg1);
} else {
err->msg = msg1;
}
va_end(ap); va_end(ap);
err->err_class = err_class;
if (errp == &error_abort) { if (os_errno != 0) {
// abort(); msg = (*errp)->msg;
(*errp)->msg = g_strdup_printf("%s: %s", msg, strerror(os_errno));
g_free(msg);
} }
*errp = err;
errno = saved_errno; errno = saved_errno;
} }