return m_pMDImport->GetScopeProps(NULL, pMVID);
}
- HRESULT Assembly::GetNextAssemblyNameRef(DWORD nIndex,
- AssemblyName **ppAssemblyName)
- {
- HRESULT hr = S_OK;
- BINDER_LOG_ENTER(L"Assembly::GetNextAssemblyNameRef");
-
- if (ppAssemblyName == NULL)
- {
- IF_FAIL_GO(E_INVALIDARG);
- }
- else if (GetNbAssemblyRefTokens() == static_cast<DWORD>(-1))
- {
- mdAssembly *pAssemblyRefTokens = NULL;
- DWORD dwCAssemblyRefTokens = 0;
-
- IF_FAIL_GO(BINDER_SPACE::GetAssemblyRefTokens(GetMDImport(),
- &pAssemblyRefTokens,
- &dwCAssemblyRefTokens));
-
- if (InterlockedCompareExchangeT(&m_pAssemblyRefTokens,
- pAssemblyRefTokens,
- NULL))
- {
- SAFE_DELETE_ARRAY(pAssemblyRefTokens);
- }
- SetNbAsssemblyRefTokens(dwCAssemblyRefTokens);
- }
-
- _ASSERTE(GetNbAssemblyRefTokens() != static_cast<DWORD>(-1));
-
- // Verify input index
- if (nIndex >= GetNbAssemblyRefTokens())
- {
- IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS));
- }
- else
- {
- ReleaseHolder<AssemblyName> pAssemblyName;
-
- SAFE_NEW(pAssemblyName, AssemblyName);
- IF_FAIL_GO(pAssemblyName->Init(GetMDImport(),
- peNone,
- GetAssemblyRefTokens()[nIndex],
- FALSE /* fIsDefinition */));
-
- *ppAssemblyName = pAssemblyName.Extract();
- }
-
- Exit:
- BINDER_LOG_LEAVE_HR(L"Assembly::GetNextAssemblyNameRef", hr);
- return hr;
- }
-
/* static */
PEKIND Assembly::GetSystemArchitecture()
{
/* in */ SString &assemblyPath,
/* in */ BOOL fIsInGAC);
- // Enumerates dependent assemblies
- HRESULT GetNextAssemblyNameRef(/* in */ DWORD nIndex,
- /* out */ AssemblyName **ppAssemblyName);
-
inline AssemblyName *GetAssemblyName(BOOL fAddRef = FALSE);
inline BOOL GetIsInGAC();
inline BOOL GetIsDynamicBind();
HRESULT FileOrDirectoryExistsLog(PathString &path);
void MutateUrlToPath(SString &urlOrPath);
- void MutatePathToUrl(SString &pathOrUrl);
// Mutates path
void PlatformPath(SString &path);
BINDER_LOG_LEAVE(W("Utils::MutateUrlToPath"));
}
- void MutatePathToUrl(SString &pathOrUrl)
- {
- BINDER_LOG_ENTER(W("Utils::MutatePathToUrl"));
- SString::Iterator i = pathOrUrl.Begin();
-
- BINDER_LOG_STRING(W("Path"), pathOrUrl);
-
-#if !defined(PLATFORM_UNIX)
- // Network path \\server --> file://server
- // Disk path c:\dir --> file:///c:/dir
- if (i[0] == W('\\'))
- {
- const SString networkUrlPrefix(SString::Literal, W("file:"));
-
- // Network path
- pathOrUrl.Insert(i, networkUrlPrefix);
- pathOrUrl.Skip(i, networkUrlPrefix);
- }
- else
- {
- const SString diskPathUrlPrefix(SString::Literal, W("file:///"));
-
- // Disk path
- pathOrUrl.Insert(i, diskPathUrlPrefix);
- pathOrUrl.Skip(i, diskPathUrlPrefix);
- }
-#else
- // Unix doesn't have a distinction between a network or a local path
- _ASSERTE(i[0] == W('\\') || i[0] == W('/'));
- const SString fileUrlPrefix(SString::Literal, W("file://"));
-
- pathOrUrl.Insert(i, fileUrlPrefix);
- pathOrUrl.Skip(i, fileUrlPrefix);
-#endif
-
- while (pathOrUrl.Find(i, W('\\')))
- {
- pathOrUrl.Replace(i, W('/'));
- }
-
- BINDER_LOG_STRING(W("URL"), pathOrUrl);
- BINDER_LOG_LEAVE(W("Utils::MutatePathToUrl"));
- }
-
void PlatformPath(SString &path)
{
BINDER_LOG_ENTER(W("Utils::PlatformPath"));
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-
-#ifndef _CIRCULARLOG_H__
-
-#define _CIRCULARLOG_H__
-
-#include "sstring.h"
-
-class CircularLog
-{
-public:
- CircularLog();
- ~CircularLog();
-
- bool Init(const WCHAR* logname, const WCHAR* logHeader, DWORD maxSize = 1024*1024);
- void Shutdown();
- void Log(const WCHAR* string);
-
-protected:
-
- void CheckForLogReset(BOOL fOverflow);
- BOOL CheckLogHeader();
- HANDLE OpenFile();
- void CloseFile();
-
- bool m_bInit;
- SString m_LogFilename;
- SString m_LogHeader;
- SString m_OldLogFilename;
- SString m_LockFilename;
- DWORD m_MaxSize;
- unsigned m_uLogCount;
-};
-
-#endif
// Starts the runtime. This is equivalent to CoInitializeCor()
STDMETHODIMP Start();
- STDMETHODIMP MapFile( // Return code.
- HANDLE hFile, // [in] Handle for file
- HMODULE *hMapAddress // [out] HINSTANCE for mapped file
- );
-
STDMETHODIMP LocksHeldByLogicalThread( // Return code.
DWORD *pCount // [out] Number of locks that the current thread holds.
);
// Class factory hook-up.
static HRESULT CreateObject(REFIID riid, void **ppUnk);
- STDMETHODIMP MapFile( // Return code.
- HANDLE hFile, // [in] Handle for file
- HMODULE *hMapAddress // [out] HINSTANCE for mapped file
- )
- {
- WRAPPER_NO_CONTRACT;
- return CorRuntimeHostBase::MapFile(hFile,hMapAddress);
- }
-
STDMETHODIMP STDMETHODCALLTYPE SetHostControl(
IHostControl* pHostControl);
_In_opt_ HANDLE hTemplateFile
);
-BOOL
-SetFileAttributesWrapper(
- _In_ LPCWSTR lpFileName,
- _In_ DWORD dwFileAttributes
- );
-
DWORD
GetFileAttributesWrapper(
_In_ LPCWSTR lpFileName
_In_ DWORD dwAdditionalFlags
);
-BOOL
-CopyFileWrapper(
- _In_ LPCWSTR lpExistingFileName,
- _In_ LPCWSTR lpNewFileName,
- _In_ BOOL bFailIfExists
- );
-
#ifndef FEATURE_PAL
BOOL
CopyFileExWrapper(
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
-BOOL
-RemoveDirectoryWrapper(
- _In_ LPCWSTR lpPathName
- );
-
-BOOL
-CreateHardLinkWrapper(
- _In_ LPCWSTR lpFileName,
- _In_ LPCWSTR lpExistingFileName,
- _Reserved_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
- );
-
DWORD
SearchPathWrapper(
_In_opt_ LPCWSTR lpPath,
);
-DWORD
-GetShortPathNameWrapper(
- _In_ LPCWSTR lpszLongPath,
- SString& lpszShortPath
- );
-
-DWORD
-GetLongPathNameWrapper(
- _In_ LPCWSTR lpszShortPath,
- SString& lpszLongPath
- );
-
UINT WINAPI GetTempFileNameWrapper(
_In_ LPCTSTR lpPathName,
_In_ LPCTSTR lpPrefixString,
bool ClrGetEnvironmentVariable(LPCSTR szEnvVarName, SString & value);
bool ClrGetEnvironmentVariableNoThrow(LPCSTR szEnvVarName, SString & value);
void ClrGetModuleFileName(HMODULE hModule, SString & value);
-bool ClrGetModuleFileNameNoThrow(HMODULE hModule, SString & value);
void ClrGetCurrentDirectory(SString & value);
-bool ClrGetCurrentDirectoryNoThrow(SString & value);
/* --------------------------------------------------------------------------- *
namespace Clr { namespace Util
{
- // This api returns a pointer to a null-terminated string that contains the local appdata directory
- // or it returns NULL in the case that the directory could not be found. The return value from this function
- // is not actually checked for existence.
- HRESULT GetLocalAppDataDirectory(LPCWSTR *ppwzLocalAppDataDirectory);
- HRESULT SetLocalAppDataDirectory(LPCWSTR pwzLocalAppDataDirectory);
-
-namespace Reg
-{
- HRESULT ReadStringValue(HKEY hKey, LPCWSTR wszSubKey, LPCWSTR wszName, SString & ssValue);
- __success(return == S_OK)
- HRESULT ReadStringValue(HKEY hKey, LPCWSTR wszSubKey, LPCWSTR wszName, __deref_out __deref_out_z LPWSTR* pwszValue);
-}
#ifdef FEATURE_COMINTEROP
namespace Com
}
#endif // FEATURE_COMINTEROP
-namespace Win32
-{
- static const WCHAR LONG_FILENAME_PREFIX_W[] = W("\\\\?\\");
- static const CHAR LONG_FILENAME_PREFIX_A[] = "\\\\?\\";
-
- void GetModuleFileName(
- HMODULE hModule,
- SString & ssFileName,
- bool fAllowLongFileNames = false);
-
- __success(return == S_OK)
- HRESULT GetModuleFileName(
- HMODULE hModule,
- __deref_out_z LPWSTR * pwszFileName,
- bool fAllowLongFileNames = false);
-
- void GetFullPathName(
- SString const & ssFileName,
- SString & ssPathName,
- DWORD * pdwFilePartIdx,
- bool fAllowLongFileNames = false);
-}
-
}}
#if defined(FEATURE_APPX) && !defined(DACCESS_COMPILE)
#define WszLoadLibrary LoadLibraryExWrapper
#define WszLoadLibraryEx LoadLibraryExWrapper
#define WszCreateFile CreateFileWrapper
-#define WszSetFileAttributes SetFileAttributesWrapper
#define WszGetFileAttributes GetFileAttributesWrapper
#define WszGetFileAttributesEx GetFileAttributesExWrapper
#define WszDeleteFile DeleteFileWrapper
#define WszFindFirstFileEx FindFirstFileExWrapper
#define WszFindNextFile FindNextFileW
-#define WszCopyFile CopyFileWrapper
-#define WszCopyFileEx CopyFileExWrapper
#define WszMoveFileEx MoveFileExWrapper
-#define WszMoveFile(lpExistingFileName, lpNewFileName) WszMoveFileEx(lpExistingFileName, lpNewFileName, 0)
#define WszCreateDirectory CreateDirectoryWrapper
-#define WszRemoveDirectory RemoveDirectoryWrapper
-#define WszCreateHardLink CreateHardLinkWrapper
//Can not use extended syntax
#define WszGetFullPathName GetFullPathNameW
//APIS which have a buffer as an out parameter
#define WszGetEnvironmentVariable GetEnvironmentVariableWrapper
#define WszSearchPath SearchPathWrapper
-#define WszGetShortPathName GetShortPathNameWrapper
-#define WszGetLongPathName GetLongPathNameWrapper
#define WszGetModuleFileName GetModuleFileNameWrapper
//NOTE: IF the following API's are enabled ensure that they can work with LongFile Names
#endif //FEATURE_METADATA_IN_VM
-#if defined(FEATURE_METADATA_IN_VM)
-
-//*****************************************************************************
-// This is a routine to try to find a class implementation given its fully
-// qualified name by using the CORPATH environment variable. CORPATH is a list
-// of directories (like PATH). Before checking CORPATH, this checks the current
-// directory, then the directory that the exe lives in. The search is
-// performed by parsing off one element at a time from the class name,
-// appending it to the directory and looking for a subdirectory or image with
-// that name. If the subdirectory exists, it drills down into that subdirectory
-// and tries the next element of the class name. When it finally bottoms out
-// but can't find the image it takes the rest of the fully qualified class name
-// and appends them with intervening '.'s trying to find a matching DLL.
-// Example:
-//
-// CORPATH=c:\bin;c:\prog
-// classname = namespace.class
-//
-// checks the following things in order:
-// c:\bin\namespace, (if <-exists) c:\bin\namespace\class.dll,
-// c:\bin\namespace.dll, c:\bin\namespace.class.dll
-// c:\prog\namespace, (if <-exists) c:\prog\namespace\class.dll,
-// c:\prog\namespace.dll, c:\prog\namespace.class.dll
-//*****************************************************************************
-HRESULT CORPATHService::GetClassFromCORPath(
- __in __in_z LPWSTR wzClassname, // [IN] fully qualified class name
- mdTypeRef tr, // [IN] TypeRef to be resolved.
- IMetaModelCommon *pCommon, // [IN] Scope in which the TypeRef is defined.
- REFIID riid, // [IN] Interface type to be returned.
- IUnknown **ppIScope, // [OUT] Scope in which the TypeRef resolves.
- mdTypeDef *ptd) // [OUT] typedef corresponding the typeref
-{
- PathString rcCorPath; // The CORPATH environment variable.
- LPWSTR szCorPath; // Used to parse CORPATH.
- int iLen; // Length of the directory.
- PathString rcCorDir; // Buffer for the directory.
- WCHAR *temp; // Used as a parsing temp.
- WCHAR *szSemiCol;
-
- // Get the CORPATH environment variable.
- if (WszGetEnvironmentVariable(W("CORPATH"), rcCorPath))
- {
- NewArrayHolder<WCHAR> szCorPathHolder = rcCorPath.GetCopyOfUnicodeString();
- szCorPath = szCorPathHolder.GetValue();
- // Try each directory in the path.
- for(;*szCorPath != W('\0');)
- {
- // Get the next directory off the path.
- if ((szSemiCol = wcschr(szCorPath, W(';'))))
- {
- temp = szCorPath;
- *szSemiCol = W('\0');
- szCorPath = szSemiCol + 1;
- }
- else
- {
- temp = szCorPath;
- szCorPath += wcslen(temp);
- }
-
- rcCorDir.Set(temp);
-
- // Check if we can find the class in the directory.
- if (CORPATHService::GetClassFromDir(wzClassname, rcCorDir, tr, pCommon, riid, ppIScope, ptd) == S_OK)
- return S_OK;
- }
- }
-
- //<TODO>These should go before the path search, but it will cause test
- // some headaches right now, so we'll give them a little time to transition.</TODO>
-
- // Try the current directory first.
- if ((iLen = WszGetCurrentDirectory( rcCorDir)) > 0 &&
- CORPATHService::GetClassFromDir(wzClassname, rcCorDir, tr, pCommon, riid, ppIScope, ptd) == S_OK)
- {
- return S_OK;
- }
-
- // Try the app directory next.
- if ((iLen = WszGetModuleFileName(NULL, rcCorDir)) > 0)
- {
-
- if(SUCCEEDED(CopySystemDirectory(rcCorDir, rcCorDir)) &&
- CORPATHService::GetClassFromDir(
- wzClassname,
- rcCorDir,
- tr,
- pCommon,
- riid,
- ppIScope,
- ptd) == S_OK)
- {
- return (S_OK);
- }
- }
-
- // Couldn't find the class.
- return S_FALSE;
-} // CORPATHService::GetClassFromCORPath
-
-//*****************************************************************************
-// This is used in conjunction with GetClassFromCORPath. See it for details
-// of the algorithm.
-//*****************************************************************************
-HRESULT CORPATHService::GetClassFromDir(
- __in __in_z LPWSTR wzClassname, // Fully qualified class name.
- __in SString& directory, // Directory to try. at most appended with a '\\'
- mdTypeRef tr, // TypeRef to resolve.
- IMetaModelCommon *pCommon, // Scope in which the TypeRef is defined.
- REFIID riid,
- IUnknown **ppIScope,
- mdTypeDef *ptd) // [OUT] typedef
-{
- WCHAR *temp; // Used as a parsing temp.
- int iTmp;
- bool bContinue; // Flag to check if the for loop should end.
- LPWSTR wzSaveClassname = NULL; // Saved offset into the class name string.
-
- // Process the class name appending each segment of the name to the
- // directory until we find a DLL.
- PathString dir;
- if (!directory.EndsWith(DIRECTORY_SEPARATOR_CHAR_W))
- {
- directory.Append(DIRECTORY_SEPARATOR_CHAR_W);
- }
-
- for(;;)
- {
- bContinue = false;
- dir.Set(directory);
-
- if ((temp = wcschr(wzClassname, NAMESPACE_SEPARATOR_WCHAR)) != NULL)
- {
- *temp = W('\0'); //terminate with null so that it can be appended
- dir.Append(wzClassname);
- *temp = NAMESPACE_SEPARATOR_WCHAR; //recover the '.'
-
- wzClassname = temp+1;
- // Check if a directory by this name exists.
- DWORD iAttrs = WszGetFileAttributes(dir);
- if (iAttrs != 0xffffffff && (iAttrs & FILE_ATTRIBUTE_DIRECTORY))
- {
- // Next element in the class spec.
- bContinue = true;
- wzSaveClassname = wzClassname;
- }
- }
- else
- {
- dir.Append(wzClassname);
-
- // Advance past the class name.
- iTmp = (int)wcslen(wzClassname);
- wzClassname += iTmp;
- }
-
- // Try to load the image.
- dir.Append(W(".dll"));
-
- // OpenScope given the dll name and make sure that the class is defined in the module.
- if ( SUCCEEDED( CORPATHService::FindTypeDef(dir, tr, pCommon, riid, ppIScope, ptd) ) )
- {
- return (S_OK);
- }
-
- // If we didn't find the dll, try some more.
- while (*wzClassname != W('\0'))
- {
- // Find the length of the next class name element.
- if ((temp = wcschr(wzClassname, NAMESPACE_SEPARATOR_WCHAR)) == NULL)
- {
- temp = wzClassname + wcslen(wzClassname);
- }
-
- // Tack on ".element.dll"
- SString::Iterator iter = dir.End();
- BOOL findperiod = dir.FindBack(iter, NAMESPACE_SEPARATOR_WCHAR);
- _ASSERTE(findperiod);
- iter++;
- dir.Truncate(iter);
-
- WCHAR save = *temp;
- *temp = W('\0');
- dir.Append(wzClassname); //element
- *temp = save;
-
- // Try to load the image.
- dir.Append(W(".dll"));
-
- // OpenScope given the dll name and make sure that the class is defined in the module.
- if ( SUCCEEDED( CORPATHService::FindTypeDef(dir, tr, pCommon, riid, ppIScope, ptd) ) )
- {
- return (S_OK);
- }
-
- // Advance to the next class name element.
- wzClassname = temp;
- if (*wzClassname != '\0')
- ++wzClassname;
- }
- if (bContinue)
- {
-
- wzClassname = wzSaveClassname;
- }
- else
- {
- break;
- }
- }
- return S_FALSE;
-} // CORPATHService::GetClassFromDir
-
-//*************************************************************
-//
-// Open the file with name wzModule and check to see if there is a type
-// with namespace/class of wzNamespace/wzType. If so, return the RegMeta
-// corresponding to the file and the mdTypeDef of the typedef
-//
-//*************************************************************
-HRESULT CORPATHService::FindTypeDef(
- __in __in_z LPCWSTR wzModule, // name of the module that we are going to open
- mdTypeRef tr, // TypeRef to resolve.
- IMetaModelCommon * pCommon, // Scope in which the TypeRef is defined.
- REFIID riid,
- IUnknown ** ppIScope,
- mdTypeDef * ptd) // [OUT] the type that we resolve to
-{
- HRESULT hr = NOERROR;
- NewHolder<Disp> pDisp;
- ReleaseHolder<IMetaDataImport2> pImport = NULL;
- CQuickArray<mdTypeRef> cqaNesters;
- CQuickArray<LPCUTF8> cqaNesterNamespaces;
- CQuickArray<LPCUTF8> cqaNesterNames;
- RegMeta * pRegMeta;
-
- _ASSERTE((ppIScope != NULL) && (ptd != NULL));
-
- *ppIScope = NULL;
-
- pDisp = new (nothrow) Disp;
- IfNullGo(pDisp);
-
- IfFailGo(pDisp->OpenScope(wzModule, 0, IID_IMetaDataImport2, (IUnknown **)&pImport));
- pRegMeta = static_cast<RegMeta *>(pImport.GetValue());
-
- // Get the Nesting hierarchy.
- IfFailGo(ImportHelper::GetNesterHierarchy(pCommon, tr, cqaNesters,
- cqaNesterNamespaces, cqaNesterNames));
-
- hr = ImportHelper::FindNestedTypeDef(
- pRegMeta->GetMiniMd(),
- cqaNesterNamespaces,
- cqaNesterNames,
- mdTokenNil,
- ptd);
- if (SUCCEEDED(hr))
- {
- *ppIScope = pImport.Extract();
- }
-
-ErrExit:
- return hr;
-} // CORPATHService::FindTypeDef
-
-#endif //FEATURE_METADATA_IN_VM
-
//*******************************************************************************
//
// Determine the blob size base of the ELEMENT_TYPE_* associated with the blob.
void *pValue, // BLOB value
ULONG cchString); // Size of string in wide chars, or -1 for auto.
-
-//*********************************************************************
-// APIs to help look up TypeRef using CORPATH environment variable
-//*********************************************************************
-class CORPATHService
-{
-public:
-
- static HRESULT GetClassFromCORPath(
- __in __in_z LPWSTR wzClassname, // fully qualified class name
- mdTypeRef tr, // TypeRef to be resolved
- IMetaModelCommon *pCommon, // Scope in which the TypeRef is defined.
- REFIID riid,
- IUnknown **ppIScope,
- mdTypeDef *ptd); // [OUT] typedef corresponding the typeref
-
- static HRESULT GetClassFromDir(
- __in __in_z LPWSTR wzClassname, // Fully qualified class name.
- __in SString& dir, // Directory to try.
- mdTypeRef tr, // TypeRef to resolve.
- IMetaModelCommon *pCommon, // Scope in which the TypeRef is defined.
- REFIID riid,
- IUnknown **ppIScope,
- mdTypeDef *ptd); // [OUT] typedef
-
- static HRESULT FindTypeDef(
- __in __in_z LPCWSTR wzModule, // name of the module that we are going to open
- mdTypeRef tr, // TypeRef to resolve.
- IMetaModelCommon *pCommon, // Scope in which the TypeRef is defined.
- REFIID riid,
- IUnknown **ppIScope,
- mdTypeDef *ptd ); // [OUT] the type that we resolve to
-}; // class CORPATHService
-
-
#if defined(FEATURE_METADATA_IN_VM)
class RegMeta;
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-//
-// Circular file log
-//
-#include "stdafx.h"
-
-#include "utilcode.h"
-#include "circularlog.h"
-
-CircularLog::CircularLog()
-{
- m_bInit = false;
-}
-
-CircularLog::~CircularLog()
-{
- Shutdown();
-}
-
-bool CircularLog::Init(const WCHAR* logname, const WCHAR* logHeader, DWORD maxSize)
-{
- Shutdown();
-
- m_LogFilename = logname;
- m_LogFilename.Append(W(".log"));
-
- m_LockFilename = logname;
- m_LockFilename.Append(W(".lock"));
-
- m_OldLogFilename = logname;
- m_OldLogFilename .Append(W(".old.log"));
-
- if (logHeader)
- m_LogHeader = logHeader;
-
- m_MaxSize = maxSize;
- m_uLogCount = 0;
-
- m_bInit = true;
-
- if (CheckLogHeader())
- {
- CheckForLogReset(FALSE);
- }
- return true;
-}
-
-void CircularLog::Shutdown()
-{
- m_bInit = false;
-}
-
-void CircularLog::Log(const WCHAR* string)
-{
- if (!m_bInit)
- {
- return;
- }
-
- HANDLE hLogFile = OpenFile();
- if (hLogFile == INVALID_HANDLE_VALUE)
- {
- return;
- }
-
- // Check for file limit only once in a while
- if ((m_uLogCount % 16) == 0)
- {
- // First do a quick check without acquiring lock, optimizing for the common case where file is not overflow.
- LARGE_INTEGER fileSize;
- if (GetFileSizeEx(hLogFile, &fileSize) && fileSize.QuadPart > m_MaxSize)
- {
- // Must close existing handle before calling CheckForOverflow, and re-open it afterwards.
- CloseHandle(hLogFile);
- CheckForLogReset(TRUE);
- hLogFile = OpenFile();
- if (hLogFile == INVALID_HANDLE_VALUE)
- {
- return;
- }
- }
- }
- m_uLogCount++;
-
- // Replace \n with \r\n (we're writing to a binary file)
- NewArrayHolder<WCHAR> pwszConvertedHolder = new WCHAR[wcslen(string)*2 + 1];
- WCHAR* pD = pwszConvertedHolder;
- WCHAR previous = W('\0');
- for (const WCHAR* pS = string ; *pS != W('\0') ; pS++)
- {
- // We get mixed strings ('\n' and '\r\n'). So attempt to filter
- // the ones that don't need to have a '\r' added.
- if (*pS == W('\n') && previous != W('\r'))
- {
- *pD = W('\r');
- pD ++;
- }
-
- *pD = *pS;
- pD++;
-
- previous = *pS;
- }
-
- *pD = W('\0');
-
- // Convert to Utf8 to reduce typical log file size
- SString logString(pwszConvertedHolder);
- StackScratchBuffer bufUtf8;
- COUNT_T cBytesUtf8 = 0;
- const UTF8 * pszUtf8Log = logString.GetUTF8(bufUtf8, &cBytesUtf8);
- // Remove null terminator from log entry buffer
- cBytesUtf8--;
-
- DWORD dwWritten;
- WriteFile(hLogFile, pszUtf8Log, (DWORD)cBytesUtf8, &dwWritten, NULL);
- CloseHandle(hLogFile);
-}
-
-
-BOOL CircularLog::CheckLogHeader()
-{
- BOOL fNeedsPushToBackupLog = FALSE;
-
- // Check to make sure the header on the log is utf8, if it is not, push the current file to the .bak file and try again.
- HANDLE hLogFile = WszCreateFile(
- m_LogFilename.GetUnicode(),
- FILE_READ_DATA,
- FILE_SHARE_READ | FILE_SHARE_WRITE,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
-
- if (hLogFile != INVALID_HANDLE_VALUE)
- {
- CHAR unicodeHeader []= {(char)0xef, (char)0xbb, (char)0xbf};
- CHAR unicodeHeaderCheckBuf[_countof(unicodeHeader)];
-
- DWORD dwRead = sizeof(unicodeHeaderCheckBuf);
- fNeedsPushToBackupLog = !ReadFile(hLogFile, &unicodeHeaderCheckBuf, dwRead, &dwRead, NULL);
-
- if (!fNeedsPushToBackupLog)
- {
- // Successfully read from file. Now check to ensure we read the right amount, and that we read the right data
- if ((dwRead != sizeof(unicodeHeader)) || (0 != memcmp(unicodeHeader, unicodeHeaderCheckBuf, dwRead)))
- {
- fNeedsPushToBackupLog = TRUE;
- }
- }
- CloseHandle(hLogFile);
- }
-
- return fNeedsPushToBackupLog;
-}
-
-#define MOVE_FILE_RETRY_TIME 100
-#define MOVE_FILE_RETRY_COUNT 10
-void CircularLog::CheckForLogReset(BOOL fOverflow)
-{
- if (!m_MaxSize)
- {
- return;
- }
-
- for (int i = 0; i < MOVE_FILE_RETRY_COUNT; i++)
- {
- FileLockHolder lock;
- if (FAILED(lock.AcquireNoThrow(m_LockFilename.GetUnicode())))
- {
- // FileLockHolder::Acquire already has a retry loop, so don't retry if it fails.
- return;
- }
-
- BOOL fLogNeedsReset = FALSE;
-
- if (fOverflow)
- {
- WIN32_FILE_ATTRIBUTE_DATA fileData;
- if (WszGetFileAttributesEx(
- m_LogFilename,
- GetFileExInfoStandard,
- &fileData) == FALSE)
- {
- return;
- }
-
- unsigned __int64 fileSize =
- (((unsigned __int64) fileData.nFileSizeHigh) << 32) |
- ((unsigned __int64) fileData.nFileSizeLow);
-
-
- if (fileSize > (unsigned __int64) m_MaxSize)
- {
- fLogNeedsReset = TRUE;
- }
- }
- else
- {
- fLogNeedsReset = CheckLogHeader();
- }
-
- if (fLogNeedsReset)
- {
- // Push current log out to .old file
- BOOL success = WszMoveFileEx(
- m_LogFilename.GetUnicode(),
- m_OldLogFilename.GetUnicode(),
- MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
-
- if (success || GetLastError() != ERROR_SHARING_VIOLATION)
- {
- return;
- }
- }
- else
- {
- // Someone else moved the file before we can.
- return;
- }
-
- // Don't want to hold the lock while sleeping.
- lock.Release();
- ClrSleepEx(MOVE_FILE_RETRY_TIME, FALSE);
- }
-}
-
-#define OPEN_FILE_RETRY_TIME 100
-#define OPEN_FILE_RETRY_COUNT 10
-// Normally we open file with FILE_SHARE_WRITE, to avoid sharing violations between multiple threads or
-// processes. However, when we create a new file, the Unicode header must be written at the beginning of the
-// file. This can't be guaranteed with multiple writers, so we require exclusive access while creating a new
-// file. Our algorithm is first try to open with OPEN_EXISTING and FILE_SHARE_WRITE, and if that fails, try
-// again with OPEN_ALWAYS and no write sharing.
-HANDLE CircularLog::OpenFile()
-{
- for (int i = 0; i < OPEN_FILE_RETRY_COUNT; i++)
- {
- // First try to open an existing file allowing shared write.
- HANDLE hLogFile = WszCreateFile(
- m_LogFilename.GetUnicode(),
- FILE_APPEND_DATA,
- FILE_SHARE_READ | FILE_SHARE_WRITE,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
-
- if (hLogFile != INVALID_HANDLE_VALUE)
- {
- return hLogFile;
- }
-
- if (GetLastError() == ERROR_FILE_NOT_FOUND)
- {
- // Try to create an new file with exclusive access.
- HANDLE hLogFile = WszCreateFile(
- m_LogFilename.GetUnicode(),
- FILE_APPEND_DATA,
- FILE_SHARE_READ,
- NULL,
- OPEN_ALWAYS,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
-
- if (hLogFile != INVALID_HANDLE_VALUE)
- {
- LARGE_INTEGER fileSize;
- if (! GetFileSizeEx(hLogFile, &fileSize))
- {
- CloseHandle(hLogFile);
- return INVALID_HANDLE_VALUE;
- }
-
- // If the file size is 0, need to write the Unicode header (utf8 bom).
- if (fileSize.QuadPart == 0)
- {
- CHAR unicodeHeader []= {(char)0xef, (char)0xbb, (char)0xbf};
- DWORD dwWritten;
- WriteFile(hLogFile, &unicodeHeader, sizeof(unicodeHeader), &dwWritten, NULL);
-
- // Write out header
-
- // Convert to Utf8 to reduce typical log file size
- StackScratchBuffer bufUtf8;
- COUNT_T cBytesUtf8 = 0;
- const UTF8 * pszUtf8Log = m_LogHeader.GetUTF8(bufUtf8, &cBytesUtf8);
- // Remove null terminator from log entry buffer
- cBytesUtf8--;
-
- WriteFile(hLogFile, pszUtf8Log, (DWORD)cBytesUtf8, &dwWritten, NULL);
- }
-
- return hLogFile;
- }
- }
-
- if (GetLastError() != ERROR_SHARING_VIOLATION)
- {
- break;
- }
-
- ClrSleepEx(OPEN_FILE_RETRY_TIME, FALSE);
- }
-
- return INVALID_HANDLE_VALUE;
-
-}
return ret;
}
-BOOL
-SetFileAttributesWrapper(
- _In_ LPCWSTR lpFileName,
- _In_ DWORD dwFileAttributes
- )
-{
- CONTRACTL
- {
- NOTHROW;
- }
- CONTRACTL_END;
-
- HRESULT hr = S_OK;
- BOOL ret = FALSE;
- DWORD lastError;
-
- EX_TRY
- {
- LongPathString path(LongPathString::Literal, lpFileName);
-
- if (SUCCEEDED(LongFile::NormalizePath(path)))
- {
- ret = SetFileAttributesW(
- path.GetUnicode(),
- dwFileAttributes
- );
- }
-
- lastError = GetLastError();
- }
- EX_CATCH_HRESULT(hr);
-
- if (hr != S_OK )
- {
- SetLastError(hr);
- }
- else if(ret == FALSE)
- {
- SetLastError(lastError);
- }
-
- return ret;
-}
-
DWORD
GetFileAttributesWrapper(
_In_ LPCWSTR lpFileName
return ret;
}
-
-BOOL
-CopyFileWrapper(
- _In_ LPCWSTR lpExistingFileName,
- _In_ LPCWSTR lpNewFileName,
- _In_ BOOL bFailIfExists
- )
-{
- CONTRACTL
- {
- NOTHROW;
- }
- CONTRACTL_END;
-
- HRESULT hr = S_OK;
- BOOL ret = FALSE;
- DWORD lastError;
-
- EX_TRY
- {
- LongPathString Existingpath(LongPathString::Literal, lpExistingFileName);
- LongPathString Newpath(LongPathString::Literal, lpNewFileName);
-
- if (SUCCEEDED(LongFile::NormalizePath(Existingpath)) && SUCCEEDED(LongFile::NormalizePath(Newpath)))
- {
- ret = CopyFileW(
- Existingpath.GetUnicode(),
- Newpath.GetUnicode(),
- bFailIfExists
- );
- }
-
- lastError = GetLastError();
- }
- EX_CATCH_HRESULT(hr);
-
- if (hr != S_OK )
- {
- SetLastError(hr);
- }
- else if(ret == FALSE)
- {
- SetLastError(lastError);
- }
-
- return ret;
-}
-
BOOL
MoveFileExWrapper(
_In_ LPCWSTR lpExistingFileName,
}
-DWORD
-GetShortPathNameWrapper(
- _In_ LPCWSTR lpszLongPath,
- SString& lpszShortPath
- )
-{
- CONTRACTL
- {
- NOTHROW;
- }
- CONTRACTL_END;
-
- DWORD ret = 0;
- HRESULT hr = S_OK;
- DWORD lastError;
-
- EX_TRY
- {
- LongPathString longPath(LongPathString::Literal, lpszLongPath);
-
- if (SUCCEEDED(LongFile::NormalizePath(longPath)))
- {
- COUNT_T size = lpszShortPath.GetUnicodeAllocation() + 1;
-
- ret = GetShortPathNameW(
- longPath.GetUnicode(),
- lpszShortPath.OpenUnicodeBuffer(size - 1),
- (DWORD)size
- );
-
- if (ret > size)
- {
- lpszShortPath.CloseBuffer();
- ret = GetShortPathNameW(
- longPath.GetUnicode(),
- lpszShortPath.OpenUnicodeBuffer(ret -1),
- ret
- );
- }
-
- lpszShortPath.CloseBuffer(ret);
- }
-
- lastError = GetLastError();
- }
- EX_CATCH_HRESULT(hr);
-
- if (hr != S_OK )
- {
- SetLastError(hr);
- }
- else if(ret == 0)
- {
- SetLastError(lastError);
- }
-
- return ret;
-}
-
-DWORD
-GetLongPathNameWrapper(
- _In_ LPCWSTR lpszShortPath,
- SString& lpszLongPath
- )
-{
- CONTRACTL
- {
- NOTHROW;
- }
- CONTRACTL_END;
-
- DWORD ret = 0;
- HRESULT hr = S_OK;
- DWORD lastError;
-
- EX_TRY
- {
- LongPathString shortPath(LongPathString::Literal, lpszShortPath);
-
- if (SUCCEEDED(LongFile::NormalizePath(shortPath)))
- {
- COUNT_T size = lpszLongPath.GetUnicodeAllocation() + 1;
-
- ret = GetLongPathNameW(
- shortPath.GetUnicode(),
- lpszLongPath.OpenUnicodeBuffer(size - 1),
- (DWORD)size
- );
-
- if (ret > size)
- {
- lpszLongPath.CloseBuffer();
- ret = GetLongPathNameW(
- shortPath.GetUnicode(),
- lpszLongPath.OpenUnicodeBuffer(ret - 1),
- ret
- );
-
- }
-
- lpszLongPath.CloseBuffer(ret);
- }
-
- lastError = GetLastError();
- }
- EX_CATCH_HRESULT(hr);
-
- if (hr != S_OK )
- {
- SetLastError(hr);
- }
- else if(ret == 0)
- {
- SetLastError(lastError);
- }
-
- return ret;
-}
-
BOOL
CreateDirectoryWrapper(
_In_ LPCWSTR lpPathName,
return ret;
}
-BOOL
-RemoveDirectoryWrapper(
- _In_ LPCWSTR lpPathName
- )
-{
- CONTRACTL
- {
- NOTHROW;
- }
- CONTRACTL_END;
-
- HRESULT hr = S_OK;
- BOOL ret = FALSE;
- DWORD lastError;
-
- EX_TRY
- {
- LongPathString path(LongPathString::Literal, lpPathName);
-
- if (SUCCEEDED(LongFile::NormalizePath(path)))
- {
- ret = RemoveDirectoryW(
- path.GetUnicode()
- );
- }
-
- lastError = GetLastError();
- }
- EX_CATCH_HRESULT(hr);
-
- if (hr != S_OK )
- {
- SetLastError(hr);
- }
- else if(ret == FALSE)
- {
- SetLastError(lastError);
- }
-
- return ret;
-}
DWORD
GetModuleFileNameWrapper(
_In_opt_ HMODULE hModule,
#ifndef FEATURE_PAL
BOOL
-CreateHardLinkWrapper(
- _In_ LPCWSTR lpFileName,
- _In_ LPCWSTR lpExistingFileName,
- _Reserved_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
- )
-{
- CONTRACTL
- {
- NOTHROW;
- }
- CONTRACTL_END;
-
- HRESULT hr = S_OK;
- BOOL ret = FALSE;
- DWORD lastError;
-
- EX_TRY
- {
- LongPathString Existingpath(LongPathString::Literal, lpExistingFileName);
- LongPathString FileName(LongPathString::Literal, lpFileName);
-
- if (SUCCEEDED(LongFile::NormalizePath(Existingpath)) && SUCCEEDED(LongFile::NormalizePath(FileName)))
- {
- ret = CreateHardLinkW(
- Existingpath.GetUnicode(),
- FileName.GetUnicode(),
- lpSecurityAttributes
- );
- }
-
- lastError = GetLastError();
- }
- EX_CATCH_HRESULT(hr);
-
- if (hr != S_OK )
- {
- SetLastError(hr);
- }
- else if(ret == FALSE)
- {
- SetLastError(lastError);
- }
-
- return ret;
-}
-
-BOOL
CopyFileExWrapper(
_In_ LPCWSTR lpExistingFileName,
_In_ LPCWSTR lpNewFileName,
}
}
-// Nothrowing wrapper.
-bool ClrGetCurrentDirectoryNoThrow(SString & value)
-{
- CONTRACTL
- {
- NOTHROW;
- GC_NOTRIGGER;
- }
- CONTRACTL_END;
-
- bool fOk = true;
- EX_TRY
- {
- ClrGetCurrentDirectory(value);
- }
- EX_CATCH
- {
- fOk = false;
- }
- EX_END_CATCH(SwallowAllExceptions)
- return fOk;
-}
//-----------------------------------------------------------------------------
// Reads an environment variable into the given SString.
// Returns true on success, false on failure (includes if the var does not exist).
return true;
}
-// Nothrowing wrapper.
-bool ClrGetEnvironmentVariableNoThrow(LPCSTR szEnvVarName, SString & value)
-{
- CONTRACTL
- {
- NOTHROW;
- GC_NOTRIGGER;
- }
- CONTRACTL_END;
-
-
- bool fOk = false;
- EX_TRY
- {
- fOk = ClrGetEnvironmentVariable(szEnvVarName, value);
- }
- EX_CATCH
- {
- fOk = false;
- }
- EX_END_CATCH(SwallowAllExceptions)
- return fOk;
-}
-
void ClrGetModuleFileName(HMODULE hModule, SString & value)
{
CONTRACTL
value.CloseBuffer(numChars);
}
-bool ClrGetModuleFileNameNoThrow(HMODULE hModule, SString & value)
-{
- CONTRACTL
- {
- NOTHROW;
- GC_NOTRIGGER;
- }
- CONTRACTL_END;
-
- bool fOk = true;
- EX_TRY
- {
- ClrGetModuleFileName(hModule, value);
- }
- EX_CATCH
- {
- fOk = false;
- }
- EX_END_CATCH(SwallowAllExceptions)
- return fOk;
-}
-
ClrDirectoryEnumerator::ClrDirectoryEnumerator(LPCWSTR pBaseDirectory, LPCWSTR pMask /*= W("*")*/)
{
CONTRACTL
static BOOL g_fLocalAppDataDirectoryInitted = FALSE;
static WCHAR *g_wszLocalAppDataDirectory = NULL;
-// This api returns a pointer to a null-terminated string that contains the local appdata directory
-// or it returns NULL in the case that the directory could not be found. The return value from this function
-// is not actually checked for existence.
- HRESULT GetLocalAppDataDirectory(LPCWSTR *ppwzLocalAppDataDirectory)
- {
- CONTRACTL {
- NOTHROW;
- GC_NOTRIGGER;
- } CONTRACTL_END;
-
- HRESULT hr = S_OK;
- *ppwzLocalAppDataDirectory = NULL;
-
- EX_TRY
- {
- if (!g_fLocalAppDataDirectoryInitted)
- {
- WCHAR *wszLocalAppData = NULL;
-
- DWORD cCharsNeeded;
- cCharsNeeded = GetEnvironmentVariableW(W("LOCALAPPDATA"), NULL, 0);
-
- if ((cCharsNeeded != 0) && (cCharsNeeded < MAX_LONGPATH))
- {
- wszLocalAppData = new WCHAR[cCharsNeeded];
- cCharsNeeded = GetEnvironmentVariableW(W("LOCALAPPDATA"), wszLocalAppData, cCharsNeeded);
- if (cCharsNeeded != 0)
- {
- // We've collected the appropriate app data directory into a local. Now publish it.
- if (InterlockedCompareExchangeT(&g_wszLocalAppDataDirectory, wszLocalAppData, NULL) == NULL)
- {
- // This variable doesn't need to be freed, as it has been stored in the global
- wszLocalAppData = NULL;
- }
- }
- }
-
- g_fLocalAppDataDirectoryInitted = TRUE;
- delete[] wszLocalAppData;
- }
- }
- EX_CATCH_HRESULT(hr);
-
- if (SUCCEEDED(hr))
- *ppwzLocalAppDataDirectory = g_wszLocalAppDataDirectory;
-
- return hr;
- }
-
- HRESULT SetLocalAppDataDirectory(LPCWSTR pwzLocalAppDataDirectory)
- {
- CONTRACTL {
- NOTHROW;
- GC_NOTRIGGER;
- } CONTRACTL_END;
-
- if (pwzLocalAppDataDirectory == NULL || *pwzLocalAppDataDirectory == W('\0'))
- return E_INVALIDARG;
-
- if (g_fLocalAppDataDirectoryInitted)
- return E_UNEXPECTED;
-
- HRESULT hr = S_OK;
-
- EX_TRY
- {
- size_t size = wcslen(pwzLocalAppDataDirectory) + 1;
- WCHAR *wszLocalAppData = new WCHAR[size];
- wcscpy_s(wszLocalAppData, size, pwzLocalAppDataDirectory);
-
- // We've collected the appropriate app data directory into a local. Now publish it.
- if (InterlockedCompareExchangeT(&g_wszLocalAppDataDirectory, wszLocalAppData, NULL) != NULL)
- {
- // Someone else already set LocalAppData. Free our copy and return an error.
- delete[] wszLocalAppData;
- hr = E_UNEXPECTED;
- }
-
- g_fLocalAppDataDirectoryInitted = TRUE;
- }
- EX_CATCH_HRESULT(hr);
-
- return hr;
- }
-
#ifndef FEATURE_PAL
// Struct used to scope suspension of client impersonation for the current thread.
// https://docs.microsoft.com/en-us/windows/desktop/secauthz/client-impersonation
} // namespace Com
#endif // FEATURE_PAL
-namespace Win32
-{
- void GetModuleFileName(
- HMODULE hModule,
- SString & ssFileName,
- bool fAllowLongFileNames)
- {
- STANDARD_VM_CONTRACT;
-
- // Try to use what the SString already has allocated. If it does not have anything allocated
- // or it has < 20 characters allocated, then bump the size requested to _MAX_PATH.
-
- DWORD dwResult = WszGetModuleFileName(hModule, ssFileName);
-
-
- if (dwResult == 0)
- ThrowHR(HRESULT_FROM_GetLastError());
-
- _ASSERTE(dwResult != 0 );
- }
-
- // Returns heap-allocated string in *pwszFileName
- HRESULT GetModuleFileName(
- HMODULE hModule,
- __deref_out_z LPWSTR * pwszFileName,
- bool fAllowLongFileNames)
- {
- CONTRACTL {
- NOTHROW;
- GC_NOTRIGGER;
- PRECONDITION(CheckPointer(pwszFileName));
- } CONTRACTL_END;
-
- HRESULT hr = S_OK;
- EX_TRY
- {
- InlineSString<_MAX_PATH> ssFileName;
- GetModuleFileName(hModule, ssFileName);
- *pwszFileName = DuplicateStringThrowing(ssFileName.GetUnicode());
- }
- EX_CATCH_HRESULT(hr);
-
- return hr;
- }
-
- void GetFullPathName(
- SString const & ssFileName,
- SString & ssPathName,
- DWORD * pdwFilePartIdx,
- bool fAllowLongFileNames)
- {
- STANDARD_VM_CONTRACT;
-
- // Get the required buffer length (including terminating NULL).
- DWORD dwLengthRequired = WszGetFullPathName(ssFileName.GetUnicode(), 0, NULL, NULL);
-
- if (dwLengthRequired == 0)
- ThrowHR(HRESULT_FROM_GetLastError());
-
- LPWSTR wszPathName = ssPathName.OpenUnicodeBuffer(dwLengthRequired - 1);
- LPWSTR wszFileName = NULL;
- DWORD dwLengthWritten = WszGetFullPathName(
- ssFileName.GetUnicode(),
- dwLengthRequired,
- wszPathName,
- &wszFileName);
-
- // Calculate the index while the buffer is open and the string pointer is stable.
- if (dwLengthWritten != 0 && dwLengthWritten < dwLengthRequired && pdwFilePartIdx != NULL)
- *pdwFilePartIdx = static_cast<DWORD>(wszFileName - wszPathName);
-
- ssPathName.CloseBuffer(dwLengthWritten < dwLengthRequired ? dwLengthWritten : 0);
-
- if (dwLengthRequired == 0)
- ThrowHR(HRESULT_FROM_GetLastError());
-
- // Overly defensive? Perhaps.
- if (!(dwLengthWritten < dwLengthRequired))
- ThrowHR(E_UNEXPECTED);
- }
-} // namespace Win32
-
} // namespace Util
} // namespace Clr
return *(void **)(&callDescrData.returnValue);
}
-// This method performs the proper profiler and debugger callbacks before dispatching the
-// call. The caller has the responsibility of furnishing the target address, register and stack arguments.
-// Stack arguments should be in reverse order, and pSrc should point to past the last argument
-// Returns the return value or the exception object if one was thrown.
-void DispatchCall(
- CallDescrData * pCallDescrData,
- OBJECTREF *pRefException
-#ifdef FEATURE_CORRUPTING_EXCEPTIONS
- , CorruptionSeverity *pSeverity /*= NULL*/
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- )
-{
- CONTRACTL
- {
- GC_TRIGGERS;
- THROWS;
- MODE_COOPERATIVE;
- }
- CONTRACTL_END;
-
-#ifdef DEBUGGING_SUPPORTED
- if (CORDebuggerTraceCall())
- g_pDebugInterface->TraceCall((const BYTE *)pCallDescrData->pTarget);
-#endif // DEBUGGING_SUPPORTED
-
-#ifdef FEATURE_CORRUPTING_EXCEPTIONS
- if (pSeverity != NULL)
- {
- // By default, assume any exception that comes out is NotCorrupting
- *pSeverity = NotCorrupting;
- }
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
-
- EX_TRY
- {
- DispatchCallDebuggerWrapper(pCallDescrData,
- FALSE);
- }
- EX_CATCH
- {
- *pRefException = GET_THROWABLE();
-
-#ifdef FEATURE_CORRUPTING_EXCEPTIONS
- if (pSeverity != NULL)
- {
- // By default, assume any exception that comes out is NotCorrupting
- *pSeverity = GetThread()->GetExceptionState()->GetLastActiveExceptionCorruptionSeverity();
- }
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
-
- }
- EX_END_CATCH(RethrowTransientExceptions);
-}
-
#ifdef CALLDESCR_REGTYPEMAP
//*******************************************************************************
void FillInRegTypeMap(int argOffset, CorElementType typ, BYTE * pMap)
CallDescrData * pCallDescrData,
BOOL fCriticalCall = FALSE);
-void DispatchCall(
- CallDescrData * pCallDescrData,
- OBJECTREF * pRefException
-#ifdef FEATURE_CORRUPTING_EXCEPTIONS
- , CorruptionSeverity * pSeverity = NULL
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- );
-
// Helper for VM->managed calls with simple signatures.
void * DispatchCallSimple(
SIZE_T *pSrc,
#endif // FEATURE_PREJIT || FEATURE_READYTORUN
-#ifndef DACCESS_COMPILE
-
-//-----------------------------------------------------------------------------
-
-
-// Nirvana Support
-
-MethodDesc* __stdcall Nirvana_FindMethodDesc(PCODE ptr, BYTE*& hotStartAddress, size_t& hotSize, BYTE*& coldStartAddress, size_t & coldSize)
-{
- EECodeInfo codeInfo(ptr);
- if (!codeInfo.IsValid())
- return NULL;
-
- IJitManager::MethodRegionInfo methodRegionInfo;
- codeInfo.GetMethodRegionInfo(&methodRegionInfo);
-
- hotStartAddress = (BYTE*)methodRegionInfo.hotStartAddress;
- hotSize = methodRegionInfo.hotSize;
- coldStartAddress = (BYTE*)methodRegionInfo.coldStartAddress;
- coldSize = methodRegionInfo.coldSize;
-
- return codeInfo.GetMethodDesc();
-}
-
-
-bool Nirvana_GetMethodInfo(MethodDesc * pMD, BYTE*& hotStartAddress, size_t& hotSize, BYTE*& coldStartAddress, size_t & coldSize)
-{
- EECodeInfo codeInfo(pMD->GetNativeCode());
- if (!codeInfo.IsValid())
- return false;
-
- IJitManager::MethodRegionInfo methodRegionInfo;
- codeInfo.GetMethodRegionInfo(&methodRegionInfo);
-
- hotStartAddress = (BYTE*)methodRegionInfo.hotStartAddress;
- hotSize = methodRegionInfo.hotSize;
- coldStartAddress = (BYTE*)methodRegionInfo.coldStartAddress;
- coldSize = methodRegionInfo.coldSize;
-
- return true;
-}
-
-
-#include "sigformat.h"
-
-__forceinline bool Nirvana_PrintMethodDescWorker(__in_ecount(iBuffer) char * szBuffer, size_t iBuffer, MethodDesc * pMD, const char * pSigString)
-{
- if (iBuffer == 0)
- return false;
-
- szBuffer[0] = '\0';
- pSigString = strchr(pSigString, ' ');
-
- if (pSigString == NULL)
- return false;
-
- ++pSigString;
-
- LPCUTF8 pNamespace;
- LPCUTF8 pClassName = pMD->GetMethodTable()->GetFullyQualifiedNameInfo(&pNamespace);
-
- if (pClassName == NULL)
- return false;
-
- if (*pNamespace != 0)
- {
- if (_snprintf_s(szBuffer, iBuffer, _TRUNCATE, "%s.%s.%s", pNamespace, pClassName, pSigString) == -1)
- return false;
- }
- else
- {
- if (_snprintf_s(szBuffer, iBuffer, _TRUNCATE, "%s.%s", pClassName, pSigString) == -1)
- return false;
- }
-
- _ASSERTE(szBuffer[0] != '\0');
-
- return true;
-}
-
-bool __stdcall Nirvana_PrintMethodDesc(__in_ecount(iBuffer) char * szBuffer, size_t iBuffer, MethodDesc * pMD)
-{
- bool fResult = false;
-
- EX_TRY
- {
- NewHolder<SigFormat> pSig = new SigFormat(pMD, NULL, false);
- fResult = Nirvana_PrintMethodDescWorker(szBuffer, iBuffer, pMD, pSig->GetCString());
- }
- EX_CATCH
- {
- fResult = false;
- }
- EX_END_CATCH(SwallowAllExceptions)
-
- return fResult;
-};
-
-
-// Nirvana_Dummy() is a dummy function that is exported privately by ordinal only.
-// The sole purpose of this function is to reference Nirvana_FindMethodDesc(),
-// Nirvana_GetMethodInfo(), and Nirvana_PrintMethodDesc() so that they are not
-// inlined or removed by the compiler or the linker.
-
-DWORD __stdcall Nirvana_Dummy()
-{
- LIMITED_METHOD_CONTRACT;
- void * funcs[] = {
- (void*)Nirvana_FindMethodDesc,
- (void*)Nirvana_GetMethodInfo,
- (void*)Nirvana_PrintMethodDesc
- };
-
- size_t n = sizeof(funcs) / sizeof(funcs[0]);
-
- size_t sum = 0;
- for (size_t i = 0; i < n; ++i)
- sum += (size_t)funcs[i];
-
- return (DWORD)sum;
-}
-
-
-#endif // #ifndef DACCESS_COMPILE
#ifdef FEATURE_PREJIT
FCIMPLEND
//**************************************************
-// LoadInMemoryTypeByName
-// Explicitly loading an in memory type
-// <TODO>@todo: this function is not dealing with nested type correctly yet.
-// We will need to parse the full name by finding "+" for enclosing type, etc.</TODO>
-//**************************************************
-void QCALLTYPE COMModule::LoadInMemoryTypeByName(QCall::ModuleHandle pModule, LPCWSTR wszFullName)
-{
- QCALL_CONTRACT;
-
- TypeHandle typeHnd;
-
- BEGIN_QCALL;
-
- if (!pModule->IsReflection())
- COMPlusThrow(kNotSupportedException, W("NotSupported_NonReflectedType"));
-
- RefClassWriter * pRCW = pModule->GetReflectionModule()->GetClassWriter();
- _ASSERTE(pRCW);
-
- // it is ok to use public import API because this is a dynamic module anyway. We are also receiving Unicode full name as
- // parameter.
- IMetaDataImport * pImport = pRCW->GetRWImporter();
-
- if (wszFullName == NULL)
- IfFailThrow( E_FAIL );
-
- // look up the handle
- mdTypeDef td;
- HRESULT hr = pImport->FindTypeDefByName(wszFullName, mdTokenNil, &td);
- if (FAILED(hr))
- {
- if (hr != CLDB_E_RECORD_NOTFOUND)
- COMPlusThrowHR(hr);
-
- // Get the UTF8 version of strFullName
- MAKE_UTF8PTR_FROMWIDE(szFullName, wszFullName);
- pModule->GetAssembly()->ThrowTypeLoadException(szFullName, IDS_CLASSLOAD_GENERAL);
- }
-
- TypeKey typeKey(pModule, td);
- typeHnd = pModule->GetClassLoader()->LoadTypeHandleForTypeKey(&typeKey, TypeHandle());
-
- END_QCALL;
-
- return;
-}
-
-//**************************************************
// GetTypeRef
// This function will return the type token given full qual name. If the type
// is defined locally, we will return the TypeDef token. Or we will return a TypeRef token
LPCWSTR wszRefedModuleFileName,
INT32 tkResolution);
- // LoadInMemoryTypeByName
- // This function will return the class token for the named element.
- static
- void QCALLTYPE LoadInMemoryTypeByName(QCall::ModuleHandle pModule, LPCWSTR wszFullName);
-
-
// SetFieldRVAContent
// This function is used to set the FieldRVA with the content data
static
return pImage.Extract();
}
-HRESULT CorRuntimeHostBase::MapFile(HANDLE hFile, HMODULE* phHandle)
-{
- CONTRACTL
- {
- NOTHROW;
- GC_TRIGGERS;
- MODE_PREEMPTIVE;
- ENTRY_POINT;
- }
- CONTRACTL_END;
-
- HRESULT hr;
- BEGIN_ENTRYPOINT_NOTHROW;
-
- BEGIN_EXTERNAL_ENTRYPOINT(&hr)
- {
- *phHandle = (HMODULE) (MapFileHelper(hFile)->GetLoadedLayout()->GetBase());
- }
- END_EXTERNAL_ENTRYPOINT;
- END_ENTRYPOINT_NOTHROW;
-
-
- return hr;
-}
-
LONG CorHost2::m_RefCount = 0;
static Volatile<BOOL> fOneOnly = 0;
static Volatile<BOOL> fReady = 0;
static SpinLock initLock;
-void DECLSPEC_NORETURN RaiseDeadLockException()
-{
- STATIC_CONTRACT_THROWS;
-
-// Disable the "initialization of static local vars is no thread safe" error
-#ifdef _MSC_VER
-#pragma warning(disable: 4640)
-#endif
- CHECK_LOCAL_STATIC_VAR(static SString s);
-#ifdef _MSC_VER
-#pragma warning(default : 4640)
-#endif
- if (!fReady)
- {
- WCHAR name[256];
- HRESULT hr = S_OK;
- {
- FAULT_NOT_FATAL();
- GCX_COOP();
- hr = UtilLoadStringRC(IDS_EE_THREAD_DEADLOCK_VICTIM, name, sizeof(name)/sizeof(WCHAR), 1);
- }
- initLock.Init(LOCK_TYPE_DEFAULT);
- SpinLockHolder __spinLockHolder(&initLock);
- if (!fReady)
- {
- if (SUCCEEDED(hr))
- {
- s.Set(name);
- fReady = 1;
- }
- else
- {
- ThrowHR(hr);
- }
- }
- }
-
- ThrowHR(HOST_E_DEADLOCK, s);
-}
-
//******************************************************************************
//
// ExceptionIsAlwaysSwallowed
LONG CallOutFilter(PEXCEPTION_POINTERS pExceptionInfo, PVOID pv);
-void DECLSPEC_NORETURN RaiseDeadLockException();
-
void STDMETHODCALLTYPE DefaultCatchHandler(PEXCEPTION_POINTERS pExceptionInfo,
OBJECTREF *Throwable = NULL,
BOOL useLastThrownObject = FALSE,
}
HCIMPLEND
-HCIMPL2(VOID, JIT_GetRuntimeFieldHandle, Object ** destPtr, CORINFO_FIELD_HANDLE field)
-{
- FCALL_CONTRACT;
-
- HELPER_METHOD_FRAME_BEGIN_0();
-
- FieldDesc *pField = (FieldDesc *)field;
- SetObjectReference((OBJECTREF*) destPtr,
- pField->GetStubFieldInfo());
-
- HELPER_METHOD_FRAME_END();
-}
-HCIMPLEND
-
HCIMPL1(Object*, JIT_GetRuntimeFieldStub, CORINFO_FIELD_HANDLE field)
{
FCALL_CONTRACT;
}
HCIMPLEND
-HCIMPL2(VOID, JIT_GetRuntimeMethodHandle, Object ** destPtr, CORINFO_METHOD_HANDLE method)
-{
- FCALL_CONTRACT;
-
- HELPER_METHOD_FRAME_BEGIN_0();
-
- MethodDesc *pMethod = (MethodDesc *)method;
- SetObjectReference((OBJECTREF*) destPtr,
- pMethod->GetStubMethodInfo());
-
- HELPER_METHOD_FRAME_END();
-}
-HCIMPLEND
-
HCIMPL1(Object*, JIT_GetRuntimeMethodStub, CORINFO_METHOD_HANDLE method)
{
FCALL_CONTRACT;
return DispatchToken::CreateDispatchToken(typeId, slotNumber);
}
-DispatchToken LoaderAllocator::TryLookupDispatchToken(UINT32 typeId, UINT32 slotNumber)
-{
- CONTRACTL {
- NOTHROW;
- GC_NOTRIGGER;
- MODE_ANY;
- } CONTRACTL_END;
-
-#ifdef FAT_DISPATCH_TOKENS
-
- if (DispatchToken::RequiresDispatchTokenFat(typeId, slotNumber))
- {
- if (m_pFatTokenSetLock != NULL)
- {
- DispatchTokenFat * pFat = NULL;
- // Stack probes and locking operations are throwing. Catch all
- // exceptions and just return an invalid token, since this is
- EX_TRY
- {
- SimpleReadLockHolder rlock(m_pFatTokenSetLock);
- if (m_pFatTokenSet != NULL)
- {
- DispatchTokenFat key(typeId, slotNumber);
- pFat = m_pFatTokenSet->Lookup(&key);
- }
- }
- EX_CATCH
- {
- pFat = NULL;
- }
- EX_END_CATCH(SwallowAllExceptions);
-
- if (pFat != NULL)
- {
- return DispatchToken(pFat);
- }
- }
- // Return invalid token when not found.
- return DispatchToken();
- }
- else
-#endif // FAT_DISPATCH_TOKENS
- {
- return DispatchToken::CreateDispatchToken(typeId, slotNumber);
- }
-}
-
void LoaderAllocator::InitVirtualCallStubManager(BaseDomain * pDomain)
{
STANDARD_VM_CONTRACT;
// in the return value.
DispatchToken GetDispatchToken(UINT32 typeId, UINT32 slotNumber);
- // Same as GetDispatchToken, but returns invalid DispatchToken when the
- // value doesn't exist or a transient exception (OOM, stack overflow) is
- // encountered. To check if the token is valid, use DispatchToken::IsValid
- DispatchToken TryLookupDispatchToken(UINT32 typeId, UINT32 slotNumber);
-
virtual LoaderAllocatorID* Id() =0;
BOOL IsCollectible() { WRAPPER_NO_CONTRACT; return m_IsCollectible; }
RETURN new PEAssembly(&bindResult, NULL, NULL, TRUE, FALSE);
}
-
-#ifndef CROSSGEN_COMPILE
-/* static */
-PEAssembly *PEAssembly::OpenMemory(PEAssembly *pParentAssembly,
- const void *flat, COUNT_T size)
-{
- STANDARD_VM_CONTRACT;
-
- PEAssembly *result = NULL;
-
- EX_TRY
- {
- result = DoOpenMemory(pParentAssembly, flat, size);
- }
- EX_HOOK
- {
- Exception *ex = GET_EXCEPTION();
-
- // Rethrow non-transient exceptions as file load exceptions with proper
- // context
-
- if (!ex->IsTransient())
- EEFileLoadException::Throw(pParentAssembly, flat, size, ex->GetHR(), ex);
- }
- EX_END_HOOK;
-
- return result;
-}
-
-
-// Thread stress
-
-class DoOpenFlatStress : APIThreadStress
-{
-public:
- PEAssembly *pParentAssembly;
- const void *flat;
- COUNT_T size;
- DoOpenFlatStress(PEAssembly *pParentAssembly, const void *flat, COUNT_T size)
- : pParentAssembly(pParentAssembly), flat(flat), size(size) {LIMITED_METHOD_CONTRACT;}
- void Invoke()
- {
- WRAPPER_NO_CONTRACT;
- PEAssemblyHolder result(PEAssembly::OpenMemory(pParentAssembly, flat, size));
- }
-};
-
-/* static */
-PEAssembly *PEAssembly::DoOpenMemory(
- PEAssembly *pParentAssembly,
- const void *flat,
- COUNT_T size)
-{
- CONTRACT(PEAssembly *)
- {
- PRECONDITION(CheckPointer(flat));
- PRECONDITION(CheckOverflow(flat, size));
- PRECONDITION(CheckPointer(pParentAssembly));
- STANDARD_VM_CHECK;
- POSTCONDITION(CheckPointer(RETVAL));
- }
- CONTRACT_END;
-
- // Thread stress
- DoOpenFlatStress ts(pParentAssembly, flat, size);
-
- // Note that we must have a flat image stashed away for two reasons.
- // First, we need a private copy of the data which we can verify
- // before doing the mapping. And secondly, we can only compute
- // the strong name hash on a flat image.
-
- PEImageHolder image(PEImage::LoadFlat(flat, size));
-
- // Need to verify that this is a CLR assembly
- if (!image->CheckILFormat())
- ThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL);
-
-
- CoreBindResult bindResult;
- ReleaseHolder<ICLRPrivAssembly> assembly;
- IfFailThrow(CCoreCLRBinderHelper::GetAssemblyFromImage(image, NULL, &assembly));
- bindResult.Init(assembly);
-
- RETURN new PEAssembly(&bindResult, NULL, pParentAssembly, FALSE);
-}
-#endif // !CROSSGEN_COMPILE
-
-
-
PEAssembly* PEAssembly::Open(CoreBindResult* pBindResult,
BOOL isSystem)
{
PEAssembly *pParentAssembly,
IMetaDataAssemblyEmit *pEmit);
- static PEAssembly *OpenMemory(
- PEAssembly *pParentAssembly,
- const void *flat,
- COUNT_T size);
-
- static PEAssembly *DoOpenMemory(
- PEAssembly *pParentAssembly,
- const void *flat,
- COUNT_T size);
-
private:
// Private helpers for crufty exception handling reasons
static PEAssembly *DoOpenSystem(IUnknown *pAppCtx);
return true;
}
-HRESULT VMPostError( // Returned error.
- HRESULT hrRpt, // Reported error.
- ...) // Error arguments.
-{
- CONTRACTL
- {
- NOTHROW;
- GC_TRIGGERS;
- MODE_ANY;
- }
- CONTRACTL_END;
-
- GCX_PREEMP();
-
- va_list marker; // User text.
- va_start(marker, hrRpt);
- hrRpt = PostErrorVA(hrRpt, marker);
- va_end(marker);
-
- return hrRpt;
-}
-
#ifndef CROSSGEN_COMPILE
//-----------------------------------------------------------------------------
#pragma warning(disable:6255)
#endif // _PREFAST_
-// Function to parse apart a command line and return the
-// arguments just like argv and argc
-LPWSTR* CommandLineToArgvW(__in LPWSTR lpCmdLine, DWORD *pNumArgs);
#define ISWWHITE(x) ((x)==W(' ') || (x)==W('\t') || (x)==W('\n') || (x)==W('\r') )
BOOL inline FitsInI1(__int64 val)
void NPrintToStdErrA(const char *pszString, size_t nbytes);
void NPrintToStdErrW(const WCHAR *pwzString, size_t nchars);
-//=====================================================================
-// VM-safe wrapper for PostError.
-//
-HRESULT VMPostError( // Returned error.
- HRESULT hrRpt, // Reported error.
- ...); // Error arguments.
-
-
#include "nativevaraccessors.h"
// --------------------------------------------------------------------------------