Blame src/win32/error.c

Packit ae9e2a
/*
Packit ae9e2a
 * Copyright (C) the libgit2 contributors. All rights reserved.
Packit ae9e2a
 *
Packit ae9e2a
 * This file is part of libgit2, distributed under the GNU GPL v2 with
Packit ae9e2a
 * a Linking Exception. For full terms see the included COPYING file.
Packit ae9e2a
 */
Packit ae9e2a
Packit ae9e2a
#include "common.h"
Packit ae9e2a
#include "error.h"
Packit ae9e2a
#include "utf-conv.h"
Packit ae9e2a
Packit ae9e2a
#ifdef GIT_WINHTTP
Packit ae9e2a
# include <winhttp.h>
Packit ae9e2a
#endif
Packit ae9e2a
Packit ae9e2a
char *git_win32_get_error_message(DWORD error_code)
Packit ae9e2a
{
Packit ae9e2a
	LPWSTR lpMsgBuf = NULL;
Packit ae9e2a
	HMODULE hModule = NULL;
Packit ae9e2a
	char *utf8_msg = NULL;
Packit ae9e2a
	DWORD dwFlags =
Packit ae9e2a
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS;
Packit ae9e2a
Packit ae9e2a
	if (!error_code)
Packit ae9e2a
		return NULL;
Packit ae9e2a
Packit ae9e2a
#ifdef GIT_WINHTTP
Packit ae9e2a
	/* Errors raised by WinHTTP are not in the system resource table */
Packit ae9e2a
	if (error_code >= WINHTTP_ERROR_BASE &&
Packit ae9e2a
		error_code <= WINHTTP_ERROR_LAST)
Packit ae9e2a
		hModule = GetModuleHandleW(L"winhttp");
Packit ae9e2a
#endif
Packit ae9e2a
Packit ae9e2a
	GIT_UNUSED(hModule);
Packit ae9e2a
Packit ae9e2a
	if (hModule)
Packit ae9e2a
		dwFlags |= FORMAT_MESSAGE_FROM_HMODULE;
Packit ae9e2a
	else
Packit ae9e2a
		dwFlags |= FORMAT_MESSAGE_FROM_SYSTEM;
Packit ae9e2a
Packit ae9e2a
	if (FormatMessageW(dwFlags, hModule, error_code,
Packit ae9e2a
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
Packit ae9e2a
		(LPWSTR)&lpMsgBuf, 0, NULL)) {
Packit ae9e2a
		/* Convert the message to UTF-8. If this fails, we will
Packit ae9e2a
		 * return NULL, which is a condition expected by the caller */
Packit ae9e2a
		if (git__utf16_to_8_alloc(&utf8_msg, lpMsgBuf) < 0)
Packit ae9e2a
			utf8_msg = NULL;
Packit ae9e2a
Packit ae9e2a
		LocalFree(lpMsgBuf);
Packit ae9e2a
	}
Packit ae9e2a
Packit ae9e2a
	return utf8_msg;
Packit ae9e2a
}