提交 4c4a6a7c 编写于 作者: A AlekseyTs

NativeClient - move localizable strings to resource string table. (changeset 1342509)

上级 06979fd8
B// Microsoft Visual C++ generated resource script.
......
......@@ -4,6 +4,7 @@
#include "logging.h"
#include <memory>
#include <string>
#include "UIStrings.h"
using namespace std;
......@@ -20,16 +21,16 @@ bool HaveLogFile()
wstring GetResourceString(UINT loadResource)
{
extern HINSTANCE g_hinstMessages;
LPWSTR tempStr;
int result = LoadString(g_hinstMessages, loadResource, (LPWSTR)&tempStr, 0);
extern HINSTANCE g_hinstMessages;
LPWSTR tempStr;
int result = LoadString(g_hinstMessages, loadResource, (LPWSTR)&tempStr, 0);
if (result > 0)
{
return wstring(tempStr);
}
if (result > 0)
{
return wstring(tempStr, result);
}
return wstring(L"");
return wstring(L"");
}
......@@ -80,6 +81,11 @@ static void LogPrefix()
fprintf(logFile, "CLI PID=%u TID=%u Ticks=%u: ", GetCurrentProcessId(), GetCurrentThreadId(), GetTickCount());
}
void Log(UINT loadResource)
{
Log(GetResourceString(loadResource).c_str());
}
void Log(LPCWSTR message)
{
if (logFile != nullptr)
......@@ -102,6 +108,14 @@ static void vLogFormatted(LPCWSTR message, va_list varargs)
}
}
void LogFormatted(UINT loadResource, ...)
{
va_list varargs;
va_start(varargs, loadResource);
LogFormatted(GetResourceString(loadResource).c_str(), varargs);
va_end(varargs);
}
void LogFormatted(LPCWSTR message, ...)
{
if (logFile != nullptr)
......@@ -116,69 +130,87 @@ void LogFormatted(LPCWSTR message, ...)
void LogTime()
{
if (logFile != nullptr)
{
SYSTEMTIME time;
GetLocalTime(&time);
LogFormatted(L"Local time = %02d:%02d:%02d.%03d", time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
}
if (logFile != nullptr)
{
SYSTEMTIME time;
GetLocalTime(&time);
LogFormatted(IDS_FormattedLocalTime, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
}
}
void LogWin32Error(UINT loadResource)
{
LogFormatted(GetResourceString(loadResource).c_str());
}
void LogWin32Error(LPCWSTR message)
{
LogFormatted(L"Win32 Error Code %X during %ws", GetLastError(), message);
LogFormatted(IDS_LogWin32Error, GetLastError(), message);
}
void Exit(int exitCode)
{
LogTime();
LogFormatted(L"Exiting with code %d", exitCode);
exit(exitCode);
LogTime();
LogFormatted(IDS_ExitingWithCode, exitCode);
exit(exitCode);
}
void FailWithGetLastError(LPWSTR optionalPrefix)
void FailWithGetLastError(UINT loadResource)
{
LPWSTR errorMsg;
if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
nullptr,
GetLastError(),
0,
(LPWSTR) &errorMsg,
0,
nullptr))
{
errorMsg = L"";
}
// TODO: How should this error be localized? Is there more information we could output for debugging purposes?
if (optionalPrefix == nullptr)
optionalPrefix = L"";
FailWithGetLastError(GetResourceString(loadResource).c_str());
}
wstring buffer(L"Internal Compiler Client Error: ");
buffer += optionalPrefix;
buffer += L" ";
buffer += errorMsg;
void FailWithGetLastError(LPCWSTR optionalPrefix)
{
LPWSTR errorMsg;
if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
nullptr,
GetLastError(),
0,
(LPWSTR)&errorMsg,
0,
nullptr))
{
errorMsg = L"";
}
// TODO: How should this error be localized? Is there more information we could output for debugging purposes?
if (optionalPrefix == nullptr)
optionalPrefix = L"";
wstring buffer = GetResourceString(IDS_InternalCompilerClientErrorPrefix);
buffer += optionalPrefix;
buffer += L" ";
buffer += errorMsg;
Log(buffer.c_str());
LocalFree(errorMsg);
throw FatalError(move(buffer));
}
Log(buffer.c_str());
LocalFree(errorMsg);
throw FatalError(move(buffer));
void FailFormatted(UINT loadResource, ...)
{
va_list varargs;
va_start(varargs, loadResource);
FailFormatted(GetResourceString(loadResource).c_str(), varargs);
va_end(varargs);
}
void FailFormatted(LPCWSTR message, ...)
{
va_list varargs;
va_start(varargs, message);
va_list varargs;
va_start(varargs, message);
wstring fullMessage(L"Internal Compiler Client Error: ");
wstring fullMessage = GetResourceString(IDS_InternalCompilerClientErrorPrefix);
int needed = _vscwprintf(message, varargs);
auto buffer = std::make_unique <WCHAR []>(needed + 1);
_vsnwprintf_s(buffer.get(), needed + 1, _TRUNCATE, message, varargs);
va_end(varargs);
int needed = _vscwprintf(message, varargs);
auto buffer = std::make_unique <WCHAR[]>(needed + 1);
_vsnwprintf_s(buffer.get(), needed + 1, _TRUNCATE, message, varargs);
va_end(varargs);
fullMessage += buffer.release();
fullMessage += L"\r\n";
fullMessage += buffer.release();
fullMessage += L"\r\n";
Log(fullMessage.c_str());
throw FatalError(move(fullMessage));
Log(fullMessage.c_str());
throw FatalError(move(fullMessage));
}
\ No newline at end of file
......@@ -20,9 +20,14 @@ bool HaveLogFile();
std::wstring GetResourceString(UINT);
bool GetEnvVar(LPCWSTR name, std::wstring &value);
void InitializeLogging();
void Log(UINT loadResource);
void Log(LPCWSTR message);
void LogFormatted(UINT loadResource, ...);
void LogFormatted(LPCWSTR message, ...);
void LogTime();
void LogWin32Error(UINT loadResource);
void LogWin32Error(LPCWSTR message);
void FailWithGetLastError(LPWSTR optionalPrefix = nullptr);
void FailWithGetLastError(UINT loadResource);
void FailWithGetLastError(LPCWSTR optionalPrefix = nullptr);
void FailFormatted(UINT loadResource, ...);
void FailFormatted(LPCWSTR message, ...);
\ No newline at end of file
......@@ -38,7 +38,7 @@ wstring GetCurrentDirectory()
int sizeNeeded = GetCurrentDirectory(0, nullptr);
if (0 == sizeNeeded)
{
FailWithGetLastError(L"GetCurrentDirectory failed");
FailWithGetLastError(IDS_GetCurrentDirectoryFailed);
}
wstring result;
......@@ -47,7 +47,7 @@ wstring GetCurrentDirectory()
auto written = (int)GetCurrentDirectory(sizeNeeded, &result[0]);
if (written == 0 || written > sizeNeeded)
{
FailWithGetLastError(L"GetCurrentDirectory failed");
FailWithGetLastError(IDS_GetCurrentDirectoryFailed);
}
result.resize(written);
......@@ -61,7 +61,7 @@ std::unique_ptr<LPCWSTR, decltype(&::LocalFree)> GetCommandLineArgs(int &argsCou
auto args = const_cast<LPCWSTR*>(CommandLineToArgvW(GetCommandLine(), &argsCount));
if (args == nullptr)
{
FailWithGetLastError(L"CommandLineToArgvW failed");
FailWithGetLastError(IDS_CommandLineToArgvWFailed);
}
return unique_ptr<LPCWSTR, decltype(&::LocalFree)>(args, ::LocalFree);
}
......@@ -154,11 +154,11 @@ HANDLE ConnectToProcess(DWORD processID, int timeoutMs)
HANDLE pipeHandle = OpenPipe(szPipeName, timeoutMs);
if (pipeHandle != INVALID_HANDLE_VALUE)
{
Log(L"Sucessfully opened pipe");
Log(IDS_SucessfullyOpenedPipe);
return pipeHandle;
}
Log(L"Failed to open pipe - can try another server process.");
Log(IDS_FailedToOpenPipe);
return NULL;
}
......@@ -189,17 +189,17 @@ bool TryCompile(HANDLE pipeHandle,
RealPipe wrapper(pipeHandle);
if (!request.WriteToPipe(wrapper))
{
Log(L"Failed to write request - can try another server process.");
Log(IDS_FailedToWriteRequest);
return false;
}
Log(L"Successfully wrote request.");
Log(IDS_SuccessfullyWroteRequest);
// We should expect a completed response since
// the only other option is a an erroroneous response
// which will generate an exception.
response = ReadResponse(wrapper);
Log(L"Successfully read response.");
Log(IDS_SuccessfullyReadResponse);
// We got a response.
return true;
......@@ -208,7 +208,7 @@ bool TryCompile(HANDLE pipeHandle,
// Get the process ids of all processes on the system.
bool GetAllProcessIds(vector<DWORD> &processes)
{
Log(L"Enumerating all process IDs");
Log(IDS_EnumeratingProcessIDs);
processes.resize(64);
DWORD bytesWritten;
......@@ -273,7 +273,7 @@ DWORD CreateNewServerProcess(LPCWSTR executablePath)
PROCESS_INFORMATION processInfo;
BOOL success;
LogFormatted(L"Attempting to create process '%ws'", executablePath);
LogFormatted(IDS_AttemptingToCreateProcess, executablePath);
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
......@@ -298,7 +298,7 @@ DWORD CreateNewServerProcess(LPCWSTR executablePath)
nullptr, 0,
nullptr, 0)))
{
FailFormatted(L"Couldn't split the process executable path: %d", err);
FailFormatted(IDS_SplitProcessPathError, err);
}
auto createPath = make_unique<wchar_t[]>(MAX_PATH);
......@@ -309,7 +309,7 @@ DWORD CreateNewServerProcess(LPCWSTR executablePath)
nullptr,
nullptr)))
{
FailFormatted(L"Couldn't make the new process path: %d", err);
FailFormatted(IDS_MakeNewProcessPathError, err);
}
success = CreateProcess(executablePath,
......@@ -326,14 +326,14 @@ DWORD CreateNewServerProcess(LPCWSTR executablePath)
if (success)
{
// We don't need the process and thread handles.
LogFormatted(L"Successfully created process with process id %d", processInfo.dwProcessId);
LogFormatted(IDS_CreatedProcess, processInfo.dwProcessId);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
return processInfo.dwProcessId;
}
else
{
LogWin32Error(L"Creating process");
LogWin32Error(IDS_CreatingProcess);
return 0;
}
}
......@@ -404,19 +404,19 @@ HANDLE TryExistingProcesses(LPCWSTR expectedProcessName)
HANDLE tempHandle;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tempHandle))
{
FailWithGetLastError(L"Couldn't get current process token:");
FailWithGetLastError(IDS_GetCurrentProcessTokenFailed);
}
SmartHandle tokenHandle(tempHandle);
if (!GetTokenUserAndElevation(tokenHandle.get(), userInfo, elevationInfo))
{
FailWithGetLastError(L"Couldn't get user token information:");
FailWithGetLastError(IDS_GetUserTokenFailed);
}
vector<DWORD> processes;
if (GetAllProcessIds(processes))
{
LogFormatted(L"Found %d processes", processes.size());
LogFormatted(IDS_FoundProcesses, processes.size());
// Check each process to find one with the right name and user
for (auto processId : processes)
......@@ -431,7 +431,7 @@ HANDLE TryExistingProcesses(LPCWSTR expectedProcessName)
// Check if the process is owned by the same user
&& ProcessHasSameUserAndElevation(processHandle.get(), userInfo.get(), elevationInfo.get()))
{
LogFormatted(L"Found process with id %d", processId);
LogFormatted(IDS_FoundProcess, processId);
HANDLE pipeHandle = ConnectToProcess(processId, TimeOutMsExistingProcess);
if (pipeHandle != NULL)
{
......@@ -515,14 +515,14 @@ CompletedResponse Run(
if (!GetExpectedProcessPath(expectedProcessPath, MAX_PATH))
{
FailWithGetLastError(L"GetExpectedProcessPath failed");
FailWithGetLastError(IDS_GetExpectedProcessPathFailed);
}
// First attempt to grab the mutex
wstring mutexName(expectedProcessPath);
replace(mutexName.begin(), mutexName.end(), L'\\', L'/');
Log(L"Creating mutex.");
Log(IDS_CreatingMutex);
SmartMutex createProcessMutex(mutexName.c_str());
......@@ -539,13 +539,13 @@ CompletedResponse Run(
if (createProcessMutex.HoldsMutex())
{
// Check for already running processes in case someone came in before us
Log(L"Trying existing processes.");
Log(IDS_TryingExistingProcesses);
pipeHandle.reset(TryExistingProcesses(expectedProcessPath));
if (pipeHandle != nullptr)
{
Log(L"Connected, releasing mutex.");
Log(IDS_Connected);
createProcessMutex.release();
Log(L"Compiling.");
Log(IDS_Compiling);
CompletedResponse response;
if (TryCompile(pipeHandle.get(),
......@@ -559,22 +559,22 @@ CompletedResponse Run(
return response;
}
Log(L"Compilation failed with existing process, retrying once.");
Log(IDS_ExistingProcessFailedRetrying);
}
else
{
Log(L"No success with existing processes - try creating a new one.");
Log(IDS_CreatingNewProcess);
processId = CreateNewServerProcess(expectedProcessPath);
if (processId != 0)
{
LogFormatted(L"Connecting to newly created process id %d", processId);
LogFormatted(IDS_ConnectingToNewProcess, processId);
pipeHandle.reset(ConnectToProcess(processId, TimeOutMsNewProcess));
if (pipeHandle != nullptr)
{
// Let everyone else access our process
Log(L"Connected, releasing mutex.");
Log(IDS_Connected);
createProcessMutex.release();
Log(L"Compiling.");
Log(IDS_Compiling);
CompletedResponse response;
if (TryCompile(pipeHandle.get(),
language,
......@@ -589,7 +589,7 @@ CompletedResponse Run(
}
}
Log(L"No success with created process, retrying once.");
Log(IDS_CreatedProcessFailedRetrying);
}
createProcessMutex.release();
......@@ -600,16 +600,16 @@ CompletedResponse Run(
}
// Try one time without a mutex
Log(L"Trying without mutex");
Log(IDS_TryingWithoutMutex);
processId = CreateNewServerProcess(expectedProcessPath);
if (processId != 0)
{
LogFormatted(L"Connecting to newly created process id %d", processId);
LogFormatted(IDS_ConnectingToNewProcess, processId);
pipeHandle.reset(ConnectToProcess(processId, TimeOutMsNewProcess));
if (pipeHandle != nullptr)
{
// Let everyone else access our process
Log(L"Connected to new process.");
Log(IDS_ConnectedNewProcess);
CompletedResponse response;
if (TryCompile(pipeHandle.get(),
language,
......@@ -632,27 +632,27 @@ CompletedResponse Run(
// pipe
if (pipeHandle == nullptr)
{
FailFormatted(L"Could not connect to server pipe");
FailFormatted(IDS_ConnectToServerPipeFailed);
}
else if (processId != 0)
{
SmartHandle process(OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId));
if (process == NULL)
{
FailFormatted(L"Could not find server process -- compiler may have disconnected or crashed due to error.");
FailFormatted(IDS_ServerIsLost);
}
else
{
DWORD exitCode;
if (GetExitCodeProcess(process.get(), &exitCode))
{
FailFormatted(L"Server process has crashed with error code: %d\n", exitCode);
FailFormatted(IDS_ServerCrashed, exitCode);
}
}
}
else
{
FailWithGetLastError(L"Unknown failure");
FailWithGetLastError(IDS_UnknownFailure);
}
// Unreachable
......
#include "stdafx.h"
#include "pipe_utils.h"
#include "logging.h"
#include "UIStrings.h"
using namespace std;
RealPipe::RealPipe(HANDLE pipeHandle)
{
this->pipeHandle = pipeHandle;
this->pipeHandle = pipeHandle;
}
bool RealPipe::Write(LPCVOID data, unsigned toWrite)
{
DWORD written;
BOOL success = WriteFile(this->pipeHandle, data, toWrite, &written, nullptr);
if (!success)
{
FailWithGetLastError(L"WriteFile on pipe failed");
}
else if (written != toWrite)
{
FailFormatted(L"WriteFile on pipe only partially completed: toWrite %d, written %d\n", toWrite, written);
}
return true;
DWORD written;
BOOL success = WriteFile(this->pipeHandle, data, toWrite, &written, nullptr);
if (!success)
{
FailWithGetLastError(IDS_WriteFileOnPipeFailed);
}
else if (written != toWrite)
{
FailFormatted(IDS_WriteFileOnPipeIncomplete, toWrite, written);
}
return true;
}
#pragma warning(suppress: 6101)
bool RealPipe::Read(_Out_ LPVOID data, unsigned toRead)
{
if (toRead == 0)
return true;
if (toRead == 0)
return true;
DWORD read;
BOOL success = ReadFile(this->pipeHandle, data, toRead, &read, nullptr);
if (!success)
{
FailWithGetLastError(L"ReadFile on pipe failed");
}
else if (read != toRead)
{
FailFormatted(L"ReadFile on pipe only partially completed: toRead %d, read %d\n", toRead, read);
}
return true;
DWORD read;
BOOL success = ReadFile(this->pipeHandle, data, toRead, &read, nullptr);
if (!success)
{
FailWithGetLastError(IDS_ReadFileOnPipeFailed);
}
else if (read != toRead)
{
FailFormatted(IDS_ReadFileOnPipeIncomplete, toRead, read);
}
return true;
}
const DWORD MinConnectionAttempts = 3; // Always make at least three attempts (matters when each attempt takes a long time (under load)).
......@@ -49,71 +50,71 @@ const DWORD MinConnectionAttempts = 3; // Always make at least three atte
// Retry up to "retryOpenTimeoutMs" milliseconds.
HANDLE OpenPipe(LPTSTR szPipeName, DWORD retryOpenTimeoutMs)
{
// Try up to retryOpenTimeoutMs if:
// PIPE_BUSY occurs
// FILE_NOT_FOUND occurs .
// Other errors causes us to fail immediately.
// Try up to retryOpenTimeoutMs if:
// PIPE_BUSY occurs
// FILE_NOT_FOUND occurs .
// Other errors causes us to fail immediately.
#pragma warning(suppress: 28159)
DWORD startTicks = GetTickCount();
DWORD currentTicks = startTicks;
// Loop 3 times or until we hit the timeout, whichever is LONGER.
for (int attempt = 0; attempt < MinConnectionAttempts || currentTicks - startTicks < retryOpenTimeoutMs; attempt++)
{
LogFormatted(L"Attempt to open named pipe '%ws'", szPipeName);
DWORD startTicks = GetTickCount();
DWORD currentTicks = startTicks;
// Loop 3 times or until we hit the timeout, whichever is LONGER.
for (int attempt = 0; attempt < MinConnectionAttempts || currentTicks - startTicks < retryOpenTimeoutMs; attempt++)
{
LogFormatted(IDS_AttemptToOpenNamedPipe, szPipeName);
HANDLE pipeHandle = CreateFile(
szPipeName,
GENERIC_READ | GENERIC_WRITE,
0, // share mode
NULL, // security attributes
OPEN_EXISTING,
0, // default attributes
NULL); // no template file
HANDLE pipeHandle = CreateFile(
szPipeName,
GENERIC_READ | GENERIC_WRITE,
0, // share mode
NULL, // security attributes
OPEN_EXISTING,
0, // default attributes
NULL); // no template file
if (pipeHandle != INVALID_HANDLE_VALUE)
{
LogFormatted(L"Successfully opened pipe '%ws' as handle %d", szPipeName, pipeHandle);
if (pipeHandle != INVALID_HANDLE_VALUE)
{
LogFormatted(IDS_OpenedPipe, szPipeName, pipeHandle);
return pipeHandle;
}
return pipeHandle;
}
// Something went wrong. If we couldn't find the pipe, then possibly the process is still starting.
DWORD errorCode = GetLastError();
// Something went wrong. If we couldn't find the pipe, then possibly the process is still starting.
DWORD errorCode = GetLastError();
if (errorCode == ERROR_PIPE_BUSY)
{
Log(L"Named pipe is busy.");
// All pipe instances are busy. Wait for one to become available.
if (!WaitNamedPipe(szPipeName, retryOpenTimeoutMs))
{
Log(L"Named pipe wait failed.");
//EDMAURER the wait timed out. Give up.
return INVALID_HANDLE_VALUE;
}
}
else if (errorCode == ERROR_FILE_NOT_FOUND)
{
// Perhaps the server is still starting. Give it just a fraction of a second to start.
Log(L"Pipe not found. Sleeping.");
Sleep(100);
}
else
{
LogWin32Error(L"Opening named pipe");
return INVALID_HANDLE_VALUE;
}
if (errorCode == ERROR_PIPE_BUSY)
{
Log(IDS_NamedPipeBusy);
// All pipe instances are busy. Wait for one to become available.
if (!WaitNamedPipe(szPipeName, retryOpenTimeoutMs))
{
Log(IDS_NamedPipeWaitFailed);
//EDMAURER the wait timed out. Give up.
return INVALID_HANDLE_VALUE;
}
}
else if (errorCode == ERROR_FILE_NOT_FOUND)
{
// Perhaps the server is still starting. Give it just a fraction of a second to start.
Log(IDS_PipeNotFound);
Sleep(100);
}
else
{
LogWin32Error(IDS_OpeningNamedPipe);
return INVALID_HANDLE_VALUE;
}
#pragma warning(suppress: 28159)
currentTicks = GetTickCount();
if (startTicks > currentTicks)
{
// Reset startTicks on overflow
startTicks = 0;
}
}
currentTicks = GetTickCount();
if (startTicks > currentTicks)
{
// Reset startTicks on overflow
startTicks = 0;
}
}
#pragma warning(suppress: 28159)
LogFormatted(L"Pipe not found after retrying for %d ms.", GetTickCount() - startTicks);
return INVALID_HANDLE_VALUE;
LogFormatted(IDS_PipeFindRetryFailed, GetTickCount() - startTicks);
return INVALID_HANDLE_VALUE;
}
\ No newline at end of file
......@@ -2,6 +2,7 @@
#include "pipe_utils.h"
#include "protocol.h"
#include "logging.h"
#include "UIStrings.h"
using namespace std;
......@@ -115,7 +116,7 @@ bool Request::WriteToPipe(IPipe& pipe)
auto currentSize = static_cast<unsigned int>(buffer.size());
auto bufferData = buffer.data();
LogFormatted(L"Writing request of size %u", currentSize);
LogFormatted(IDS_WritingRequest, currentSize);
return pipe.Write(&currentSize, sizeof(currentSize))
&& pipe.Write(bufferData, currentSize);
}
......@@ -155,17 +156,17 @@ wstring ReadStringFromPipe(IPipe& pipe)
int stringLength;
if (!pipe.Read(&stringLength, sizeof(stringLength)))
{
FailFormatted(L"Pipe read failed\n");
FailFormatted(IDS_PipeReadFailed);
}
LogFormatted(L"String length = %d", stringLength);
LogFormatted(IDS_StringLength, stringLength);
wstring string;
string.resize(stringLength);
if (!pipe.Read(&string[0], stringLength * sizeof(wchar_t)))
{
FailFormatted(L"Pipe read failed\n");
FailFormatted(IDS_PipeReadFailed);
}
return string;
......@@ -176,12 +177,12 @@ CompletedResponse ReadCompletedResponse(IPipe& pipe)
int exitCode;
if (!pipe.Read(&exitCode, sizeof(exitCode)))
{
FailFormatted(L"Pipe read failed\n");
FailFormatted(IDS_PipeReadFailed);
}
bool utf8output;
if (!pipe.Read(&utf8output, sizeof(utf8output)))
{
FailFormatted(L"Pipe read failed\n");
FailFormatted(IDS_PipeReadFailed);
}
auto output = ReadStringFromPipe(pipe);
auto errorOutput = ReadStringFromPipe(pipe);
......@@ -193,34 +194,33 @@ CompletedResponse ReadCompletedResponse(IPipe& pipe)
// received, throws a FatalError exception.
CompletedResponse ReadResponse(IPipe& pipe)
{
Log(L"Reading response");
Log(IDS_ReadingResponse);
int sizeInBytes;
Response::ResponseType responseType;
if (!pipe.Read(&sizeInBytes, sizeof(sizeInBytes)))
{
FailFormatted(L"Pipe read failed\n");
FailFormatted(IDS_PipeReadFailed);
}
LogFormatted(L"Response has %d bytes", sizeInBytes);
LogFormatted(IDS_ResponseSize, sizeInBytes);
if (!pipe.Read(&responseType, sizeof(responseType)))
{
FailFormatted(L"Pipe read failed\n");
FailFormatted(IDS_PipeReadFailed);
}
LogFormatted(L"Response type: %d", responseType);
LogFormatted(IDS_ResponseType, responseType);
switch (responseType)
{
case Response::MISMATCHED_VERSION:
FailWithGetLastError(L"Received mismatched version response from server. "
L"Are your client and server binaries out of sync?");
break;
FailWithGetLastError(IDS_VersionMismatch);
break;
case Response::COMPLETED:
break;
break;
default:
FailWithGetLastError(L"Received unknown response from server");
FailWithGetLastError(IDS_UnknownResponse);
break;
}
return ReadCompletedResponse(pipe);
return ReadCompletedResponse(pipe);
}
\ No newline at end of file
#include "stdafx.h"
#include "smart_resources.h"
#include "UIStrings.h"
void SmartHandle::close(HANDLE handle)
{
......@@ -52,7 +53,7 @@ SmartMutex::SmartMutex(LPCWSTR mutexName)
// related. We can only log the error and continue without it.
if (this->handle == nullptr)
{
LogWin32Error(L"Failure to create mutex");
LogWin32Error(IDS_CreateMutexFailed);
}
this->holdsMutex = this->handle != nullptr && GetLastError() == ERROR_SUCCESS;
......@@ -65,27 +66,27 @@ bool SmartMutex::HoldsMutex()
bool SmartMutex::Wait(const int waitTime)
{
Log(L"Waiting for mutex.");
Log(IDS_WaitingForMutex);
auto mutexError = WaitForSingleObject(this->handle, waitTime);
this->holdsMutex = false;
switch (mutexError)
{
case WAIT_ABANDONED:
Log(L"Acquired mutex, but mutex was previously abandoned");
Log(IDS_AcquiredAbandonedMutex);
this->holdsMutex = true;
break;
case WAIT_OBJECT_0:
Log(L"Acquired mutex.");
Log(IDS_AcquiredMutex);
this->holdsMutex = true;
break;
case WAIT_TIMEOUT:
Log(L"Waiting for mutex timed out");
Log(IDS_WaitingMutexTimeout);
break;
case WAIT_FAILED:
LogWin32Error(L"Waiting on the mutex failed");
LogWin32Error(IDS_WaitingMutexFailed);
break;
default:
LogFormatted(L"Unknown WaitForSingleObject mutex failure %d, return code not documented\n", mutexError);
LogFormatted(IDS_WaitingMutexUnknownFailure, mutexError);
break;
}
return this->holdsMutex;
......@@ -100,22 +101,22 @@ void SmartMutex::release()
{
if (handle != nullptr && holdsMutex)
{
if (!ReleaseMutex(handle))
{
Log(L"Error releasing mutex");
}
else
{
holdsMutex = false;
}
if (!ReleaseMutex(handle))
{
Log(IDS_ReleaseMutexFailed);
}
else
{
holdsMutex = false;
}
}
}
SmartMutex::~SmartMutex()
{
release();
if (handle != nullptr)
{
CloseHandle(handle);
}
release();
if (handle != nullptr)
{
CloseHandle(handle);
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册