Path: blob/21.2-virgl/src/gallium/drivers/swr/rasterizer/common/os.cpp
4574 views
/****************************************************************************1* Copyright (C) 2017 Intel Corporation. All Rights Reserved.2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20* IN THE SOFTWARE.21****************************************************************************/2223#include "common/os.h"24#include <vector>25#include <array>26#include <sstream>2728#if defined(_WIN32)29#include <shlobj.h>30#endif // Windows3132#if defined(__APPLE__) || defined(FORCE_LINUX) || defined(__linux__) || defined(__gnu_linux__)33#include <pthread.h>34#endif // Linux3536#if defined(_MSC_VER)37static const DWORD MS_VC_EXCEPTION = 0x406D1388;3839#pragma pack(push, 8)40typedef struct tagTHREADNAME_INFO41{42DWORD dwType; // Must be 0x1000.43LPCSTR szName; // Pointer to name (in user addr space).44DWORD dwThreadID; // Thread ID (-1=caller thread).45DWORD dwFlags; // Reserved for future use, must be zero.46} THREADNAME_INFO;47#pragma pack(pop)4849void LegacySetThreadName(const char* pThreadName)50{51THREADNAME_INFO info;52info.dwType = 0x1000;53info.szName = pThreadName;54info.dwThreadID = GetCurrentThreadId();55info.dwFlags = 0;5657if (!IsDebuggerPresent())58{59// No debugger attached to interpret exception, no need to actually do it60return;61}6263#pragma warning(push)64#pragma warning(disable : 6320 6322)65__try66{67RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);68}69__except (EXCEPTION_EXECUTE_HANDLER)70{71}72#pragma warning(pop)73}74#endif // _WIN327576void SWR_API SetCurrentThreadName(const char* pThreadName)77{78#if defined(_MSC_VER)79// The SetThreadDescription API was brought in version 1607 of Windows 10.80typedef HRESULT(WINAPI * PFNSetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);81// The SetThreadDescription API works even if no debugger is attached.82auto pfnSetThreadDescription = reinterpret_cast<PFNSetThreadDescription>(83GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetThreadDescription"));8485if (!pfnSetThreadDescription)86{87// try KernelBase.dll88pfnSetThreadDescription = reinterpret_cast<PFNSetThreadDescription>(89GetProcAddress(GetModuleHandleA("KernelBase.dll"), "SetThreadDescription"));90}9192if (pfnSetThreadDescription)93{94std::string utf8Name = pThreadName;95std::wstring wideName;96wideName.resize(utf8Name.size() + 1);97swprintf_s(&(wideName.front()), wideName.size(), L"%S", utf8Name.c_str());98HRESULT hr = pfnSetThreadDescription(GetCurrentThread(), wideName.c_str());99SWR_ASSERT(SUCCEEDED(hr), "Failed to set thread name to %s", pThreadName);100101// Fall through - it seems like some debuggers only recognize the exception102}103104// Fall back to exception based hack105LegacySetThreadName(pThreadName);106#endif // _WIN32107108#if defined(FORCE_LINUX) || defined(__linux__) || defined(__gnu_linux__)109pthread_setname_np(pthread_self(), pThreadName);110#endif // Linux111}112113#if defined(__APPLE__) || defined(FORCE_LINUX) || defined(__linux__) || defined(__gnu_linux__)114static void115SplitString(std::vector<std::string>& out_segments, const std::string& input, char splitToken)116{117out_segments.clear();118119std::istringstream f(input);120std::string s;121while (std::getline(f, s, splitToken))122{123if (s.size())124{125out_segments.push_back(s);126}127}128}129#endif // Unix130131void SWR_API CreateDirectoryPath(const std::string& path)132{133#if defined(_WIN32)134SHCreateDirectoryExA(nullptr, path.c_str(), nullptr);135#endif // Windows136137#if defined(__APPLE__) || defined(FORCE_LINUX) || defined(__linux__) || defined(__gnu_linux__)138std::vector<std::string> pathSegments;139SplitString(pathSegments, path, '/');140141std::string tmpPath;142for (auto const& segment : pathSegments)143{144tmpPath.push_back('/');145tmpPath += segment;146147int result = mkdir(tmpPath.c_str(), 0777);148if (result == -1 && errno != EEXIST)149{150break;151}152}153#endif // Unix154}155156/// Execute Command (block until finished)157/// @returns process exit value158int SWR_API ExecCmd(const std::string& cmd, ///< (In) Command line string159const char* pOptEnvStrings, ///< (Optional In) Environment block for new process160std::string* pOptStdOut, ///< (Optional Out) Standard Output text161std::string* pOptStdErr, ///< (Optional Out) Standard Error text162const std::string* pOptStdIn) ///< (Optional In) Standard Input text163{164int rvalue = -1;165166#if defined(_WIN32)167struct WinPipe168{169HANDLE hRead;170HANDLE hWrite;171};172std::array<WinPipe, 3> hPipes = {};173174SECURITY_ATTRIBUTES saAttr = {sizeof(SECURITY_ATTRIBUTES)};175saAttr.bInheritHandle = TRUE; // Pipe handles are inherited by child process.176saAttr.lpSecurityDescriptor = NULL;177178{179bool bFail = false;180for (WinPipe& p : hPipes)181{182if (!CreatePipe(&p.hRead, &p.hWrite, &saAttr, 0))183{184bFail = true;185}186}187188if (bFail)189{190for (WinPipe& p : hPipes)191{192CloseHandle(p.hRead);193CloseHandle(p.hWrite);194}195return rvalue;196}197}198199STARTUPINFOA StartupInfo{};200StartupInfo.cb = sizeof(STARTUPINFOA);201StartupInfo.dwFlags = STARTF_USESTDHANDLES;202StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;203StartupInfo.wShowWindow = SW_HIDE;204if (pOptStdIn)205{206StartupInfo.hStdInput = hPipes[0].hRead;207}208StartupInfo.hStdOutput = hPipes[1].hWrite;209StartupInfo.hStdError = hPipes[2].hWrite;210PROCESS_INFORMATION procInfo{};211212// CreateProcess can modify the string213std::string local_cmd = cmd;214215BOOL ProcessValue = CreateProcessA(NULL,216(LPSTR)local_cmd.c_str(),217NULL,218NULL,219TRUE,2200,221(LPVOID)pOptEnvStrings,222NULL,223&StartupInfo,224&procInfo);225226if (ProcessValue && procInfo.hProcess)227{228auto ReadFromPipe = [](HANDLE hPipe, std::string* pOutStr) {229char buf[1024];230DWORD dwRead = 0;231DWORD dwAvail = 0;232while (true)233{234if (!::PeekNamedPipe(hPipe, NULL, 0, NULL, &dwAvail, NULL))235{236break;237}238239if (!dwAvail) // no data available, return240{241break;242}243244if (!::ReadFile(hPipe,245buf,246std::min<size_t>(sizeof(buf) - 1, size_t(dwAvail)),247&dwRead,248NULL) ||249!dwRead)250{251// error, the child process might ended252break;253}254255buf[dwRead] = 0;256if (pOutStr)257{258(*pOutStr) += buf;259}260}261};262bool bProcessEnded = false;263size_t bytesWritten = 0;264do265{266if (pOptStdIn && (pOptStdIn->size() > bytesWritten))267{268DWORD bytesToWrite = static_cast<DWORD>(pOptStdIn->size()) - bytesWritten;269if (!::WriteFile(hPipes[0].hWrite,270pOptStdIn->data() + bytesWritten,271bytesToWrite,272&bytesToWrite,273nullptr))274{275// Failed to write to pipe276break;277}278bytesWritten += bytesToWrite;279}280281// Give some timeslice (50ms), so we won't waste 100% cpu.282bProcessEnded = (WaitForSingleObject(procInfo.hProcess, 50) == WAIT_OBJECT_0);283284ReadFromPipe(hPipes[1].hRead, pOptStdOut);285ReadFromPipe(hPipes[2].hRead, pOptStdErr);286} while (!bProcessEnded);287288DWORD exitVal = 0;289if (!GetExitCodeProcess(procInfo.hProcess, &exitVal))290{291exitVal = 1;292}293294CloseHandle(procInfo.hProcess);295CloseHandle(procInfo.hThread);296297rvalue = exitVal;298}299300for (WinPipe& p : hPipes)301{302CloseHandle(p.hRead);303CloseHandle(p.hWrite);304}305306#else307308// Non-Windows implementation309310#endif311312return rvalue;313}314315316