msvcrt: Import cbrt implementation from musl.
[wine.git] / dlls / mscoree / metahost.c
blobacefb2887caca3ab0841827e07d8a3aa10cf4bec
1 /*
2 * ICLRMetaHost - discovery and management of available .NET runtimes
4 * Copyright 2010 Vincent Povirk for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdio.h>
22 #include <stdarg.h>
23 #include <assert.h>
25 #define COBJMACROS
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winreg.h"
30 #include "winternl.h"
31 #include "ole2.h"
32 #include "shlwapi.h"
34 #include "corerror.h"
35 #include "cor.h"
36 #include "mscoree.h"
37 #include "corhdr.h"
38 #include "cordebug.h"
39 #include "metahost.h"
40 #include "fusion.h"
41 #include "wine/list.h"
42 #include "wine/heap.h"
43 #include "mscoree_private.h"
45 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL( mscoree );
49 static const struct ICLRRuntimeInfoVtbl CLRRuntimeInfoVtbl;
51 #define NUM_RUNTIMES 4
53 static struct CLRRuntimeInfo runtimes[NUM_RUNTIMES] = {
54 {{&CLRRuntimeInfoVtbl}, 1, 0, 3705, 0},
55 {{&CLRRuntimeInfoVtbl}, 1, 1, 4322, 0},
56 {{&CLRRuntimeInfoVtbl}, 2, 0, 50727, 0},
57 {{&CLRRuntimeInfoVtbl}, 4, 0, 30319, 0}
60 static CRITICAL_SECTION runtime_list_cs;
61 static CRITICAL_SECTION_DEBUG runtime_list_cs_debug =
63 0, 0, &runtime_list_cs,
64 { &runtime_list_cs_debug.ProcessLocksList,
65 &runtime_list_cs_debug.ProcessLocksList },
66 0, 0, { (DWORD_PTR)(__FILE__ ": runtime_list_cs") }
68 static CRITICAL_SECTION runtime_list_cs = { &runtime_list_cs_debug, -1, 0, 0, 0, 0 };
70 struct CLRMetaHost
72 ICLRMetaHost ICLRMetaHost_iface;
74 RuntimeLoadedCallbackFnPtr callback;
77 static struct CLRMetaHost GlobalCLRMetaHost;
79 static HMODULE mono_handle;
81 BOOL is_mono_started;
82 static BOOL is_mono_shutdown;
84 typedef struct _MonoProfilerDesc *MonoProfilerHandle;
86 typedef void (CDECL *MonoProfilerRuntimeShutdownBeginCallback) (MonoProfiler *prof);
88 MonoImage* (CDECL *mono_assembly_get_image)(MonoAssembly *assembly);
89 MonoAssembly* (CDECL *mono_assembly_load_from)(MonoImage *image, const char *fname, MonoImageOpenStatus *status);
90 const char* (CDECL *mono_assembly_name_get_name)(MonoAssemblyName *aname);
91 const char* (CDECL *mono_assembly_name_get_culture)(MonoAssemblyName *aname);
92 MonoAssembly* (CDECL *mono_assembly_open)(const char *filename, MonoImageOpenStatus *status);
93 void (CDECL *mono_callspec_set_assembly)(MonoAssembly *assembly);
94 MonoClass* (CDECL *mono_class_from_mono_type)(MonoType *type);
95 MonoClass* (CDECL *mono_class_from_name)(MonoImage *image, const char* name_space, const char *name);
96 MonoMethod* (CDECL *mono_class_get_method_from_name)(MonoClass *klass, const char *name, int param_count);
97 static void (CDECL *mono_config_parse)(const char *filename);
98 MonoDomain* (CDECL *mono_domain_get)(void);
99 MonoDomain* (CDECL *mono_domain_get_by_id)(int id);
100 BOOL (CDECL *mono_domain_set)(MonoDomain *domain,BOOL force);
101 void (CDECL *mono_domain_set_config)(MonoDomain *domain,const char *base_dir,const char *config_file_name);
102 static void (CDECL *mono_free)(void *);
103 MonoImage* (CDECL *mono_get_corlib)(void);
104 static MonoImage* (CDECL *mono_image_open)(const char *fname, MonoImageOpenStatus *status);
105 MonoImage* (CDECL *mono_image_open_from_module_handle)(HMODULE module_handle, char* fname, UINT has_entry_point, MonoImageOpenStatus* status);
106 static void (CDECL *mono_install_assembly_preload_hook)(MonoAssemblyPreLoadFunc func, void *user_data);
107 int (CDECL *mono_jit_exec)(MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[]);
108 MonoDomain* (CDECL *mono_jit_init_version)(const char *domain_name, const char *runtime_version);
109 static void (CDECL *mono_jit_set_aot_mode)(MonoAotMode mode);
110 static int (CDECL *mono_jit_set_trace_options)(const char* options);
111 void* (CDECL *mono_marshal_get_vtfixup_ftnptr)(MonoImage *image, DWORD token, WORD type);
112 MonoDomain* (CDECL *mono_object_get_domain)(MonoObject *obj);
113 MonoMethod* (CDECL *mono_object_get_virtual_method)(MonoObject *obj, MonoMethod *method);
114 MonoObject* (CDECL *mono_object_new)(MonoDomain *domain, MonoClass *klass);
115 void* (CDECL *mono_object_unbox)(MonoObject *obj);
116 static MonoProfilerHandle (CDECL *mono_profiler_create)(MonoProfiler *prof);
117 static void (CDECL *mono_profiler_install)(MonoProfiler *prof, MonoProfileFunc shutdown_callback);
118 static void (CDECL *mono_profiler_set_runtime_shutdown_begin_callback)(MonoProfilerHandle handle, MonoProfilerRuntimeShutdownBeginCallback cb);
119 MonoType* (CDECL *mono_reflection_type_from_name)(char *name, MonoImage *image);
120 MonoObject* (CDECL *mono_runtime_invoke)(MonoMethod *method, void *obj, void **params, MonoObject **exc);
121 void (CDECL *mono_runtime_object_init)(MonoObject *this_obj);
122 void (CDECL *mono_runtime_quit)(void);
123 static void (CDECL *mono_set_crash_chaining)(BOOL chain_signals);
124 static void (CDECL *mono_set_dirs)(const char *assembly_dir, const char *config_dir);
125 static void (CDECL *mono_set_verbose_level)(DWORD level);
126 MonoString* (CDECL *mono_string_new)(MonoDomain *domain, const char *str);
127 static char* (CDECL *mono_stringify_assembly_name)(MonoAssemblyName *aname);
128 MonoThread* (CDECL *mono_thread_attach)(MonoDomain *domain);
129 void (CDECL *mono_thread_manage)(void);
130 void (CDECL *mono_trace_set_print_handler)(MonoPrintCallback callback);
131 void (CDECL *mono_trace_set_printerr_handler)(MonoPrintCallback callback);
133 static BOOL find_mono_dll(LPCWSTR path, LPWSTR dll_path);
135 static MonoAssembly* CDECL mono_assembly_preload_hook_fn(MonoAssemblyName *aname, char **assemblies_path, void *user_data);
137 static void CDECL mono_shutdown_callback_fn(MonoProfiler *prof);
139 static void CDECL mono_print_handler_fn(const char *string, INT is_stdout);
141 static MonoImage* CDECL image_open_module_handle_dummy(HMODULE module_handle,
142 char* fname, UINT has_entry_point, MonoImageOpenStatus* status)
144 return mono_image_open(fname, status);
147 static void CDECL set_crash_chaining_dummy(BOOL crash_chaining)
151 static void CDECL set_print_handler_dummy(MonoPrintCallback callback)
155 static HRESULT load_mono(LPCWSTR mono_path)
157 static const WCHAR lib[] = {'\\','l','i','b',0};
158 static const WCHAR etc[] = {'\\','e','t','c',0};
159 WCHAR mono_dll_path[MAX_PATH+16];
160 WCHAR mono_lib_path[MAX_PATH+4], mono_etc_path[MAX_PATH+4];
161 char mono_lib_path_a[MAX_PATH], mono_etc_path_a[MAX_PATH];
162 int aot_size;
163 char aot_setting[256];
164 int trace_size;
165 char trace_setting[256];
166 int verbose_size;
167 char verbose_setting[256];
169 if (is_mono_shutdown)
171 ERR("Cannot load Mono after it has been shut down.\n");
172 return E_FAIL;
175 if (!mono_handle)
177 lstrcpyW(mono_lib_path, mono_path);
178 lstrcatW(mono_lib_path, lib);
179 WideCharToMultiByte(CP_UTF8, 0, mono_lib_path, -1, mono_lib_path_a, MAX_PATH, NULL, NULL);
181 lstrcpyW(mono_etc_path, mono_path);
182 lstrcatW(mono_etc_path, etc);
183 WideCharToMultiByte(CP_UTF8, 0, mono_etc_path, -1, mono_etc_path_a, MAX_PATH, NULL, NULL);
185 if (!find_mono_dll(mono_path, mono_dll_path)) goto fail;
187 mono_handle = LoadLibraryW(mono_dll_path);
189 if (!mono_handle) goto fail;
191 #define LOAD_MONO_FUNCTION(x) do { \
192 x = (void*)GetProcAddress(mono_handle, #x); \
193 if (!x) { \
194 goto fail; \
196 } while (0);
198 LOAD_MONO_FUNCTION(mono_assembly_get_image);
199 LOAD_MONO_FUNCTION(mono_assembly_load_from);
200 LOAD_MONO_FUNCTION(mono_assembly_name_get_name);
201 LOAD_MONO_FUNCTION(mono_assembly_name_get_culture);
202 LOAD_MONO_FUNCTION(mono_assembly_open);
203 LOAD_MONO_FUNCTION(mono_config_parse);
204 LOAD_MONO_FUNCTION(mono_class_from_mono_type);
205 LOAD_MONO_FUNCTION(mono_class_from_name);
206 LOAD_MONO_FUNCTION(mono_class_get_method_from_name);
207 LOAD_MONO_FUNCTION(mono_domain_get);
208 LOAD_MONO_FUNCTION(mono_domain_get_by_id);
209 LOAD_MONO_FUNCTION(mono_domain_set);
210 LOAD_MONO_FUNCTION(mono_domain_set_config);
211 LOAD_MONO_FUNCTION(mono_free);
212 LOAD_MONO_FUNCTION(mono_get_corlib);
213 LOAD_MONO_FUNCTION(mono_image_open);
214 LOAD_MONO_FUNCTION(mono_install_assembly_preload_hook);
215 LOAD_MONO_FUNCTION(mono_jit_exec);
216 LOAD_MONO_FUNCTION(mono_jit_init_version);
217 LOAD_MONO_FUNCTION(mono_jit_set_trace_options);
218 LOAD_MONO_FUNCTION(mono_marshal_get_vtfixup_ftnptr);
219 LOAD_MONO_FUNCTION(mono_object_get_domain);
220 LOAD_MONO_FUNCTION(mono_object_get_virtual_method);
221 LOAD_MONO_FUNCTION(mono_object_new);
222 LOAD_MONO_FUNCTION(mono_object_unbox);
223 LOAD_MONO_FUNCTION(mono_reflection_type_from_name);
224 LOAD_MONO_FUNCTION(mono_runtime_invoke);
225 LOAD_MONO_FUNCTION(mono_runtime_object_init);
226 LOAD_MONO_FUNCTION(mono_runtime_quit);
227 LOAD_MONO_FUNCTION(mono_set_dirs);
228 LOAD_MONO_FUNCTION(mono_set_verbose_level);
229 LOAD_MONO_FUNCTION(mono_stringify_assembly_name);
230 LOAD_MONO_FUNCTION(mono_string_new);
231 LOAD_MONO_FUNCTION(mono_thread_attach);
232 LOAD_MONO_FUNCTION(mono_thread_manage);
234 #undef LOAD_MONO_FUNCTION
236 #define LOAD_OPT_MONO_FUNCTION(x, default) do { \
237 x = (void*)GetProcAddress(mono_handle, #x); \
238 if (!x) { \
239 x = default; \
241 } while (0);
243 LOAD_OPT_MONO_FUNCTION(mono_callspec_set_assembly, NULL);
244 LOAD_OPT_MONO_FUNCTION(mono_image_open_from_module_handle, image_open_module_handle_dummy);
245 LOAD_OPT_MONO_FUNCTION(mono_jit_set_aot_mode, NULL);
246 LOAD_OPT_MONO_FUNCTION(mono_profiler_create, NULL);
247 LOAD_OPT_MONO_FUNCTION(mono_profiler_install, NULL);
248 LOAD_OPT_MONO_FUNCTION(mono_profiler_set_runtime_shutdown_begin_callback, NULL);
249 LOAD_OPT_MONO_FUNCTION(mono_set_crash_chaining, set_crash_chaining_dummy);
250 LOAD_OPT_MONO_FUNCTION(mono_trace_set_print_handler, set_print_handler_dummy);
251 LOAD_OPT_MONO_FUNCTION(mono_trace_set_printerr_handler, set_print_handler_dummy);
253 #undef LOAD_OPT_MONO_FUNCTION
255 if (mono_callspec_set_assembly == NULL)
257 mono_callspec_set_assembly = (void*)GetProcAddress(mono_handle, "mono_trace_set_assembly");
258 if (!mono_callspec_set_assembly) goto fail;
261 if (mono_profiler_create != NULL)
263 /* Profiler API v2 */
264 MonoProfilerHandle handle = mono_profiler_create(NULL);
265 mono_profiler_set_runtime_shutdown_begin_callback(handle, mono_shutdown_callback_fn);
267 else if (mono_profiler_install != NULL)
269 /* Profiler API v1 */
270 mono_profiler_install(NULL, mono_shutdown_callback_fn);
273 mono_set_crash_chaining(TRUE);
275 mono_trace_set_print_handler(mono_print_handler_fn);
276 mono_trace_set_printerr_handler(mono_print_handler_fn);
278 mono_set_dirs(mono_lib_path_a, mono_etc_path_a);
280 mono_config_parse(NULL);
282 mono_install_assembly_preload_hook(mono_assembly_preload_hook_fn, NULL);
284 aot_size = GetEnvironmentVariableA("WINE_MONO_AOT", aot_setting, sizeof(aot_setting));
286 if (aot_size)
288 MonoAotMode mode;
289 if (strcmp(aot_setting, "interp") == 0)
290 mode = MONO_AOT_MODE_INTERP_ONLY;
291 else if (strcmp(aot_setting, "none") == 0)
292 mode = MONO_AOT_MODE_NONE;
293 else
295 ERR("unknown WINE_MONO_AOT setting, valid settings are interp and none\n");
296 mode = MONO_AOT_MODE_NONE;
298 if (mono_jit_set_aot_mode != NULL)
300 mono_jit_set_aot_mode(mode);
302 else
304 ERR("mono_jit_set_aot_mode export not found\n");
308 trace_size = GetEnvironmentVariableA("WINE_MONO_TRACE", trace_setting, sizeof(trace_setting));
310 if (trace_size)
312 mono_jit_set_trace_options(trace_setting);
315 verbose_size = GetEnvironmentVariableA("WINE_MONO_VERBOSE", verbose_setting, sizeof(verbose_setting));
317 if (verbose_size)
319 mono_set_verbose_level(verbose_setting[0] - '0');
323 return S_OK;
325 fail:
326 ERR("Could not load Mono into this process\n");
327 FreeLibrary(mono_handle);
328 mono_handle = NULL;
329 return E_FAIL;
332 static char* get_exe_basename_utf8(void)
334 WCHAR filenameW[MAX_PATH], *basenameW;
336 GetModuleFileNameW(NULL, filenameW, MAX_PATH);
338 basenameW = wcsrchr(filenameW, '\\');
339 if (basenameW)
340 basenameW += 1;
341 else
342 basenameW = filenameW;
344 return WtoA(basenameW);
347 MonoDomain* get_root_domain(void)
349 static MonoDomain* root_domain;
351 if (root_domain != NULL)
352 return root_domain;
354 EnterCriticalSection(&runtime_list_cs);
356 if (root_domain == NULL)
358 char *exe_basename;
360 exe_basename = get_exe_basename_utf8();
362 root_domain = mono_jit_init_version(exe_basename, "v4.0.30319");
364 HeapFree(GetProcessHeap(), 0, exe_basename);
366 is_mono_started = TRUE;
369 LeaveCriticalSection(&runtime_list_cs);
371 return root_domain;
374 static void CDECL mono_shutdown_callback_fn(MonoProfiler *prof)
376 is_mono_shutdown = TRUE;
379 static void CDECL mono_print_handler_fn(const char *string, INT is_stdout)
381 const char *p;
382 for (; *string; string = p)
384 if ((p = strstr(string, "\n"))) p++;
385 else p = string + strlen(string);
386 wine_dbg_printf("%.*s", (int)(p - string), string);
390 static HRESULT WINAPI thread_set_fn(void)
392 WARN("stub\n");
393 return S_OK;
396 static HRESULT WINAPI thread_unset_fn(void)
398 WARN("stub\n");
399 return S_OK;
402 static HRESULT CLRRuntimeInfo_GetRuntimeHost(CLRRuntimeInfo *This, RuntimeHost **result)
404 HRESULT hr = S_OK;
405 WCHAR mono_path[MAX_PATH];
407 if (This->loaded_runtime)
409 *result = This->loaded_runtime;
410 return hr;
413 if (!get_mono_path(mono_path, FALSE))
415 ERR("Wine Mono is not installed\n");
416 return CLR_E_SHIM_RUNTIME;
419 EnterCriticalSection(&runtime_list_cs);
421 if (This->loaded_runtime)
423 *result = This->loaded_runtime;
424 LeaveCriticalSection(&runtime_list_cs);
425 return hr;
428 if (GlobalCLRMetaHost.callback)
430 GlobalCLRMetaHost.callback(&This->ICLRRuntimeInfo_iface, thread_set_fn, thread_unset_fn);
433 hr = load_mono(mono_path);
435 if (SUCCEEDED(hr))
436 hr = RuntimeHost_Construct(This, &This->loaded_runtime);
438 LeaveCriticalSection(&runtime_list_cs);
440 if (SUCCEEDED(hr))
441 *result = This->loaded_runtime;
443 return hr;
446 void expect_no_runtimes(void)
448 if (mono_handle && is_mono_started && !is_mono_shutdown)
450 ERR("Process exited with a Mono runtime loaded.\n");
451 return;
455 static inline CLRRuntimeInfo *impl_from_ICLRRuntimeInfo(ICLRRuntimeInfo *iface)
457 return CONTAINING_RECORD(iface, CLRRuntimeInfo, ICLRRuntimeInfo_iface);
460 static HRESULT WINAPI CLRRuntimeInfo_QueryInterface(ICLRRuntimeInfo* iface,
461 REFIID riid,
462 void **ppvObject)
464 TRACE("%p %s %p\n", iface, debugstr_guid(riid), ppvObject);
466 if ( IsEqualGUID( riid, &IID_ICLRRuntimeInfo ) ||
467 IsEqualGUID( riid, &IID_IUnknown ) )
469 *ppvObject = iface;
471 else
473 FIXME("Unsupported interface %s\n", debugstr_guid(riid));
474 return E_NOINTERFACE;
477 ICLRRuntimeInfo_AddRef( iface );
479 return S_OK;
482 static ULONG WINAPI CLRRuntimeInfo_AddRef(ICLRRuntimeInfo* iface)
484 return 2;
487 static ULONG WINAPI CLRRuntimeInfo_Release(ICLRRuntimeInfo* iface)
489 return 1;
492 static HRESULT WINAPI CLRRuntimeInfo_GetVersionString(ICLRRuntimeInfo* iface,
493 LPWSTR pwzBuffer, DWORD *pcchBuffer)
495 struct CLRRuntimeInfo *This = impl_from_ICLRRuntimeInfo(iface);
496 DWORD buffer_size = *pcchBuffer;
497 HRESULT hr = S_OK;
498 char version[11];
499 DWORD size;
501 TRACE("%p %p %p\n", iface, pwzBuffer, pcchBuffer);
503 size = snprintf(version, sizeof(version), "v%u.%u.%u", This->major, This->minor, This->build);
505 assert(size <= sizeof(version));
507 *pcchBuffer = MultiByteToWideChar(CP_UTF8, 0, version, -1, NULL, 0);
509 if (pwzBuffer)
511 if (buffer_size >= *pcchBuffer)
512 MultiByteToWideChar(CP_UTF8, 0, version, -1, pwzBuffer, buffer_size);
513 else
514 hr = E_NOT_SUFFICIENT_BUFFER;
517 return hr;
520 static BOOL get_install_root(LPWSTR install_dir)
522 static const WCHAR dotnet_key[] = {'S','O','F','T','W','A','R','E','\\','M','i','c','r','o','s','o','f','t','\\','.','N','E','T','F','r','a','m','e','w','o','r','k','\\',0};
523 static const WCHAR install_root[] = {'I','n','s','t','a','l','l','R','o','o','t',0};
525 DWORD len;
526 HKEY key;
528 if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, dotnet_key, 0, KEY_READ, &key))
529 return FALSE;
531 len = MAX_PATH * sizeof(WCHAR);
532 if (RegQueryValueExW(key, install_root, 0, NULL, (LPBYTE)install_dir, &len))
534 RegCloseKey(key);
535 return FALSE;
537 RegCloseKey(key);
539 return TRUE;
542 static HRESULT WINAPI CLRRuntimeInfo_GetRuntimeDirectory(ICLRRuntimeInfo* iface,
543 LPWSTR pwzBuffer, DWORD *pcchBuffer)
545 static const WCHAR slash[] = {'\\',0};
546 DWORD buffer_size = *pcchBuffer;
547 WCHAR system_dir[MAX_PATH];
548 WCHAR version[MAX_PATH];
549 DWORD version_size, size;
550 HRESULT hr = S_OK;
552 TRACE("%p %p %p\n", iface, pwzBuffer, pcchBuffer);
554 if (!get_install_root(system_dir))
556 ERR("error reading registry key for installroot\n");
557 return E_FAIL;
559 else
561 version_size = MAX_PATH;
562 ICLRRuntimeInfo_GetVersionString(iface, version, &version_size);
563 lstrcatW(system_dir, version);
564 lstrcatW(system_dir, slash);
565 size = lstrlenW(system_dir) + 1;
568 *pcchBuffer = size;
570 if (pwzBuffer)
572 if (buffer_size >= size)
573 lstrcpyW(pwzBuffer, system_dir);
574 else
575 hr = E_NOT_SUFFICIENT_BUFFER;
578 return hr;
581 static HRESULT WINAPI CLRRuntimeInfo_IsLoaded(ICLRRuntimeInfo* iface,
582 HANDLE hndProcess, BOOL *pbLoaded)
584 FIXME("%p %p %p\n", iface, hndProcess, pbLoaded);
586 return E_NOTIMPL;
589 static HRESULT WINAPI CLRRuntimeInfo_LoadErrorString(ICLRRuntimeInfo* iface,
590 UINT iResourceID, LPWSTR pwzBuffer, DWORD *pcchBuffer, LONG iLocaleid)
592 FIXME("%p %u %p %p %x\n", iface, iResourceID, pwzBuffer, pcchBuffer, iLocaleid);
594 return E_NOTIMPL;
597 static HRESULT WINAPI CLRRuntimeInfo_LoadLibrary(ICLRRuntimeInfo* iface,
598 LPCWSTR pwzDllName, HMODULE *phndModule)
600 WCHAR version[MAX_PATH];
601 HRESULT hr;
602 DWORD cchBuffer;
604 TRACE("%p %s %p\n", iface, debugstr_w(pwzDllName), phndModule);
606 cchBuffer = MAX_PATH;
607 hr = ICLRRuntimeInfo_GetVersionString(iface, version, &cchBuffer);
608 if (FAILED(hr)) return hr;
610 return LoadLibraryShim(pwzDllName, version, NULL, phndModule);
613 static HRESULT WINAPI CLRRuntimeInfo_GetProcAddress(ICLRRuntimeInfo* iface,
614 LPCSTR pszProcName, LPVOID *ppProc)
616 FIXME("%p %s %p\n", iface, debugstr_a(pszProcName), ppProc);
618 return E_NOTIMPL;
621 static HRESULT WINAPI CLRRuntimeInfo_GetInterface(ICLRRuntimeInfo* iface,
622 REFCLSID rclsid, REFIID riid, LPVOID *ppUnk)
624 struct CLRRuntimeInfo *This = impl_from_ICLRRuntimeInfo(iface);
625 RuntimeHost *host;
626 HRESULT hr;
628 TRACE("%p %s %s %p\n", iface, debugstr_guid(rclsid), debugstr_guid(riid), ppUnk);
630 hr = CLRRuntimeInfo_GetRuntimeHost(This, &host);
632 if (SUCCEEDED(hr))
633 hr = RuntimeHost_GetInterface(host, rclsid, riid, ppUnk);
635 return hr;
638 static HRESULT WINAPI CLRRuntimeInfo_IsLoadable(ICLRRuntimeInfo* iface,
639 BOOL *pbLoadable)
641 FIXME("%p %p\n", iface, pbLoadable);
643 return E_NOTIMPL;
646 static HRESULT WINAPI CLRRuntimeInfo_SetDefaultStartupFlags(ICLRRuntimeInfo* iface,
647 DWORD dwStartupFlags, LPCWSTR pwzHostConfigFile)
649 FIXME("%p %x %s\n", iface, dwStartupFlags, debugstr_w(pwzHostConfigFile));
651 return E_NOTIMPL;
654 static HRESULT WINAPI CLRRuntimeInfo_GetDefaultStartupFlags(ICLRRuntimeInfo* iface,
655 DWORD *pdwStartupFlags, LPWSTR pwzHostConfigFile, DWORD *pcchHostConfigFile)
657 FIXME("%p %p %p %p\n", iface, pdwStartupFlags, pwzHostConfigFile, pcchHostConfigFile);
659 return E_NOTIMPL;
662 static HRESULT WINAPI CLRRuntimeInfo_BindAsLegacyV2Runtime(ICLRRuntimeInfo* iface)
664 FIXME("%p\n", iface);
666 return E_NOTIMPL;
669 static HRESULT WINAPI CLRRuntimeInfo_IsStarted(ICLRRuntimeInfo* iface,
670 BOOL *pbStarted, DWORD *pdwStartupFlags)
672 FIXME("%p %p %p\n", iface, pbStarted, pdwStartupFlags);
674 return E_NOTIMPL;
677 static const struct ICLRRuntimeInfoVtbl CLRRuntimeInfoVtbl = {
678 CLRRuntimeInfo_QueryInterface,
679 CLRRuntimeInfo_AddRef,
680 CLRRuntimeInfo_Release,
681 CLRRuntimeInfo_GetVersionString,
682 CLRRuntimeInfo_GetRuntimeDirectory,
683 CLRRuntimeInfo_IsLoaded,
684 CLRRuntimeInfo_LoadErrorString,
685 CLRRuntimeInfo_LoadLibrary,
686 CLRRuntimeInfo_GetProcAddress,
687 CLRRuntimeInfo_GetInterface,
688 CLRRuntimeInfo_IsLoadable,
689 CLRRuntimeInfo_SetDefaultStartupFlags,
690 CLRRuntimeInfo_GetDefaultStartupFlags,
691 CLRRuntimeInfo_BindAsLegacyV2Runtime,
692 CLRRuntimeInfo_IsStarted
695 HRESULT ICLRRuntimeInfo_GetRuntimeHost(ICLRRuntimeInfo *iface, RuntimeHost **result)
697 struct CLRRuntimeInfo *This = impl_from_ICLRRuntimeInfo(iface);
699 assert(This->ICLRRuntimeInfo_iface.lpVtbl == &CLRRuntimeInfoVtbl);
701 return CLRRuntimeInfo_GetRuntimeHost(This, result);
704 #ifdef __i386__
705 static const WCHAR libmono2_arch_dll[] = {'\\','b','i','n','\\','l','i','b','m','o','n','o','-','2','.','0','-','x','8','6','.','d','l','l',0};
706 #elif defined(__x86_64__)
707 static const WCHAR libmono2_arch_dll[] = {'\\','b','i','n','\\','l','i','b','m','o','n','o','-','2','.','0','-','x','8','6','_','6','4','.','d','l','l',0};
708 #else
709 static const WCHAR libmono2_arch_dll[] = {'\\','b','i','n','\\','l','i','b','m','o','n','o','-','2','.','0','.','d','l','l',0};
710 #endif
712 static BOOL find_mono_dll(LPCWSTR path, LPWSTR dll_path)
714 static const WCHAR mono2_dll[] = {'\\','b','i','n','\\','m','o','n','o','-','2','.','0','.','d','l','l',0};
715 static const WCHAR libmono2_dll[] = {'\\','b','i','n','\\','l','i','b','m','o','n','o','-','2','.','0','.','d','l','l',0};
716 DWORD attributes=INVALID_FILE_ATTRIBUTES;
718 lstrcpyW(dll_path, path);
719 lstrcatW(dll_path, libmono2_arch_dll);
720 attributes = GetFileAttributesW(dll_path);
722 if (attributes == INVALID_FILE_ATTRIBUTES)
724 lstrcpyW(dll_path, path);
725 lstrcatW(dll_path, mono2_dll);
726 attributes = GetFileAttributesW(dll_path);
729 if (attributes == INVALID_FILE_ATTRIBUTES)
731 lstrcpyW(dll_path, path);
732 lstrcatW(dll_path, libmono2_dll);
733 attributes = GetFileAttributesW(dll_path);
736 return (attributes != INVALID_FILE_ATTRIBUTES);
739 static BOOL get_mono_path_local(LPWSTR path)
741 static const WCHAR subdir_mono[] = {'\\','m','o','n','o','\\','m','o','n','o','-','2','.','0', 0};
742 WCHAR base_path[MAX_PATH], mono_dll_path[MAX_PATH];
744 /* c:\windows\mono\mono-2.0 */
745 GetWindowsDirectoryW(base_path, MAX_PATH);
746 lstrcatW(base_path, subdir_mono);
748 if (find_mono_dll(base_path, mono_dll_path))
750 lstrcpyW(path, base_path);
751 return TRUE;
754 return FALSE;
757 static BOOL get_mono_path_registry(LPWSTR path)
759 static const WCHAR keyname[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','o','n','o',0};
760 static const WCHAR valuename[] = {'R','u','n','t','i','m','e','P','a','t','h',0};
761 WCHAR base_path[MAX_PATH], mono_dll_path[MAX_PATH];
762 HKEY hkey;
763 DWORD res, valuesize;
764 BOOL ret=FALSE;
766 /* @@ Wine registry key: HKCU\Software\Wine\Mono */
767 res = RegOpenKeyW(HKEY_CURRENT_USER, keyname, &hkey);
768 if (res != ERROR_SUCCESS)
769 return FALSE;
771 valuesize = sizeof(base_path);
772 res = RegGetValueW(hkey, NULL, valuename, RRF_RT_REG_SZ, NULL, base_path, &valuesize);
773 if (res == ERROR_SUCCESS && find_mono_dll(base_path, mono_dll_path))
775 lstrcpyW(path, base_path);
776 ret = TRUE;
779 RegCloseKey(hkey);
781 return ret;
784 static BOOL get_mono_path_dos(const WCHAR *dir, LPWSTR path)
786 static const WCHAR unix_prefix[] = {'\\','\\','?','\\','u','n','i','x','\\'};
787 static const WCHAR basedir[] = L"\\wine-mono-" WINE_MONO_VERSION;
788 LPWSTR dos_dir;
789 WCHAR mono_dll_path[MAX_PATH];
790 DWORD len;
791 BOOL ret;
793 if (memcmp(dir, unix_prefix, sizeof(unix_prefix)) == 0)
794 return FALSE; /* No drive letter for this directory */
796 len = lstrlenW( dir ) + lstrlenW( basedir ) + 1;
797 if (!(dos_dir = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
798 lstrcpyW( dos_dir, dir );
799 lstrcatW( dos_dir, basedir );
801 ret = find_mono_dll(dos_dir, mono_dll_path);
802 if (ret)
803 lstrcpyW(path, dos_dir);
805 heap_free(dos_dir);
807 return ret;
810 static BOOL get_mono_path_unix(const char *unix_dir, LPWSTR path)
812 static WCHAR * (CDECL *p_wine_get_dos_file_name)(const char*);
813 LPWSTR dos_dir;
814 BOOL ret;
816 if (!p_wine_get_dos_file_name)
818 p_wine_get_dos_file_name = (void*)GetProcAddress(GetModuleHandleA("kernel32"), "wine_get_dos_file_name");
819 if (!p_wine_get_dos_file_name)
820 return FALSE;
823 dos_dir = p_wine_get_dos_file_name(unix_dir);
824 if (!dos_dir)
825 return FALSE;
827 ret = get_mono_path_dos( dos_dir, path);
829 heap_free(dos_dir);
830 return ret;
833 static BOOL get_mono_path_datadir(LPWSTR path)
835 static const WCHAR winedatadirW[] = {'W','I','N','E','D','A','T','A','D','I','R',0};
836 static const WCHAR winebuilddirW[] = {'W','I','N','E','B','U','I','L','D','D','I','R',0};
837 static const WCHAR unix_prefix[] = {'\\','?','?','\\','u','n','i','x','\\'};
838 static const WCHAR monoW[] = {'\\','m','o','n','o',0};
839 static const WCHAR dotdotmonoW[] = {'\\','.','.','\\','m','o','n','o',0};
840 const WCHAR *data_dir, *suffix;
841 WCHAR *package_dir;
842 BOOL ret;
844 if ((data_dir = _wgetenv( winedatadirW )))
845 suffix = monoW;
846 else if ((data_dir = _wgetenv( winebuilddirW )))
847 suffix = dotdotmonoW;
848 else
849 return FALSE;
851 if (!wcsncmp( data_dir, unix_prefix, wcslen(unix_prefix) )) return FALSE;
852 data_dir += 4; /* skip \??\ prefix */
853 package_dir = heap_alloc( (lstrlenW(data_dir) + lstrlenW(suffix) + 1) * sizeof(WCHAR));
854 lstrcpyW( package_dir, data_dir );
855 lstrcatW( package_dir, suffix );
857 ret = get_mono_path_dos(package_dir, path);
859 heap_free(package_dir);
861 return ret;
864 BOOL get_mono_path(LPWSTR path, BOOL skip_local)
866 return (!skip_local && get_mono_path_local(path)) ||
867 get_mono_path_registry(path) ||
868 get_mono_path_datadir(path) ||
869 get_mono_path_unix(INSTALL_DATADIR "/wine/mono", path) ||
870 (strcmp(INSTALL_DATADIR, "/usr/share") &&
871 get_mono_path_unix("/usr/share/wine/mono", path)) ||
872 get_mono_path_unix("/opt/wine/mono", path);
875 struct InstalledRuntimeEnum
877 IEnumUnknown IEnumUnknown_iface;
878 LONG ref;
879 ULONG pos;
882 static const struct IEnumUnknownVtbl InstalledRuntimeEnum_Vtbl;
884 static inline struct InstalledRuntimeEnum *impl_from_IEnumUnknown(IEnumUnknown *iface)
886 return CONTAINING_RECORD(iface, struct InstalledRuntimeEnum, IEnumUnknown_iface);
889 static HRESULT WINAPI InstalledRuntimeEnum_QueryInterface(IEnumUnknown* iface, REFIID riid,
890 void **ppvObject)
892 TRACE("%p %s %p\n", iface, debugstr_guid(riid), ppvObject);
894 if ( IsEqualGUID( riid, &IID_IEnumUnknown ) ||
895 IsEqualGUID( riid, &IID_IUnknown ) )
897 *ppvObject = iface;
899 else
901 FIXME("Unsupported interface %s\n", debugstr_guid(riid));
902 return E_NOINTERFACE;
905 IEnumUnknown_AddRef( iface );
907 return S_OK;
910 static ULONG WINAPI InstalledRuntimeEnum_AddRef(IEnumUnknown* iface)
912 struct InstalledRuntimeEnum *This = impl_from_IEnumUnknown(iface);
913 ULONG ref = InterlockedIncrement(&This->ref);
915 TRACE("(%p) refcount=%u\n", iface, ref);
917 return ref;
920 static ULONG WINAPI InstalledRuntimeEnum_Release(IEnumUnknown* iface)
922 struct InstalledRuntimeEnum *This = impl_from_IEnumUnknown(iface);
923 ULONG ref = InterlockedDecrement(&This->ref);
925 TRACE("(%p) refcount=%u\n", iface, ref);
927 if (ref == 0)
929 HeapFree(GetProcessHeap(), 0, This);
932 return ref;
935 static HRESULT WINAPI InstalledRuntimeEnum_Next(IEnumUnknown *iface, ULONG celt,
936 IUnknown **rgelt, ULONG *pceltFetched)
938 struct InstalledRuntimeEnum *This = impl_from_IEnumUnknown(iface);
939 ULONG num_fetched = 0;
940 HRESULT hr=S_OK;
941 IUnknown *item;
943 TRACE("(%p,%u,%p,%p)\n", iface, celt, rgelt, pceltFetched);
945 while (num_fetched < celt)
947 if (This->pos >= NUM_RUNTIMES)
949 hr = S_FALSE;
950 break;
952 item = (IUnknown*)&runtimes[This->pos].ICLRRuntimeInfo_iface;
953 IUnknown_AddRef(item);
954 rgelt[num_fetched] = item;
955 num_fetched++;
956 This->pos++;
959 if (pceltFetched)
960 *pceltFetched = num_fetched;
962 return hr;
965 static HRESULT WINAPI InstalledRuntimeEnum_Skip(IEnumUnknown *iface, ULONG celt)
967 struct InstalledRuntimeEnum *This = impl_from_IEnumUnknown(iface);
968 ULONG num_fetched = 0;
969 HRESULT hr=S_OK;
971 TRACE("(%p,%u)\n", iface, celt);
973 while (num_fetched < celt)
975 if (This->pos >= NUM_RUNTIMES)
977 hr = S_FALSE;
978 break;
980 num_fetched++;
981 This->pos++;
984 return hr;
987 static HRESULT WINAPI InstalledRuntimeEnum_Reset(IEnumUnknown *iface)
989 struct InstalledRuntimeEnum *This = impl_from_IEnumUnknown(iface);
991 TRACE("(%p)\n", iface);
993 This->pos = 0;
995 return S_OK;
998 static HRESULT WINAPI InstalledRuntimeEnum_Clone(IEnumUnknown *iface, IEnumUnknown **ppenum)
1000 struct InstalledRuntimeEnum *This = impl_from_IEnumUnknown(iface);
1001 struct InstalledRuntimeEnum *new_enum;
1003 TRACE("(%p)\n", iface);
1005 new_enum = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_enum));
1006 if (!new_enum)
1007 return E_OUTOFMEMORY;
1009 new_enum->IEnumUnknown_iface.lpVtbl = &InstalledRuntimeEnum_Vtbl;
1010 new_enum->ref = 1;
1011 new_enum->pos = This->pos;
1013 *ppenum = &new_enum->IEnumUnknown_iface;
1015 return S_OK;
1018 static const struct IEnumUnknownVtbl InstalledRuntimeEnum_Vtbl = {
1019 InstalledRuntimeEnum_QueryInterface,
1020 InstalledRuntimeEnum_AddRef,
1021 InstalledRuntimeEnum_Release,
1022 InstalledRuntimeEnum_Next,
1023 InstalledRuntimeEnum_Skip,
1024 InstalledRuntimeEnum_Reset,
1025 InstalledRuntimeEnum_Clone
1028 static HRESULT WINAPI CLRMetaHost_QueryInterface(ICLRMetaHost* iface,
1029 REFIID riid,
1030 void **ppvObject)
1032 TRACE("%s %p\n", debugstr_guid(riid), ppvObject);
1034 if ( IsEqualGUID( riid, &IID_ICLRMetaHost ) ||
1035 IsEqualGUID( riid, &IID_IUnknown ) )
1037 *ppvObject = iface;
1039 else
1041 FIXME("Unsupported interface %s\n", debugstr_guid(riid));
1042 return E_NOINTERFACE;
1045 ICLRMetaHost_AddRef( iface );
1047 return S_OK;
1050 static ULONG WINAPI CLRMetaHost_AddRef(ICLRMetaHost* iface)
1052 return 2;
1055 static ULONG WINAPI CLRMetaHost_Release(ICLRMetaHost* iface)
1057 return 1;
1060 static inline BOOL isDigit(WCHAR c)
1062 return c >= '0' && c <= '9';
1065 static BOOL parse_runtime_version(LPCWSTR version, DWORD *major, DWORD *minor, DWORD *build)
1067 *major = 0;
1068 *minor = 0;
1069 *build = 0;
1071 if (version[0] == 'v' || version[0] == 'V')
1073 version++;
1074 if (!isDigit(*version))
1075 return FALSE;
1077 while (isDigit(*version))
1078 *major = *major * 10 + (*version++ - '0');
1080 if (*version == 0)
1081 return TRUE;
1083 if (*version++ != '.' || !isDigit(*version))
1084 return FALSE;
1086 while (isDigit(*version))
1087 *minor = *minor * 10 + (*version++ - '0');
1089 if (*version == 0)
1090 return TRUE;
1092 if (*version++ != '.' || !isDigit(*version))
1093 return FALSE;
1095 while (isDigit(*version))
1096 *build = *build * 10 + (*version++ - '0');
1098 return *version == 0;
1100 else
1101 return FALSE;
1104 static HRESULT get_runtime(LPCWSTR pwzVersion, BOOL allow_short,
1105 REFIID iid, LPVOID *ppRuntime)
1107 int i;
1108 DWORD major, minor, build;
1110 if (!pwzVersion)
1111 return E_POINTER;
1113 if (!parse_runtime_version(pwzVersion, &major, &minor, &build))
1115 ERR("Cannot parse %s\n", debugstr_w(pwzVersion));
1116 return CLR_E_SHIM_RUNTIME;
1119 for (i=0; i<NUM_RUNTIMES; i++)
1121 if (runtimes[i].major == major && runtimes[i].minor == minor &&
1122 (runtimes[i].build == build || (allow_short && major >= 4 && build == 0)))
1124 return ICLRRuntimeInfo_QueryInterface(&runtimes[i].ICLRRuntimeInfo_iface, iid,
1125 ppRuntime);
1129 FIXME("Unrecognized version %s\n", debugstr_w(pwzVersion));
1130 return CLR_E_SHIM_RUNTIME;
1133 HRESULT WINAPI CLRMetaHost_GetRuntime(ICLRMetaHost* iface,
1134 LPCWSTR pwzVersion, REFIID iid, LPVOID *ppRuntime)
1136 TRACE("%s %s %p\n", debugstr_w(pwzVersion), debugstr_guid(iid), ppRuntime);
1138 return get_runtime(pwzVersion, FALSE, iid, ppRuntime);
1141 HRESULT WINAPI CLRMetaHost_GetVersionFromFile(ICLRMetaHost* iface,
1142 LPCWSTR pwzFilePath, LPWSTR pwzBuffer, DWORD *pcchBuffer)
1144 ASSEMBLY *assembly;
1145 HRESULT hr;
1146 LPSTR version;
1147 ULONG buffer_size=*pcchBuffer;
1149 TRACE("%s %p %p\n", debugstr_w(pwzFilePath), pwzBuffer, pcchBuffer);
1151 hr = assembly_create(&assembly, pwzFilePath);
1153 if (SUCCEEDED(hr))
1155 hr = assembly_get_runtime_version(assembly, &version);
1157 if (SUCCEEDED(hr))
1159 *pcchBuffer = MultiByteToWideChar(CP_UTF8, 0, version, -1, NULL, 0);
1161 if (pwzBuffer)
1163 if (buffer_size >= *pcchBuffer)
1164 MultiByteToWideChar(CP_UTF8, 0, version, -1, pwzBuffer, buffer_size);
1165 else
1166 hr = E_NOT_SUFFICIENT_BUFFER;
1170 assembly_release(assembly);
1173 return hr;
1176 static HRESULT WINAPI CLRMetaHost_EnumerateInstalledRuntimes(ICLRMetaHost* iface,
1177 IEnumUnknown **ppEnumerator)
1179 struct InstalledRuntimeEnum *new_enum;
1181 TRACE("%p\n", ppEnumerator);
1183 new_enum = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_enum));
1184 if (!new_enum)
1185 return E_OUTOFMEMORY;
1187 new_enum->IEnumUnknown_iface.lpVtbl = &InstalledRuntimeEnum_Vtbl;
1188 new_enum->ref = 1;
1189 new_enum->pos = 0;
1191 *ppEnumerator = &new_enum->IEnumUnknown_iface;
1193 return S_OK;
1196 static HRESULT WINAPI CLRMetaHost_EnumerateLoadedRuntimes(ICLRMetaHost* iface,
1197 HANDLE hndProcess, IEnumUnknown **ppEnumerator)
1199 FIXME("%p %p\n", hndProcess, ppEnumerator);
1201 return E_NOTIMPL;
1204 static HRESULT WINAPI CLRMetaHost_RequestRuntimeLoadedNotification(ICLRMetaHost* iface,
1205 RuntimeLoadedCallbackFnPtr pCallbackFunction)
1207 TRACE("%p\n", pCallbackFunction);
1209 if(!pCallbackFunction)
1210 return E_POINTER;
1212 if (GlobalCLRMetaHost.callback)
1213 return HOST_E_INVALIDOPERATION;
1215 GlobalCLRMetaHost.callback = pCallbackFunction;
1217 return S_OK;
1220 static HRESULT WINAPI CLRMetaHost_QueryLegacyV2RuntimeBinding(ICLRMetaHost* iface,
1221 REFIID riid, LPVOID *ppUnk)
1223 FIXME("%s %p\n", debugstr_guid(riid), ppUnk);
1225 return E_NOTIMPL;
1228 HRESULT WINAPI CLRMetaHost_ExitProcess(ICLRMetaHost* iface, INT32 iExitCode)
1230 TRACE("%i\n", iExitCode);
1232 EnterCriticalSection(&runtime_list_cs);
1234 if (is_mono_started && !is_mono_shutdown)
1236 /* search for a runtime and call System.Environment.Exit() */
1237 int i;
1239 for (i=0; i<NUM_RUNTIMES; i++)
1240 if (runtimes[i].loaded_runtime)
1241 RuntimeHost_ExitProcess(runtimes[i].loaded_runtime, iExitCode);
1244 ExitProcess(iExitCode);
1247 static const struct ICLRMetaHostVtbl CLRMetaHost_vtbl =
1249 CLRMetaHost_QueryInterface,
1250 CLRMetaHost_AddRef,
1251 CLRMetaHost_Release,
1252 CLRMetaHost_GetRuntime,
1253 CLRMetaHost_GetVersionFromFile,
1254 CLRMetaHost_EnumerateInstalledRuntimes,
1255 CLRMetaHost_EnumerateLoadedRuntimes,
1256 CLRMetaHost_RequestRuntimeLoadedNotification,
1257 CLRMetaHost_QueryLegacyV2RuntimeBinding,
1258 CLRMetaHost_ExitProcess
1261 static struct CLRMetaHost GlobalCLRMetaHost = {
1262 { &CLRMetaHost_vtbl }
1265 HRESULT CLRMetaHost_CreateInstance(REFIID riid, void **ppobj)
1267 return ICLRMetaHost_QueryInterface(&GlobalCLRMetaHost.ICLRMetaHost_iface, riid, ppobj);
1270 struct CLRMetaHostPolicy
1272 ICLRMetaHostPolicy ICLRMetaHostPolicy_iface;
1275 static struct CLRMetaHostPolicy GlobalCLRMetaHostPolicy;
1277 static HRESULT WINAPI metahostpolicy_QueryInterface(ICLRMetaHostPolicy *iface, REFIID riid, void **obj)
1279 TRACE("%s %p\n", debugstr_guid(riid), obj);
1281 if ( IsEqualGUID( riid, &IID_ICLRMetaHostPolicy ) ||
1282 IsEqualGUID( riid, &IID_IUnknown ) )
1284 ICLRMetaHostPolicy_AddRef( iface );
1285 *obj = iface;
1286 return S_OK;
1289 FIXME("Unsupported interface %s\n", debugstr_guid(riid));
1291 *obj = NULL;
1292 return E_NOINTERFACE;
1295 static ULONG WINAPI metahostpolicy_AddRef(ICLRMetaHostPolicy *iface)
1297 return 2;
1300 static ULONG WINAPI metahostpolicy_Release(ICLRMetaHostPolicy *iface)
1302 return 1;
1305 static HRESULT WINAPI metahostpolicy_GetRequestedRuntime(ICLRMetaHostPolicy *iface, METAHOST_POLICY_FLAGS dwPolicyFlags,
1306 LPCWSTR pwzBinary, IStream *pCfgStream, LPWSTR pwzVersion, DWORD *pcchVersion,
1307 LPWSTR pwzImageVersion, DWORD *pcchImageVersion, DWORD *pdwConfigFlags, REFIID riid,
1308 LPVOID *ppRuntime)
1310 ICLRRuntimeInfo *result;
1311 HRESULT hr;
1312 WCHAR filename[MAX_PATH];
1313 const WCHAR *path = NULL;
1314 int flags = 0;
1316 TRACE("%d %p %p %p %p %p %p %p %s %p\n", dwPolicyFlags, pwzBinary, pCfgStream,
1317 pwzVersion, pcchVersion, pwzImageVersion, pcchImageVersion, pdwConfigFlags,
1318 debugstr_guid(riid), ppRuntime);
1320 if (pdwConfigFlags) {
1321 FIXME("ignoring config flags\n");
1322 *pdwConfigFlags = 0;
1325 if(dwPolicyFlags & METAHOST_POLICY_USE_PROCESS_IMAGE_PATH)
1327 GetModuleFileNameW(0, filename, MAX_PATH);
1328 path = filename;
1330 else if(pwzBinary)
1332 path = pwzBinary;
1335 if(dwPolicyFlags & METAHOST_POLICY_APPLY_UPGRADE_POLICY)
1336 flags |= RUNTIME_INFO_UPGRADE_VERSION;
1338 hr = get_runtime_info(path, pwzImageVersion, NULL, pCfgStream, 0, flags, FALSE, &result);
1339 if (SUCCEEDED(hr))
1341 if (pwzImageVersion)
1343 /* Ignoring errors on purpose */
1344 ICLRRuntimeInfo_GetVersionString(result, pwzImageVersion, pcchImageVersion);
1347 hr = ICLRRuntimeInfo_QueryInterface(result, riid, ppRuntime);
1349 ICLRRuntimeInfo_Release(result);
1352 TRACE("<- 0x%08x\n", hr);
1354 return hr;
1357 static const struct ICLRMetaHostPolicyVtbl CLRMetaHostPolicy_vtbl =
1359 metahostpolicy_QueryInterface,
1360 metahostpolicy_AddRef,
1361 metahostpolicy_Release,
1362 metahostpolicy_GetRequestedRuntime
1365 static struct CLRMetaHostPolicy GlobalCLRMetaHostPolicy = {
1366 { &CLRMetaHostPolicy_vtbl }
1369 HRESULT CLRMetaHostPolicy_CreateInstance(REFIID riid, void **ppobj)
1371 return ICLRMetaHostPolicy_QueryInterface(&GlobalCLRMetaHostPolicy.ICLRMetaHostPolicy_iface, riid, ppobj);
1375 * Assembly search override settings:
1377 * WINE_MONO_OVERRIDES=*,Gac=n
1378 * Never search the GAC for libraries.
1380 * WINE_MONO_OVERRIDES=Microsoft.Xna.Framework,Gac=n
1381 * Never search the GAC for Microsoft.Xna.Framework
1383 * WINE_MONO_OVERRIDES=Microsoft.Xna.Framework.*,Gac=n;Microsoft.Xna.Framework.GamerServices,Gac=y
1384 * Never search the GAC for Microsoft.Xna.Framework, or any library starting
1385 * with Microsoft.Xna.Framework, except for Microsoft.Xna.Framework.GamerServices
1388 /* assembly search override flags */
1389 #define ASSEMBLY_SEARCH_GAC 1
1390 #define ASSEMBLY_SEARCH_UNDEFINED 2
1391 #define ASSEMBLY_SEARCH_DEFAULT ASSEMBLY_SEARCH_GAC
1393 typedef struct override_entry {
1394 char *name;
1395 DWORD flags;
1396 struct list entry;
1397 } override_entry;
1399 static struct list env_overrides = LIST_INIT(env_overrides);
1401 #define IS_OPTION_TRUE(ch) \
1402 ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
1403 #define IS_OPTION_FALSE(ch) \
1404 ((ch) == 'n' || (ch) == 'N' || (ch) == 'f' || (ch) == 'F' || (ch) == '0')
1406 static void parse_override_entry(override_entry *entry, const char *string, int string_len)
1408 const char *next_key, *equals, *value;
1409 UINT kvp_len, key_len;
1411 entry->flags = ASSEMBLY_SEARCH_DEFAULT;
1413 while (string && string_len > 0)
1415 next_key = memchr(string, ',', string_len);
1417 if (next_key)
1419 kvp_len = next_key - string;
1420 next_key++;
1422 else
1423 kvp_len = string_len;
1425 equals = memchr(string, '=', kvp_len);
1427 if (equals)
1429 key_len = equals - string;
1430 value = equals + 1;
1431 switch (key_len) {
1432 case 3:
1433 if (!_strnicmp(string, "gac", 3)) {
1434 if (IS_OPTION_TRUE(*value))
1435 entry->flags |= ASSEMBLY_SEARCH_GAC;
1436 else if (IS_OPTION_FALSE(*value))
1437 entry->flags &= ~ASSEMBLY_SEARCH_GAC;
1439 break;
1440 default:
1441 break;
1445 string = next_key;
1446 string_len -= kvp_len + 1;
1450 static BOOL WINAPI parse_env_overrides(INIT_ONCE *once, void *param, void **context)
1452 const char *override_string = getenv("WINE_MONO_OVERRIDES");
1453 struct override_entry *entry;
1455 if (override_string)
1457 const char *entry_start;
1459 entry_start = override_string;
1461 while (entry_start && *entry_start)
1463 const char *next_entry, *basename_end;
1464 UINT entry_len;
1466 next_entry = strchr(entry_start, ';');
1468 if (next_entry)
1470 entry_len = next_entry - entry_start;
1471 next_entry++;
1473 else
1474 entry_len = strlen(entry_start);
1476 basename_end = memchr(entry_start, ',', entry_len);
1478 if (!basename_end)
1480 entry_start = next_entry;
1481 continue;
1484 entry = heap_alloc_zero(sizeof(*entry));
1485 if (!entry)
1487 ERR("out of memory\n");
1488 break;
1491 entry->name = heap_alloc_zero(basename_end - entry_start + 1);
1492 if (!entry->name)
1494 ERR("out of memory\n");
1495 heap_free(entry);
1496 break;
1499 memcpy(entry->name, entry_start, basename_end - entry_start);
1501 entry_len -= basename_end - entry_start + 1;
1502 entry_start = basename_end + 1;
1504 parse_override_entry(entry, entry_start, entry_len);
1506 list_add_tail(&env_overrides, &entry->entry);
1508 entry_start = next_entry;
1512 return TRUE;
1515 static DWORD get_basename_search_flags(const char *basename, MonoAssemblyName *aname, HKEY userkey, HKEY appkey)
1517 struct override_entry *entry;
1518 char buffer[256];
1519 DWORD buffer_size;
1520 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
1522 InitOnceExecuteOnce(&init_once, parse_env_overrides, NULL, NULL);
1524 LIST_FOR_EACH_ENTRY(entry, &env_overrides, override_entry, entry)
1526 if (strcmp(basename, entry->name) == 0)
1528 return entry->flags;
1532 buffer_size = sizeof(buffer);
1533 if (appkey && !RegQueryValueExA(appkey, basename, 0, NULL, (LPBYTE)buffer, &buffer_size))
1535 override_entry reg_entry;
1537 memset(&reg_entry, 0, sizeof(reg_entry));
1539 parse_override_entry(&reg_entry, buffer, strlen(buffer));
1541 return reg_entry.flags;
1544 buffer_size = sizeof(buffer);
1545 if (userkey && !RegQueryValueExA(userkey, basename, 0, NULL, (LPBYTE)buffer, &buffer_size))
1547 override_entry reg_entry;
1549 memset(&reg_entry, 0, sizeof(reg_entry));
1551 parse_override_entry(&reg_entry, buffer, strlen(buffer));
1553 return reg_entry.flags;
1556 if (strcmp(basename, "Microsoft.Xna.Framework.*") == 0)
1557 /* XNA redist is broken in Wine Mono, use FNA instead. */
1558 return 0;
1560 return ASSEMBLY_SEARCH_UNDEFINED;
1563 static HKEY get_app_overrides_key(void)
1565 static const WCHAR subkeyW[] = {'\\','M','o','n','o','\\','A','s','m','O','v','e','r','r','i','d','e','s',0};
1566 WCHAR bufferW[MAX_PATH+18];
1567 HKEY appkey = 0;
1568 DWORD len;
1570 len = (GetModuleFileNameW( 0, bufferW, MAX_PATH ));
1571 if (len && len < MAX_PATH)
1573 HKEY tmpkey;
1574 WCHAR *p, *appname = bufferW;
1575 if ((p = wcsrchr( appname, '/' ))) appname = p + 1;
1576 if ((p = wcsrchr( appname, '\\' ))) appname = p + 1;
1577 lstrcatW( appname, subkeyW );
1578 /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Mono\AsmOverrides */
1579 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
1581 if (RegOpenKeyW( tmpkey, appname, &appkey )) appkey = 0;
1582 RegCloseKey( tmpkey );
1586 return appkey;
1589 static DWORD get_assembly_search_flags(MonoAssemblyName *aname)
1591 const char *name = mono_assembly_name_get_name(aname);
1592 char *name_copy, *name_end;
1593 DWORD result;
1594 HKEY appkey = 0, userkey;
1596 /* @@ Wine registry key: HKCU\Software\Wine\Mono\AsmOverrides */
1597 if (RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Mono\\AsmOverrides", &userkey )) userkey = 0;
1599 appkey = get_app_overrides_key();
1601 result = get_basename_search_flags(name, aname, userkey, appkey);
1602 if (result != ASSEMBLY_SEARCH_UNDEFINED)
1604 if (userkey) RegCloseKey(userkey);
1605 if (appkey) RegCloseKey(appkey);
1606 return result;
1609 name_copy = heap_alloc((strlen(name) + 3) * sizeof(WCHAR));
1610 if (!name_copy)
1612 ERR("out of memory\n");
1613 if (userkey) RegCloseKey(userkey);
1614 if (appkey) RegCloseKey(appkey);
1615 return ASSEMBLY_SEARCH_DEFAULT;
1618 strcpy(name_copy, name);
1619 name_end = name_copy + strlen(name);
1623 strcpy(name_end, ".*");
1624 result = get_basename_search_flags(name_copy, aname, userkey, appkey);
1625 if (result != ASSEMBLY_SEARCH_UNDEFINED) break;
1627 *name_end = 0;
1628 name_end = strrchr(name_copy, '.');
1629 } while (name_end != NULL);
1631 /* default flags */
1632 if (result == ASSEMBLY_SEARCH_UNDEFINED)
1634 result = get_basename_search_flags("*", aname, userkey, appkey);
1635 if (result == ASSEMBLY_SEARCH_UNDEFINED)
1636 result = ASSEMBLY_SEARCH_DEFAULT;
1639 heap_free(name_copy);
1640 if (appkey) RegCloseKey(appkey);
1641 if (userkey) RegCloseKey(userkey);
1643 return result;
1646 HRESULT get_file_from_strongname(WCHAR* stringnameW, WCHAR* assemblies_path, int path_length)
1648 HRESULT hr=S_OK;
1649 IAssemblyCache *asmcache;
1650 ASSEMBLY_INFO info;
1651 static const WCHAR fusiondll[] = {'f','u','s','i','o','n',0};
1652 HMODULE hfusion=NULL;
1653 static HRESULT (WINAPI *pCreateAssemblyCache)(IAssemblyCache**,DWORD);
1655 if (!pCreateAssemblyCache)
1657 hr = LoadLibraryShim(fusiondll, NULL, NULL, &hfusion);
1659 if (SUCCEEDED(hr))
1661 pCreateAssemblyCache = (void*)GetProcAddress(hfusion, "CreateAssemblyCache");
1662 if (!pCreateAssemblyCache)
1663 hr = E_FAIL;
1667 if (SUCCEEDED(hr))
1668 hr = pCreateAssemblyCache(&asmcache, 0);
1670 if (SUCCEEDED(hr))
1672 info.cbAssemblyInfo = sizeof(info);
1673 info.pszCurrentAssemblyPathBuf = assemblies_path;
1674 info.cchBuf = path_length;
1675 assemblies_path[0] = 0;
1677 hr = IAssemblyCache_QueryAssemblyInfo(asmcache, 0, stringnameW, &info);
1679 IAssemblyCache_Release(asmcache);
1682 return hr;
1685 static MonoAssembly* mono_assembly_try_load(WCHAR *path)
1687 MonoAssembly *result = NULL;
1688 MonoImageOpenStatus stat;
1689 char *pathA;
1691 if (!(pathA = WtoA(path))) return NULL;
1693 result = mono_assembly_open(pathA, &stat);
1694 HeapFree(GetProcessHeap(), 0, pathA);
1696 if (result) TRACE("found: %s\n", debugstr_w(path));
1697 return result;
1700 static MonoAssembly* CDECL mono_assembly_preload_hook_fn(MonoAssemblyName *aname, char **assemblies_path, void *user_data)
1702 HRESULT hr;
1703 MonoAssembly *result=NULL;
1704 char *stringname=NULL;
1705 const char *assemblyname;
1706 const char *culture;
1707 LPWSTR stringnameW, cultureW;
1708 int stringnameW_size, cultureW_size;
1709 WCHAR path[MAX_PATH];
1710 char *pathA;
1711 MonoImageOpenStatus stat;
1712 DWORD search_flags;
1713 int i;
1714 static const WCHAR dotdllW[] = {'.','d','l','l',0};
1715 static const WCHAR dotexeW[] = {'.','e','x','e',0};
1717 stringname = mono_stringify_assembly_name(aname);
1718 assemblyname = mono_assembly_name_get_name(aname);
1719 culture = mono_assembly_name_get_culture(aname);
1720 if (culture)
1722 cultureW_size = MultiByteToWideChar(CP_UTF8, 0, culture, -1, NULL, 0);
1723 cultureW = HeapAlloc(GetProcessHeap(), 0, cultureW_size * sizeof(WCHAR));
1724 if (cultureW) MultiByteToWideChar(CP_UTF8, 0, culture, -1, cultureW, cultureW_size);
1726 else cultureW = NULL;
1728 TRACE("%s\n", debugstr_a(stringname));
1730 if (!stringname || !assemblyname) return NULL;
1732 search_flags = get_assembly_search_flags(aname);
1733 if (private_path)
1735 stringnameW_size = MultiByteToWideChar(CP_UTF8, 0, assemblyname, -1, NULL, 0);
1736 stringnameW = HeapAlloc(GetProcessHeap(), 0, stringnameW_size * sizeof(WCHAR));
1737 if (stringnameW)
1739 MultiByteToWideChar(CP_UTF8, 0, assemblyname, -1, stringnameW, stringnameW_size);
1740 for (i = 0; private_path[i] != NULL; i++)
1742 /* This is the lookup order used in Mono */
1743 /* 1st try: [culture]/[name].dll (culture may be empty) */
1744 wcscpy(path, private_path[i]);
1745 if (cultureW) PathAppendW(path, cultureW);
1746 PathAppendW(path, stringnameW);
1747 wcscat(path, dotdllW);
1748 result = mono_assembly_try_load(path);
1749 if (result) break;
1751 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1752 wcscpy(path + wcslen(path) - wcslen(dotdllW), dotexeW);
1753 result = mono_assembly_try_load(path);
1754 if (result) break;
1756 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1757 path[wcslen(path) - wcslen(dotexeW)] = 0;
1758 PathAppendW(path, stringnameW);
1759 wcscat(path, dotdllW);
1760 result = mono_assembly_try_load(path);
1761 if (result) break;
1763 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1764 wcscpy(path + wcslen(path) - wcslen(dotdllW), dotexeW);
1765 result = mono_assembly_try_load(path);
1766 if (result) break;
1768 HeapFree(GetProcessHeap(), 0, stringnameW);
1769 if (result) goto done;
1773 /* FIXME: We should search the given paths before the GAC. */
1775 if ((search_flags & ASSEMBLY_SEARCH_GAC) != 0)
1777 stringnameW_size = MultiByteToWideChar(CP_UTF8, 0, stringname, -1, NULL, 0);
1779 stringnameW = HeapAlloc(GetProcessHeap(), 0, stringnameW_size * sizeof(WCHAR));
1780 if (stringnameW)
1782 MultiByteToWideChar(CP_UTF8, 0, stringname, -1, stringnameW, stringnameW_size);
1784 hr = get_file_from_strongname(stringnameW, path, MAX_PATH);
1786 HeapFree(GetProcessHeap(), 0, stringnameW);
1788 else
1789 hr = E_OUTOFMEMORY;
1791 if (SUCCEEDED(hr))
1793 TRACE("found: %s\n", debugstr_w(path));
1795 pathA = WtoA(path);
1797 if (pathA)
1799 result = mono_assembly_open(pathA, &stat);
1801 if (!result)
1802 ERR("Failed to load %s, status=%u\n", debugstr_w(path), stat);
1804 HeapFree(GetProcessHeap(), 0, pathA);
1808 else
1809 TRACE("skipping Windows GAC search due to override setting\n");
1811 done:
1812 HeapFree(GetProcessHeap(), 0, cultureW);
1813 mono_free(stringname);
1815 return result;
1818 HRESULT get_runtime_info(LPCWSTR exefile, LPCWSTR version, LPCWSTR config_file,
1819 IStream *config_stream, DWORD startup_flags, DWORD runtimeinfo_flags,
1820 BOOL legacy, ICLRRuntimeInfo **result)
1822 static const WCHAR dotconfig[] = {'.','c','o','n','f','i','g',0};
1823 static const DWORD supported_startup_flags = 0;
1824 static const DWORD supported_runtime_flags = RUNTIME_INFO_UPGRADE_VERSION;
1825 int i;
1826 WCHAR local_version[MAX_PATH];
1827 ULONG local_version_size = MAX_PATH;
1828 WCHAR local_config_file[MAX_PATH];
1829 HRESULT hr;
1830 parsed_config_file parsed_config;
1832 if (startup_flags & ~supported_startup_flags)
1833 FIXME("unsupported startup flags %x\n", startup_flags & ~supported_startup_flags);
1835 if (runtimeinfo_flags & ~supported_runtime_flags)
1836 FIXME("unsupported runtimeinfo flags %x\n", runtimeinfo_flags & ~supported_runtime_flags);
1838 if (exefile && !exefile[0])
1839 exefile = NULL;
1841 if (exefile && !config_file && !config_stream)
1843 lstrcpyW(local_config_file, exefile);
1844 lstrcatW(local_config_file, dotconfig);
1846 config_file = local_config_file;
1849 if (config_file || config_stream)
1851 BOOL found = FALSE;
1852 if (config_file)
1853 hr = parse_config_file(config_file, &parsed_config);
1854 else
1855 hr = parse_config_stream(config_stream, &parsed_config);
1857 if (SUCCEEDED(hr))
1859 supported_runtime *entry;
1860 LIST_FOR_EACH_ENTRY(entry, &parsed_config.supported_runtimes, supported_runtime, entry)
1862 hr = get_runtime(entry->version, TRUE, &IID_ICLRRuntimeInfo, (void**)result);
1863 if (SUCCEEDED(hr))
1865 found = TRUE;
1866 break;
1870 else
1872 WARN("failed to parse config file %s, hr=%x\n", debugstr_w(config_file), hr);
1875 free_parsed_config_file(&parsed_config);
1877 if (found)
1878 return S_OK;
1881 if (exefile && !version)
1883 DWORD major, minor, build;
1885 hr = CLRMetaHost_GetVersionFromFile(0, exefile, local_version, &local_version_size);
1887 version = local_version;
1889 if (FAILED(hr)) return hr;
1891 /* When running an executable, specifically when getting the version number from
1892 * the exe, native accepts a matching major.minor with build <= expected build. */
1893 if (!parse_runtime_version(version, &major, &minor, &build))
1895 ERR("Cannot parse %s\n", debugstr_w(version));
1896 return CLR_E_SHIM_RUNTIME;
1899 if (legacy)
1900 i = 3;
1901 else
1902 i = NUM_RUNTIMES;
1904 while (i--)
1906 if (runtimes[i].major == major && runtimes[i].minor == minor && runtimes[i].build >= build)
1908 return ICLRRuntimeInfo_QueryInterface(&runtimes[i].ICLRRuntimeInfo_iface,
1909 &IID_ICLRRuntimeInfo, (void **)result);
1914 if (version)
1916 hr = CLRMetaHost_GetRuntime(0, version, &IID_ICLRRuntimeInfo, (void**)result);
1917 if(SUCCEEDED(hr))
1918 return hr;
1921 if (runtimeinfo_flags & RUNTIME_INFO_UPGRADE_VERSION)
1923 DWORD major, minor, build;
1925 if (version && !parse_runtime_version(version, &major, &minor, &build))
1927 ERR("Cannot parse %s\n", debugstr_w(version));
1928 return CLR_E_SHIM_RUNTIME;
1931 if (legacy)
1932 i = 3;
1933 else
1934 i = NUM_RUNTIMES;
1936 while (i--)
1938 /* Must be greater or equal to the version passed in. */
1939 if (!version || ((runtimes[i].major >= major && runtimes[i].minor >= minor && runtimes[i].build >= build) ||
1940 (runtimes[i].major >= major && runtimes[i].minor > minor) ||
1941 (runtimes[i].major > major)))
1943 return ICLRRuntimeInfo_QueryInterface(&runtimes[i].ICLRRuntimeInfo_iface,
1944 &IID_ICLRRuntimeInfo, (void **)result);
1948 return CLR_E_SHIM_RUNTIME;
1951 return CLR_E_SHIM_RUNTIME;