CRITICAL_SECTION g_dacCritSec;
ClrDataAccess* g_dacImpl;
-HINSTANCE g_thisModule;
EXTERN_C
#ifdef TARGET_UNIX
#endif
InitializeCriticalSection(&g_dacCritSec);
- // Save the module handle.
- g_thisModule = (HINSTANCE)instance;
-
g_procInitialized = true;
break;
}
return TRUE;
}
-HINSTANCE
-GetModuleInst(void)
-{
- return g_thisModule;
-}
-
HRESULT
ConvertUtf8(__in LPCUTF8 utf8,
ULONG32 bufLen,
// Do some validation
IfFailRet(VerifyDlls());
- // To support EH SxS, utilcode requires the base address of the runtime
- // as part of its initialization so that functions like "WasThrownByUs" work correctly since
- // they use the CLR base address to check if an exception was raised by a given instance of the runtime
- // or not.
- //
- // Thus, when DAC is initialized, initialize utilcode with the base address of the runtime loaded in the
- // target process. This is similar to work done in CorDB::SetTargetCLR for mscordbi.
-
- g_hmodCoreCLR = (HINSTANCE)m_globalBase; // Base address of the runtime in the target process
-
return S_OK;
}
DAC_PAL,
};
-// mscordacwks's module handle
-extern HINSTANCE g_thisModule;
-
class ReflectionModule;
struct DAC_MD_IMPORT
return hr;
}
+#ifndef TARGET_UNIX
+extern "C" IMAGE_DOS_HEADER __ImageBase;
+#endif
+
HRESULT ClrDataAccess::GetDacModuleHandle(HMODULE *phModule)
{
if(phModule == NULL)
return E_INVALIDARG;
- *phModule = GetModuleInst();
+
+#ifndef TARGET_UNIX
+ *phModule = (HMODULE)&__ImageBase;
return S_OK;
+#else
+ // hModule is not available under TARGET_UNIX
+ return E_FAIL;
+#endif
}
HRESULT ClrDataAccess::GetRCWData(CLRDATA_ADDRESS addr, struct DacpRCWData *rcwData)
#define SUPPORT_LOCAL_DEBUGGING 1
#endif
-//********** Globals. *********************************************************
-#ifndef HOST_UNIX
-HINSTANCE g_hInst; // Instance handle to this piece of code.
-#endif
-
//-----------------------------------------------------------------------------
// SxS Versioning story for Mscordbi (ICorDebug + friends)
//-----------------------------------------------------------------------------
case DLL_PROCESS_ATTACH:
{
-#ifndef HOST_UNIX
- g_hInst = hInstance;
-#else
+#ifdef HOST_UNIX
int err = PAL_InitializeDLL();
if(err != 0)
{
}
-//*****************************************************************************
-// This helper provides access to the instance handle of the loaded image.
-//*****************************************************************************
-#ifndef TARGET_UNIX
-HINSTANCE GetModuleInst()
-{
- return g_hInst;
-}
-#endif
-
-
//-----------------------------------------------------------------------------
// Substitute for mscoree
//
#ifndef TARGET_UNIX
// PDB format - use diasymreader.dll with COM activation
InlineSString<_MAX_PATH> ssBuf;
- IfFailThrow(GetHModuleDirectory(GetModuleInst(), ssBuf));
+ IfFailThrow(GetClrModuleDirectory(ssBuf));
IfFailThrow(FakeCoCreateInstanceEx(CLSID_CorSymBinder_SxS,
ssBuf.GetUnicode(),
IID_ISymUnmanagedBinder,
/* ------------------------------------------------------------------------- *
* CordbBase class
* ------------------------------------------------------------------------- */
+extern void* GetClrModuleBase();
// Do any initialization necessary for both CorPublish and CorDebug
// This includes enabling logging and adding the SEDebug priv.
unsigned level = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::EXTERNAL_LogLevel, LL_INFO1000);
unsigned bytesPerThread = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_StressLogSize, STRESSLOG_CHUNK_SIZE * 2);
unsigned totalBytes = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_TotalStressLogSize, STRESSLOG_CHUNK_SIZE * 1024);
-#ifndef TARGET_UNIX
- StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, GetModuleInst());
-#else
- StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, NULL);
-#endif
+ StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, GetClrModuleBase());
}
}
m_targetCLR = hmodTargetCLR;
#endif
- // @REVIEW: are we happy with this workaround? It allows us to use the existing
- // infrastructure for instance name decoration, but it really doesn't fit
- // the same model because coreclr.dll isn't in this process and hmodTargetCLR
- // is the debuggee target, not the coreclr.dll to bind utilcode to..
-
- g_hmodCoreCLR = hmodTargetCLR;
-
return S_OK;
}
// These hooks must be removed before shipping.
class ShimProcess;
-
-#ifndef TARGET_UNIX
-extern HINSTANCE GetModuleInst();
-#endif
-
-
template <class T>
class CordbSafeHashTable;
HModuleHolder hDacDll;
PathString wszAccessDllPath;
-#ifdef TARGET_UNIX
- if (!PAL_GetPALDirectoryWrapper(wszAccessDllPath))
- {
- ThrowLastError();
- }
- PCWSTR eeFlavor = MAKEDLLNAME_W(W("mscordaccore"));
-#else
//
// Load the access DLL from the same directory as the the current CLR Debugging Services DLL.
//
-
- if (!WszGetModuleFileName(GetModuleInst(), wszAccessDllPath))
+ if (GetClrModuleDirectory(wszAccessDllPath) != S_OK)
{
ThrowLastError();
}
- if (!SUCCEEDED(CopySystemDirectory(wszAccessDllPath, wszAccessDllPath)))
- {
- ThrowHR(E_INVALIDARG);
- }
-
// Dac Dll is named:
// mscordaccore.dll <-- coreclr
// mscordacwks.dll <-- desktop
- PCWSTR eeFlavor =
- W("mscordaccore.dll");
+ PCWSTR eeFlavor = MAKEDLLNAME_W(W("mscordaccore"));
-#endif // TARGET_UNIX
wszAccessDllPath.Append(eeFlavor);
hDacDll.Assign(WszLoadLibrary(wszAccessDllPath));
// The debugger can then use ReadProcessMemory to read through this array.
ULONG_PTR rgData [] = {
CLRDBG_EXCEPTION_DATA_CHECKSUM,
- (ULONG_PTR) g_hThisInst,
+ (ULONG_PTR)GetClrModuleBase(),
(ULONG_PTR) pManagedEvent
};
// Ignore any notification exceptions sent from code:Debugger.SendRawEvent.
// This is not a common case, but could happen in some cases described
// in SendRawEvent. Either way, Left-Side and VM should just ignore these.
- if (IsEventDebuggerNotification(exception, PTR_TO_CORDB_ADDRESS(g_hThisInst)))
+ if (IsEventDebuggerNotification(exception, PTR_TO_CORDB_ADDRESS(GetClrModuleBase())))
{
return true;
}
// If its not a stub, then maybe its an address in mscoree?
if (result == false)
{
- result = (IsIPInModule(g_hThisInst, (PCODE)stubAddress) == TRUE);
+ result = (IsIPInModule(GetClrModuleBase(), (PCODE)stubAddress) == TRUE);
}
// This is a synchronous event (reply required)
#PAL_fwprintf
#PAL_GetLogicalCpuCountFromOS
#PAL_GetNumaProcessorNode
-#PAL_GetPALDirectoryW
#PAL_get_stdout
#PAL_get_stderr
#PAL_GetApplicationGroupId
#PAL_GetCurrentThread
#PAL_GetCpuLimit
#PAL_GetNativeExceptionHolderHead
+#PAL_GetPalHostModule
#PAL_GetSymbolModuleBase
#PAL_GetTransportPipeName
#PAL_InitializeDLL
#endif // !defined(CROSSGEN_COMPILE) && !defined(CORECLR_EMBEDDED)
-// Globals
-extern HINSTANCE g_hThisInst;
-
-HINSTANCE GetModuleInst()
-{
- LIMITED_METHOD_CONTRACT;
- return (g_hThisInst);
-}
+extern void* GetClrModuleBase();
// ---------------------------------------------------------------------------
// %%Function: MetaDataGetDispenser
return hr;
}
-STDAPI GetCORSystemDirectoryInternaL(SString& pBuffer)
-{
- CONTRACTL {
- NOTHROW;
- GC_NOTRIGGER;
- ENTRY_POINT;
- } CONTRACTL_END;
-
- HRESULT hr = S_OK;
- BEGIN_ENTRYPOINT_NOTHROW;
-
-
-#ifdef CROSSGEN_COMPILE
-
- if (WszGetModuleFileName(NULL, pBuffer) > 0)
- {
- hr = CopySystemDirectory(pBuffer, pBuffer);
- }
- else {
- hr = HRESULT_FROM_GetLastError();
- }
-
-#else
-
- if (!PAL_GetPALDirectoryWrapper(pBuffer)) {
- hr = HRESULT_FROM_GetLastError();
- }
-#endif
-
- END_ENTRYPOINT_NOTHROW;
- return hr;
-}
-
static DWORD g_dwSystemDirectory = 0;
static WCHAR * g_pSystemDirectory = NULL;
// use local buffer for thread safety
PathString wzSystemDirectory;
-
- hr = GetCORSystemDirectoryInternaL(wzSystemDirectory);
+ hr = GetClrModuleDirectory(wzSystemDirectory);
if (FAILED(hr)) {
wzSystemDirectory.Set(W('\0'));
#include "intrinsic.h" // Functions to make intrinsic.
-
-// Helper function returns the instance handle of this module.
-HINSTANCE GetModuleInst();
-
#endif // __STDAFX_H__
FORCEINLINE void VoidClrDeleteCriticalSection(CRITSEC_COOKIE cs) { if (cs != NULL) ClrDeleteCriticalSection(cs); }
typedef Wrapper<CRITSEC_COOKIE, DoNothing<CRITSEC_COOKIE>, VoidClrDeleteCriticalSection, NULL> CRITSEC_AllocationHolder;
-HMODULE GetCLRModule ();
+DWORD GetClrModulePathName(SString& buffer);
extern thread_local int t_CantAllocCount;
extern LPCWSTR CorCompileGetRuntimeDllName(CorCompileRuntimeDlls id);
-// Will always return a valid HMODULE for CLR_INFO, but will return NULL for NGEN_COMPILER_INFO
-// if the DLL has not yet been loaded (it does not try to cause a load).
-extern HMODULE CorCompileGetRuntimeDll(CorCompileRuntimeDlls id);
-
struct CORCOMPILE_RUNTIME_DLL_INFO
{
// This structure can only contain information not updated by authenticode signing. It is required
struct CORCOMPILE_DEPENDENCY;
typedef GUID CORCOMPILE_NGEN_SIGNATURE;
-
-//**********************************************************************
-// Internal versions of shim functions for use by the CLR.
-
-STDAPI GetCORSystemDirectoryInternaL(
- SString& pBuffer
- );
-
-//LONGPATH:TODO: Remove this once Desktop usage has been removed
-STDAPI GetCORSystemDirectoryInternal(
- __out_ecount_part_opt(cchBuffer, *pdwLength) LPWSTR pBuffer,
- DWORD cchBuffer,
- __out_opt DWORD* pdwLength
- );
-
#endif // _CORPRIV_H_
// EOF =======================================================================
_Out_opt_ SString& lpBuffer
);
-BOOL PAL_GetPALDirectoryWrapper(SString& pbuffer);
-
#endif //_WIN_PATH_APIS_WRAPPER_
class StressLog {
public:
static void Initialize(unsigned facilities, unsigned level, unsigned maxBytesPerThread,
- unsigned maxBytesTotal, HMODULE hMod);
+ unsigned maxBytesTotal, void* moduleBase);
static void Terminate(BOOL fProcessDetach=FALSE);
static void ThreadDetach(); // call at DllMain THREAD_DETACH if you want to recycle thread logs
static int NewChunk ()
typedef Wrapper<BSTR, DoNothing, HolderSysFreeString> BSTRHolder;
-// HMODULE_TGT represents a handle to a module in the target process. In non-DAC builds this is identical
-// to HMODULE (HINSTANCE), which is the base address of the module. In DAC builds this must be a target address,
-// and so is represented by TADDR.
-
-#ifdef DACCESS_COMPILE
-typedef TADDR HMODULE_TGT;
-#else
-typedef HMODULE HMODULE_TGT;
-#endif
-
-BOOL IsIPInModule(HMODULE_TGT hModule, PCODE ip);
-
-extern HINSTANCE g_hmodCoreCLR;
+BOOL IsIPInModule(PTR_VOID pModuleBaseAddress, PCODE ip);
namespace UtilCode
{
#undef InterlockedCompareExchangePointer
#define InterlockedCompareExchangePointer Use_InterlockedCompareExchangeT
-// Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL",
+// Returns the directory for clr module. So, if path was for "C:\Dir1\Dir2\Filename.DLL",
// then this would return "C:\Dir1\Dir2\" (note the trailing backslash).
-HRESULT GetHModuleDirectory(HMODULE hMod, SString& wszPath);
+HRESULT GetClrModuleDirectory(SString& wszPath);
HRESULT CopySystemDirectory(const SString& pPathString, SString& pbuffer);
HMODULE LoadLocalizedResourceDLLForSDK(_In_z_ LPCWSTR wzResourceDllName, _In_opt_z_ LPCWSTR modulePath=NULL, bool trySelf=true);
extern void jitShutdown(bool processIsTerminating);
-HINSTANCE g_hInst = nullptr;
-
/*****************************************************************************/
extern "C" DLLEXPORT BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID pvReserved)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
- g_hInst = (HINSTANCE)hInstance;
DisableThreadLibraryCalls((HINSTANCE)hInstance);
}
else if (dwReason == DLL_PROCESS_DETACH)
return TRUE;
}
-
-HINSTANCE GetModuleInst()
-{
- return (g_hInst);
-}
#include "mscoree.h"
#include "corhost.h"
-//********** Locals. **********************************************************
-HINSTANCE GetModuleInst();
-
// @telesto - why does Telesto export any Co-classes at all?
// This map contains the list of coclasses which are exported from this module.
#include "intrinsic.h" // Functions to make intrinsic.
-
-
-// Helper function returns the instance handle of this module.
-HINSTANCE GetModuleInst();
IN HINSTANCE hInstance);
PALIMPORT
-BOOL
-PALAPI
-PAL_GetPALDirectoryW(
- OUT LPWSTR lpDirectoryName,
- IN OUT UINT* cchDirectoryName);
-
-#define PAL_GetPALDirectory PAL_GetPALDirectoryW
-
-PALIMPORT
VOID
PALAPI
PAL_Random(
#endif
// Some Helper Definitions
-BOOL
-PAL_GetPALDirectoryW(
- PathWCharString& lpDirectoryName);
-
DWORD
GetCurrentDirectoryA(
PathCharString& lpBuffer);
Abstract:
A replacement for PAL_Initialize when loading CoreCLR. Instead of taking a command line (which CoreCLR
- instances aren't given anyway) the path into which the CoreCLR is installed is supplied instead. This is
- cached so that PAL_GetPALDirectoryW can return it later.
+ instances aren't given anyway) the path into which the CoreCLR is installed is supplied instead.
This routine also makes sure the psuedo dynamic libraries PALRT and mscorwks have their initialization
methods called.
static const char URANDOM_DEVICE_NAME[]="/dev/urandom";
-/*++
-
-Function :
-
- PAL_GetPALDirectoryW
-
- Returns the fully qualified path name
- where the PALL DLL was loaded from.
-
- On failure it returns FALSE and sets the
- proper LastError code.
-
---*/
-BOOL
-PAL_GetPALDirectoryW(PathWCharString& lpDirectoryName)
-{
- LPCWSTR lpFullPathAndName = NULL;
- LPCWSTR lpEndPoint = NULL;
- BOOL bRet = FALSE;
-
- PERF_ENTRY(PAL_GetPALDirectoryW);
-
- MODSTRUCT *module = LOADGetPalLibrary();
- if (!module)
- {
- SetLastError(ERROR_INTERNAL_ERROR);
- goto EXIT;
- }
- lpFullPathAndName = module->lib_name;
- if (lpFullPathAndName == NULL)
- {
- SetLastError(ERROR_INTERNAL_ERROR);
- goto EXIT;
- }
- lpEndPoint = PAL_wcsrchr( lpFullPathAndName, '/' );
- if ( lpEndPoint )
- {
- /* The path that we return is required to have
- the trailing slash on the end.*/
- lpEndPoint++;
-
-
- if(!lpDirectoryName.Set(lpFullPathAndName,lpEndPoint - lpFullPathAndName))
- {
- ASSERT( "The buffer was not large enough.\n" );
- SetLastError( ERROR_INSUFFICIENT_BUFFER );
- goto EXIT;
- }
-
- bRet = TRUE;
- }
- else
- {
- ASSERT( "Unable to determine the path.\n" );
- /* Error path, should not be executed. */
- SetLastError( ERROR_INTERNAL_ERROR );
- }
-
-EXIT:
- PERF_EXIT(PAL_GetPALDirectoryW);
- return bRet;
-}
-
-/*++
-
-Function :
-
- PAL_GetPALDirectoryW
-
- Returns the fully qualified path name
- where the PALL DLL was loaded from.
-
- On failure it returns FALSE and sets the
- proper LastError code.
-
---*/
-PALIMPORT
-BOOL
-PALAPI
-PAL_GetPALDirectoryW( OUT LPWSTR lpDirectoryName, IN OUT UINT* cchDirectoryName )
-{
- PathWCharString directory;
- BOOL bRet;
- PERF_ENTRY(PAL_GetPALDirectoryW);
- ENTRY( "PAL_GetPALDirectoryW( %p, %d )\n", lpDirectoryName, *cchDirectoryName );
-
- bRet = PAL_GetPALDirectoryW(directory);
-
- if (bRet) {
-
- if (directory.GetCount() > *cchDirectoryName)
- {
- SetLastError( ERROR_INSUFFICIENT_BUFFER );
- bRet = FALSE;
- }
- else
- {
- PAL_wcscpy(lpDirectoryName, directory.GetString());
- }
-
- *cchDirectoryName = directory.GetCount();
- }
-
- LOGEXIT( "PAL_GetPALDirectoryW returns BOOL %d.\n", bRet);
- PERF_EXIT(PAL_GetPALDirectoryW);
- return bRet;
-
-}
-
VOID
PALAPI
PAL_Random(
miscellaneous/SetLastError/test1/test.cpp
miscellaneous/_i64tow/test1/test1.cpp
pal_specific/PAL_errno/test1/PAL_errno.cpp
- pal_specific/PAL_GetPALDirectoryW/test1/PAL_GetPALDirectoryW.cpp
# pal_specific/PAL_GetUserTempDirectoryW/test1/PAL_GetUserTempDirectoryW.cpp
#pal_specific/PAL_get_stderr/test1/PAL_get_stderr.cpp
#pal_specific/PAL_get_stdin/test1/PAL_get_stdin.cpp
miscellaneous/SetLastError/test1/paltest_setlasterror_test1
miscellaneous/_i64tow/test1/paltest_i64tow_test1
pal_specific/PAL_errno/test1/paltest_pal_errno_test1
-pal_specific/PAL_GetPALDirectoryW/test1/paltest_pal_getpaldirectoryw_test1
pal_specific/PAL_GetUserTempDirectoryW/test1/paltest_pal_getusertempdirectoryw_test1
pal_specific/PAL_Initialize_Terminate/test1/paltest_pal_initialize_terminate_test1
pal_specific/PAL_Initialize_Terminate/test2/paltest_pal_initialize_terminate_test2
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-/*=============================================================
-**
-** Source: pal_getpaldirectoryw.c
-**
-** Purpose: Positive test the PAL_GetPALDirectoryW API.
-** Call this API to retrieve a fully-qualified
-** directory name where the PAL DLL is loaded from.
-**
-**
-**============================================================*/
-#define UNICODE
-#include <palsuite.h>
-
-PALTEST(pal_specific_PAL_GetPALDirectoryW_test1_paltest_pal_getpaldirectoryw_test1, "pal_specific/PAL_GetPALDirectoryW/test1/paltest_pal_getpaldirectoryw_test1")
-{
- int err;
- BOOL bValue;
- DWORD dwFileAttribute;
- WCHAR *wpDirectoryName = NULL;
- char *pDirectoryName = NULL;
-
- /*Initialize the PAL environment*/
- err = PAL_Initialize(argc, argv);
- if(0 != err)
- {
- return FAIL;
- }
-
- /*allocate momory to store the directory name*/
- wpDirectoryName = (WCHAR*)malloc(MAX_PATH*sizeof(WCHAR));
- if(NULL == wpDirectoryName)
- {
- Fail("\nFailed to allocate memory for storing directory name!\n");
- }
-
- UINT size = MAX_PATH;
- /*retrieve the machine configuration directory*/
- bValue = PAL_GetPALDirectoryW(wpDirectoryName, &size);
- if(FALSE == bValue)
- {
- free(wpDirectoryName);
- Fail("Failed to call PAL_GetPALDirectoryW API, "
- "error code =%u\n", GetLastError());
- }
-
-
- /*convert wide char string to a standard one*/
- pDirectoryName = convertC(wpDirectoryName);
- if(0 == strlen(pDirectoryName))
- {
- free(wpDirectoryName);
- free(pDirectoryName);
- Fail("The retrieved directory name string is empty!\n");
- }
-
- /*free the memory*/
- free(pDirectoryName);
-
- /*retrieve the attribute of a file or directory*/
- dwFileAttribute = GetFileAttributesW(wpDirectoryName);
-
- /*free the memory*/
- free(wpDirectoryName);
-
- /*check if the attribute indicates a directory*/
- if(FILE_ATTRIBUTE_DIRECTORY !=
- (dwFileAttribute & FILE_ATTRIBUTE_DIRECTORY))
- {
- Fail("The retrieved directory name is not a valid directory!\n");
- }
-
- PAL_Terminate();
- return PASS;
-}
miscellaneous/MessageBoxW/test2/paltest_messageboxw_test2
miscellaneous/wsprintfW/test2/paltest_wsprintfw_test2
miscellaneous/wsprintfW/test7/paltest_wsprintfw_test7
-pal_specific/PAL_GetPALDirectoryW/test1/paltest_pal_getpaldirectoryw_test1
pal_specific/PAL_GetUserTempDirectoryW/test1/paltest_pal_getusertempdirectoryw_test1
pal_specific/PAL_get_stderr/test1/paltest_pal_get_stderr_test1
pal_specific/PAL_get_stdin/test1/paltest_pal_get_stdin_test1
if(CLR_CMAKE_HOST_UNIX)
target_link_libraries(crossgen
mscorrc
- coreclrpal
palrt
+ coreclrpal
)
else()
target_link_libraries(crossgen
}
}
-extern HMODULE g_hThisInst;
-
int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv)
{
-#ifndef TARGET_UNIX
- g_hThisInst = WszGetModuleHandle(NULL);
-#endif
-
/////////////////////////////////////////////////////////////////////////
//
// Parse the arguments
#include <stdlib.h>
// External prototypes.
-extern HINSTANCE GetModuleInst();
+extern void* GetClrModuleBase();
//*****************************************************************************
// Do the mapping from an langId to an hinstance node
#ifdef CROSSGEN_COMPILE
// The resources are embeded into the .exe itself for crossgen
- *pHInst = GetModuleInst();
+ *pHInst = (HINSTANCE)GetClrModuleBase();
#else
#ifdef SELF_NO_HOST
// Try first in the same directory as this dll.
- hr = GetCORSystemDirectoryInternaL(rcPath);
+ hr = GetClrModuleDirectory(rcPath);
if (FAILED(hr))
return hr;
#include "clrnt.h"
#include "contract.h"
-HINSTANCE g_hmodCoreCLR;
+#if HOST_WINDOWS
+extern "C" IMAGE_DOS_HEADER __ImageBase;
+#else
+static void* pImageBase = NULL;
+#endif
+
+void* GetClrModuleBase()
+{
+ LIMITED_METHOD_CONTRACT;
+
+#if HOST_WINDOWS
+ return (void*)&__ImageBase;
+#else // HOST_WINDOWS
+ // PAL_GetSymbolModuleBase defers to dladdr, which is typically a hash lookup through symbols.
+ // It should be fairly fast, however it may take a loader lock, so we will cache the result.
+ void* pRet = VolatileLoadWithoutBarrier(&pImageBase);
+ if (!pRet)
+ {
+ pImageBase = pRet = (void*)PAL_GetSymbolModuleBase((void*)GetClrModuleBase);
+ }
+
+ return pRet;
+#endif // HOST_WINDOWS
+}
thread_local int t_CantAllocCount;
#endif // FAILPOINTS_ENABLED
-
-
-//-----------------------------------------------------------------------------------
-// This is the approved way to get a module handle to mscorwks.dll (or coreclr.dll).
-// Never call GetModuleHandle(mscorwks) yourself as this will break side-by-side inproc.
-//
-// This function is safe to call before or during CRT initialization. It can not
-// legally return NULL (it only does so in the case of a broken build invariant.)
-//
-// TODO puCLR SxS utilcode work: Since this is never supposed to return NULL, it should
-// not be present in SELF_NO_HOST builds of utilcode where there isn't necessarily a
-// CLR in the process. We should also ASSERT that GetModuleHandleA isn't returning
-// NULL below - we've probably been getting away with this in SELF_NO_HOST cases like
-// mscordbi.dll.
-//-----------------------------------------------------------------------------------
-HMODULE GetCLRModule ()
+DWORD GetClrModulePathName(SString& buffer)
{
- //! WARNING: At the time this function is invoked, the C Runtime has NOT been fully initialized, let alone the CLR.
- //! So don't put in a runtime contract and don't invoke other functions in the CLR (not even _ASSERTE!)
-
- STATIC_CONTRACT_NOTHROW;
- STATIC_CONTRACT_SUPPORTS_DAC; // DAC can call in here since we initialize the SxS callbacks in ClrDataAccess::Initialize.
-
- // You got here because the dll that included this copy of utilcode.lib.
- // did not set g_hmodCoreCLR. The most likely cause is that you're running
- // a dll (other than coreclr.dll) that links to utilcode.lib.
- _ASSERTE(g_hmodCoreCLR != NULL);
-
- return g_hmodCoreCLR;
+#ifdef HOST_WINDOWS
+ return WszGetModuleFileName((HINSTANCE)GetClrModuleBase(), buffer);
+#else
+ return WszGetModuleFileName(PAL_GetPalHostModule(), buffer);
+#endif
}
-
-
#if defined(SELF_NO_HOST)
HMODULE CLRLoadLibrary(LPCWSTR lpLibFileName)
// and it will do nothing.
void GetLastThrownObjectExceptionFromThread(Exception **ppException);
+// Helper function to get pointer to clr module base
+void* GetClrModuleBase();
+
Exception *Exception::g_OOMException = NULL;
// avoid global constructors
exceptionArgs[0] = arg0;
#if !defined(FEATURE_UTILCODE_NO_DEPENDENCIES)
- exceptionArgs[INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE - 1] = (ULONG_PTR) (GetCLRModule());
+ exceptionArgs[INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE - 1] = (ULONG_PTR)GetClrModuleBase();
#endif // !defined(FEATURE_UTILCODE_NO_DEPENDENCIES)
return INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE;
return FALSE;
}
#if!defined(FEATURE_UTILCODE_NO_DEPENDENCIES)
- if ( ((ULONG_PTR)(GetCLRModule())) != pcER->ExceptionInformation[INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE - 1] )
+ if ((ULONG_PTR)GetClrModuleBase() != pcER->ExceptionInformation[INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE - 1] )
{
return FALSE;
}
}
#endif // HOST_WINDOWS
-
-#ifdef HOST_WINDOWS
-
-#if ! defined(DACCESS_COMPILE) && !defined(SELF_NO_HOST)
-extern HINSTANCE g_hThisInst;
-#endif// ! defined(DACCESS_COMPILE) && !defined(SELF_NO_HOST)
-
-BOOL PAL_GetPALDirectoryWrapper(SString& pbuffer)
-{
-
- HRESULT hr = S_OK;
-
- PathString pPath;
- DWORD dwPath;
- HINSTANCE hinst = NULL;
-
-#if ! defined(DACCESS_COMPILE) && !defined(SELF_NO_HOST)
- hinst = g_hThisInst;
-#endif// ! defined(DACCESS_COMPILE) && !defined(SELF_NO_HOST)
-
-#ifndef CROSSGEN_COMPILE
- _ASSERTE(hinst != NULL);
-#endif
-
- dwPath = WszGetModuleFileName(hinst, pPath);
-
- if(dwPath == 0)
- {
- hr = HRESULT_FROM_GetLastErrorNA();
- }
- else
- {
- hr = CopySystemDirectory(pPath, pbuffer);
- }
-
- return (hr == S_OK);
-}
-
-#else
-
-BOOL PAL_GetPALDirectoryWrapper(SString& pbuffer)
-{
- BOOL retval = FALSE;
- COUNT_T size = MAX_LONGPATH;
-
- if(!(retval = PAL_GetPALDirectoryW(pbuffer.OpenUnicodeBuffer(size - 1), &size)))
- {
- pbuffer.CloseBuffer(0);
- retval = PAL_GetPALDirectoryW(pbuffer.OpenUnicodeBuffer(size - 1), &size);
- }
-
- pbuffer.CloseBuffer(size);
-
- return retval;
-}
-
-#endif // HOST_WINDOWS
-
-
//Implementation of LongFile Helpers
const WCHAR LongFile::DirectorySeparatorChar = W('\\');
const WCHAR LongFile::AltDirectorySeparatorChar = W('/');
}
-// Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL",
-// then this would return "C:\Dir1\Dir2\" (note the trailing backslash).
-HRESULT GetHModuleDirectory(
- __in HMODULE hMod,
- SString& wszPath)
+// Returns the directory for clr module. So, if path was for "C:\Dir1\Dir2\Filename.DLL",
+// then this would return "C:\Dir1\Dir2\" (note the trailing backslash).HRESULT GetClrModuleDirectory(SString& wszPath)
+HRESULT GetClrModuleDirectory(SString& wszPath)
{
CONTRACTL
{
}
CONTRACTL_END;
- DWORD dwRet = WszGetModuleFileName(hMod, wszPath);
+ DWORD dwRet = GetClrModulePathName(wszPath);
- if (dwRet == 0)
+ if (dwRet == 0)
{ // Some other error.
return HRESULT_FROM_GetLastError();
}
- CopySystemDirectory(wszPath, wszPath);
-
-
+ CopySystemDirectory(wszPath, wszPath);
return S_OK;
}
/*********************************************************************************/
void StressLog::Initialize(unsigned facilities, unsigned level, unsigned maxBytesPerThread,
- unsigned maxBytesTotal, HMODULE hMod)
+ unsigned maxBytesTotal, void* moduleBase)
{
STATIC_CONTRACT_LEAF;
GetSystemTimeAsFileTime (&theLog.startTime);
theLog.startTimeStamp = getTimeStamp();
+ theLog.moduleOffset = (SIZE_T)moduleBase;
#ifndef HOST_UNIX
- theLog.moduleOffset = (SIZE_T)hMod; // HMODULES are base addresses.
-
#ifdef _DEBUG
HMODULE hModNtdll = GetModuleHandleA("ntdll.dll");
theLog.RtlCaptureStackBackTrace = reinterpret_cast<PFNRtlCaptureStackBackTrace>(
GetProcAddress(hModNtdll, "RtlCaptureStackBackTrace"));
#endif // _DEBUG
-
-#else // !HOST_UNIX
- theLog.moduleOffset = (SIZE_T)PAL_GetSymbolModuleBase((void *)StressLog::Initialize);
#endif // !HOST_UNIX
#if !defined (STRESS_LOG_READONLY) && defined(HOST_WINDOWS)
//======================================================================
// This function returns true, if it can determine that the instruction pointer
// refers to a code address that belongs in the range of the given image.
-// <TODO>@TODO: Merge with IsIPInModule from vm\util.hpp</TODO>
-
-BOOL IsIPInModule(HMODULE_TGT hModule, PCODE ip)
+BOOL IsIPInModule(PTR_VOID pModuleBaseAddress, PCODE ip)
{
STATIC_CONTRACT_LEAF;
SUPPORTS_DAC;
struct Param
{
- HMODULE_TGT hModule;
+ PTR_VOID pModuleBaseAddress;
PCODE ip;
BOOL fRet;
} param;
- param.hModule = hModule;
+ param.pModuleBaseAddress = pModuleBaseAddress;
param.ip = ip;
param.fRet = FALSE;
#ifdef HOST_WINDOWS
PAL_TRY(Param *, pParam, ¶m)
{
- PTR_BYTE pBase = dac_cast<PTR_BYTE>(pParam->hModule);
+ PTR_BYTE pBase = dac_cast<PTR_BYTE>(pParam->pModuleBaseAddress);
PTR_IMAGE_DOS_HEADER pDOS = NULL;
PTR_IMAGE_NT_HEADERS pNT = NULL;
if (FAILED(hr))
{
PathString symbolReaderPath;
- hr = GetHModuleDirectory(GetModuleInst(), symbolReaderPath);
+ hr = GetClrModuleDirectory(symbolReaderPath);
if (FAILED(hr))
{
RETURN (NULL);
{
g_fEEInit = true;
-#if CORECLR_EMBEDDED
-
-#ifdef TARGET_WINDOWS
- HINSTANCE curModule = WszGetModuleHandle(NULL);
-#else
- HINSTANCE curModule = PAL_GetPalHostModule();
-#endif
-
- g_hmodCoreCLR = curModule;
- g_hThisInst = curModule;
-#endif
-
#ifndef CROSSGEN_COMPILE
// We cache the SystemInfo for anyone to use throughout the life of the EE.
unsigned level = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::EXTERNAL_LogLevel, LL_INFO1000);
unsigned bytesPerThread = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_StressLogSize, STRESSLOG_CHUNK_SIZE * 4);
unsigned totalBytes = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_TotalStressLogSize, STRESSLOG_CHUNK_SIZE * 1024);
- StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, GetModuleInst());
+ StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, GetClrModuleBase());
g_pStressLog = &StressLog::theLog;
}
#endif
#ifndef TARGET_UNIX
{
// Record mscorwks geometry
- PEDecoder pe(g_hThisInst);
+ PEDecoder pe(GetClrModuleBase());
g_runtimeLoadedBaseAddress = (SIZE_T)pe.GetBase();
g_runtimeVirtualSize = (SIZE_T)pe.GetVirtualSize();
switch (pParam->dwReason)
{
- case DLL_PROCESS_ATTACH:
- {
- g_hmodCoreCLR = pParam->hInst;
- // Save the module handle.
- g_hThisInst = pParam->hInst;
- break;
- }
-
case DLL_PROCESS_DETACH:
{
// lpReserved is NULL if we're here because someone called FreeLibrary
HRESULT hr = E_FAIL;
PathString CoreClrFolderHolder;
- extern HINSTANCE g_hThisInst;
bool havePath = false;
- if (WszGetModuleFileName(g_hThisInst, CoreClrFolderHolder))
+ if (GetClrModulePathName(CoreClrFolderHolder))
{
// Load JIT from next to CoreCLR binary
havePath = true;
#include "gcstress.h"
HRESULT EnsureRtlFunctions();
-HINSTANCE GetModuleInst();
+
+// Helper function returns the base of clr module.
+void* GetClrModuleBase();
#if defined(TARGET_X86) || defined(TARGET_AMD64)
//
EX_TRY
{
PathString wszDACPath;
- if (SUCCEEDED(::GetCORSystemDirectoryInternaL(wszDACPath)))
+ if (SUCCEEDED(::GetClrModuleDirectory(wszDACPath)))
{
wszDACPath.Append(wszDACName);
- hr = (*pFnWerRegisterRuntimeExceptionModule)(wszDACPath, (PDWORD)g_hThisInst);
+ hr = (*pFnWerRegisterRuntimeExceptionModule)(wszDACPath, (PDWORD)GetClrModuleBase());
}
else {
hr = E_FAIL;
addressString.Printf(W("%p"), pExceptionInfo? (UINT_PTR)pExceptionInfo->ExceptionRecord->ExceptionAddress : address);
// We should always have the reference to the runtime's instance
- _ASSERTE(g_hThisInst != NULL);
+ _ASSERTE(GetClrModuleBase() != NULL);
// Setup the string to contain the runtime's base address. Thus, when customers report FEEE with just
// the event log entry containing this string, we can use the absolute and base addresses to determine
// where the fault happened inside the runtime.
SmallStackSString runtimeBaseAddressString;
- runtimeBaseAddressString.Printf(W("%p"), g_hThisInst);
+ runtimeBaseAddressString.Printf(W("%p"), GetClrModuleBase());
SmallStackSString exitCodeString;
exitCodeString.Printf(W("%x"), exitCode);
PCWSTR lpwszCommandLine = W("");
- // if WszGetModuleFileName fails, we return an empty string
- if (!WszGetModuleFileName(GetCLRModule(), dllPath)) {
+ // if GetClrModulePathName fails, we return an empty string
+ if (!GetClrModulePathName(dllPath)) {
dllPath.Set(W("\0"));
}
-
if(type == ETW::InfoLog::InfoStructs::Callback)
{
FireEtwRuntimeInformationDCStart( GetClrInstanceId(),
const char* DumpGeneratorName = "createdump.exe";
PathString coreclrPath;
- if (WszGetModuleFileName(GetCLRModule(), coreclrPath))
+ if (GetClrModulePathName(coreclrPath))
{
SString::CIterator lastBackslash = coreclrPath.End();
if (coreclrPath.FindBack(lastBackslash, W('\\')))
CONTRACT_VIOLATION(TakesLockViolation);
fExternalException = (!ExecutionManager::IsManagedCode(GetIP(pExceptionInfo->ContextRecord)) &&
- !IsIPInModule(g_hThisInst, GetIP(pExceptionInfo->ContextRecord)));
+ !IsIPInModule(GetClrModuleBase(), GetIP(pExceptionInfo->ContextRecord)));
}
if (fExternalException)
if ((!fAVisOk) && !(pExceptionRecord->ExceptionFlags & EXCEPTION_UNWINDING))
{
PCODE ip = (PCODE)GetIP(pContext);
- if (IsIPInModule(g_hThisInst, ip) || IsIPInModule(GCHeapUtilities::GetGCModule(), ip))
+ if (IsIPInModule(GetClrModuleBase(), ip) || IsIPInModule(GCHeapUtilities::GetGCModuleBase(), ip))
{
CONTRACT_VIOLATION(ThrowsViolation|FaultViolation);
BOOL fExternalException;
fExternalException = (!ExecutionManager::IsManagedCode(ip) &&
- !IsIPInModule(g_hThisInst, ip));
+ !IsIPInModule(GetClrModuleBase(), ip));
if (fExternalException)
{
fIsCallerInVM = !ExecutionManager::IsManagedCode(callerIP);
#else
#if defined(DACCESS_COMPILE)
- HMODULE_TGT hEE = DacGlobalBase();
+ PTR_VOID eeBase = DacGlobalBase();
#else // !DACCESS_COMPILE
- HMODULE_TGT hEE = g_hThisInst;
+ PTR_VOID eeBase = GetClrModuleBase();
#endif // !DACCESS_COMPILE
- fIsCallerInVM = IsIPInModule(hEE, callerIP);
+ fIsCallerInVM = IsIPInModule(eeBase, callerIP);
#endif // TARGET_UNIX
if (!fIsCallerInVM)
VersionInfo g_gc_version_info;
// The module that contains the GC.
-HMODULE g_gc_module;
+PTR_VOID g_gc_module_base;
// GC entrypoints for the the linked-in GC. These symbols are invoked
// directly if we are not using a standalone GC.
#ifndef DACCESS_COMPILE
-HMODULE GCHeapUtilities::GetGCModule()
+PTR_VOID GCHeapUtilities::GetGCModuleBase()
{
- assert(g_gc_module);
- return g_gc_module;
+ assert(g_gc_module_base);
+ return g_gc_module_base;
}
namespace
// to "publish" it by assigning it to g_pGCHeap.
//
// This function can proceed concurrently with StashKeywordAndLevel below.
-void FinalizeLoad(IGCHeap* gcHeap, IGCHandleManager* handleMgr, HMODULE gcModule)
+void FinalizeLoad(IGCHeap* gcHeap, IGCHandleManager* handleMgr, PTR_VOID pGcModuleBase)
{
g_pGCHeap = gcHeap;
g_pGCHandleManager = handleMgr;
g_gcDacGlobals = &g_gc_dac_vars;
g_gc_load_status = GC_LOAD_STATUS_LOAD_COMPLETE;
- g_gc_module = gcModule;
+ g_gc_module_base = pGcModuleBase;
LOG((LF_GC, LL_INFO100, "GC load successful\n"));
}
HRESULT initResult = initFunc(gcToClr, &heap, &manager, &g_gc_dac_vars);
if (initResult == S_OK)
{
- FinalizeLoad(heap, manager, hMod);
+ PTR_VOID pGcModuleBase;
+
+#if TARGET_WINDOWS
+ pGcModuleBase = (PTR_VOID)hMod;
+#else
+ pGcModuleBase = (PTR_VOID)PAL_GetSymbolModuleBase((PVOID)initFunc);
+#endif
+
+ FinalizeLoad(heap, manager, pGcModuleBase);
}
else
{
HRESULT initResult = GC_Initialize(nullptr, &heap, &manager, &g_gc_dac_vars);
if (initResult == S_OK)
{
- FinalizeLoad(heap, manager, GetModuleInst());
+ FinalizeLoad(heap, manager, GetClrModuleBase());
}
else
{
#endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
#ifndef DACCESS_COMPILE
- // Gets the module that contains the GC.
- static HMODULE GetGCModule();
+ // Gets a pointer to the module that contains the GC.
+ static PTR_VOID GetGCModuleBase();
// Loads (if using a standalone GC) and initializes the GC.
static HRESULT LoadAndInitialize();
CONTRACT_VIOLATION(ThrowsViolation);
// Get reference to MSCORWKS image in memory...
- PEDecoder pe(g_hThisInst);
+ PEDecoder pe(GetClrModuleBase());
// Find the UEF section from the image
IMAGE_SECTION_HEADER* pUEFSection = pe.FindSection(CLR_UEF_SECTION_NAME);
{
#ifdef TARGET_X86
- IMAGE_DOS_HEADER *pDOS = (IMAGE_DOS_HEADER *)g_hThisInst;
+ IMAGE_DOS_HEADER *pDOS = (IMAGE_DOS_HEADER *)GetClrModuleBase();
_ASSERTE(pDOS->e_magic == VAL16(IMAGE_DOS_SIGNATURE) && pDOS->e_lfanew != 0);
- IMAGE_NT_HEADERS *pNT = (IMAGE_NT_HEADERS*)((LPBYTE)g_hThisInst + VAL32(pDOS->e_lfanew));
+ IMAGE_NT_HEADERS *pNT = (IMAGE_NT_HEADERS*)((LPBYTE)GetClrModuleBase() + VAL32(pDOS->e_lfanew));
#ifdef HOST_64BIT
_ASSERTE(pNT->Signature == VAL32(IMAGE_NT_SIGNATURE)
&& pNT->FileHeader.SizeOfOptionalHeader == VAL16(sizeof(IMAGE_OPTIONAL_HEADER64))
#else // TARGET_X86
// Is the address in mscoree.dll at all? (All helpers are in
// mscoree.dll)
- if (dynamicHlpFunc->pfnHelper >= (LPBYTE*)g_hThisInst && dynamicHlpFunc->pfnHelper < (LPBYTE*)g_hThisInst + VAL32(pNT->OptionalHeader.SizeOfImage))
+ if (dynamicHlpFunc->pfnHelper >= (LPBYTE*)GetClrModuleBase() && dynamicHlpFunc->pfnHelper < (LPBYTE*)GetClrModuleBase() + VAL32(pNT->OptionalHeader.SizeOfImage))
{
// See note above. How do I get the size on x86 for a static method?
hlpFuncCount->helperSize = 0;
return CorCompileRuntimeDllNames[id];
}
-#ifndef CROSSGEN_COMPILE
-
-//==============================================================================
-// Will always return a valid HMODULE for CLR_INFO, but will return NULL for NGEN_COMPILER_INFO
-// if the DLL has not yet been loaded (it does not try to cause a load).
-
-extern HMODULE CorCompileGetRuntimeDll(CorCompileRuntimeDlls id)
-{
- CONTRACTL
- {
- THROWS;
- GC_NOTRIGGER;
- MODE_ANY;
- INJECT_FAULT(COMPlusThrowOM(););
- }
- CONTRACTL_END;
-
- // Currently special cased for every entry.
- static_assert_no_msg(NUM_RUNTIME_DLLS == 2);
- static_assert_no_msg(CORECLR_INFO == 0);
-
- HMODULE hMod = NULL;
-
- // Try to load the correct DLL
- switch (id)
- {
- case CORECLR_INFO:
- hMod = GetCLRModule();
- break;
-
- default:
- COMPlusThrowNonLocalized(kExecutionEngineException,
- W("Invalid runtime DLL ID"));
- break;
- }
-
- return hMod;
-}
-#endif // CROSSGEN_COMPILE
-
//===========================================================================================================
// Validates that an NI matches the running CLR, OS, CPU, etc.
//
// Return the parent assembly for this module if desired.
if (pAssemblyId != NULL)
{
- // Lie and say the assembly isn't avaialable until we are loaded (even though it is.)
+ // Lie and say the assembly isn't available until we are loaded (even though it is.)
// This is for backward compatibilty - we may want to change it
if (pModule->IsProfilerNotified())
{
NULL
);
- if (((UINT_PTR)g_hThisInst) != uImageBase)
+ if (((UINT_PTR)GetClrModuleBase()) != uImageBase)
{
break;
}
Volatile<LONG> g_TrapReturningThreads;
-HINSTANCE g_hThisInst;
BBSweep g_BBSweep;
#ifdef _DEBUG
extern "C" Volatile<LONG> g_TrapReturningThreads;
-EXTERN HINSTANCE g_hThisInst;
EXTERN BBSweep g_BBSweep;
EXTERN IBCLogger g_IBCLogger;
// Note: FEATURE_MERGE_JIT_AND_ENGINE is defined for the Desktop crossgen compilation as well.
//
PathString CoreClrFolder;
- extern HINSTANCE g_hThisInst;
#if !defined(FEATURE_MERGE_JIT_AND_ENGINE)
if (m_fDontLoadJit)
}
else
#endif // !defined(FEATURE_MERGE_JIT_AND_ENGINE)
- if (WszGetModuleFileName(g_hThisInst, CoreClrFolder))
{
- hr = CopySystemDirectory(CoreClrFolder, CoreClrFolder);
+ hr = GetClrModuleDirectory(CoreClrFolder);
if (SUCCEEDED(hr))
{
CoreClrFolder.Append(pwzJitName);
-
}
}
set(CORECLR_LIBRARIES
${CORECLR_STATIC_LIB_LOCATION}/libcoreclr_static.a
${CORECLR_STATIC_LIB_LOCATION}/libSystem.Globalization.Native.a
- ${CORECLR_STATIC_LIB_LOCATION}/libcoreclrpal.a
${CORECLR_STATIC_LIB_LOCATION}/libpalrt.a
+ ${CORECLR_STATIC_LIB_LOCATION}/libcoreclrpal.a
${CORECLR_STATIC_LIB_LOCATION}/libeventprovider.a
${CORECLR_STATIC_LIB_LOCATION}/libnativeresourcestring.a
)