mscoree: Implement GetFileVersion.
[wine] / dlls / mscoree / metahost.c
1 /*
2  * ICLRMetaHost - discovery and management of available .NET runtimes
3  *
4  * Copyright 2010 Vincent Povirk for CodeWeavers
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include <stdio.h>
22 #include <stdarg.h>
23 #include <assert.h>
24
25 #define COBJMACROS
26
27 #include "wine/unicode.h"
28 #include "wine/library.h"
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winreg.h"
32 #include "ole2.h"
33
34 #include "corerror.h"
35 #include "mscoree.h"
36 #include "fusion.h"
37 #include "metahost.h"
38 #include "wine/list.h"
39 #include "mscoree_private.h"
40
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL( mscoree );
44
45 static const WCHAR net_11_subdir[] = {'1','.','0',0};
46 static const WCHAR net_20_subdir[] = {'2','.','0',0};
47 static const WCHAR net_40_subdir[] = {'4','.','0',0};
48
49 const struct ICLRRuntimeInfoVtbl CLRRuntimeInfoVtbl;
50
51 #define NUM_RUNTIMES 3
52
53 static struct CLRRuntimeInfo runtimes[NUM_RUNTIMES] = {
54     {&CLRRuntimeInfoVtbl, net_11_subdir, 1, 1, 4322, 0},
55     {&CLRRuntimeInfoVtbl, net_20_subdir, 2, 0, 50727, 0},
56     {&CLRRuntimeInfoVtbl, net_40_subdir, 4, 0, 30319, 0}
57 };
58
59 static int runtimes_initialized;
60
61 static CRITICAL_SECTION runtime_list_cs;
62 static CRITICAL_SECTION_DEBUG runtime_list_cs_debug =
63 {
64     0, 0, &runtime_list_cs,
65     { &runtime_list_cs_debug.ProcessLocksList,
66       &runtime_list_cs_debug.ProcessLocksList },
67       0, 0, { (DWORD_PTR)(__FILE__ ": runtime_list_cs") }
68 };
69 static CRITICAL_SECTION runtime_list_cs = { &runtime_list_cs_debug, -1, 0, 0, 0, 0 };
70
71 #define NUM_ABI_VERSIONS 2
72
73 static loaded_mono loaded_monos[NUM_ABI_VERSIONS];
74
75 static BOOL find_mono_dll(LPCWSTR path, LPWSTR dll_path, int abi_version);
76
77 static MonoAssembly* mono_assembly_search_hook_fn(MonoAssemblyName *aname, char **assemblies_path, void *user_data);
78
79 static void set_environment(LPCWSTR bin_path)
80 {
81     WCHAR path_env[MAX_PATH];
82     int len;
83
84     static const WCHAR pathW[] = {'P','A','T','H',0};
85
86     /* We have to modify PATH as Mono loads other DLLs from this directory. */
87     GetEnvironmentVariableW(pathW, path_env, sizeof(path_env)/sizeof(WCHAR));
88     len = strlenW(path_env);
89     path_env[len++] = ';';
90     strcpyW(path_env+len, bin_path);
91     SetEnvironmentVariableW(pathW, path_env);
92 }
93
94 static HRESULT load_mono(CLRRuntimeInfo *This, loaded_mono **result)
95 {
96     static const WCHAR bin[] = {'\\','b','i','n',0};
97     static const WCHAR lib[] = {'\\','l','i','b',0};
98     static const WCHAR etc[] = {'\\','e','t','c',0};
99     static const WCHAR glibdll[] = {'l','i','b','g','l','i','b','-','2','.','0','-','0','.','d','l','l',0};
100     WCHAR mono_dll_path[MAX_PATH+16], mono_bin_path[MAX_PATH+4];
101     WCHAR mono_lib_path[MAX_PATH+4], mono_etc_path[MAX_PATH+4];
102     char mono_lib_path_a[MAX_PATH], mono_etc_path_a[MAX_PATH];
103     int trace_size;
104     char trace_setting[256];
105
106     if (This->mono_abi_version == -1)
107         MESSAGE("wine: Install the Windows version of Mono to run .NET executables\n");
108
109     if (This->mono_abi_version <= 0 || This->mono_abi_version > NUM_ABI_VERSIONS)
110         return E_FAIL;
111
112     *result = &loaded_monos[This->mono_abi_version-1];
113
114     if (!(*result)->mono_handle)
115     {
116         strcpyW(mono_bin_path, This->mono_path);
117         strcatW(mono_bin_path, bin);
118         set_environment(mono_bin_path);
119
120         strcpyW(mono_lib_path, This->mono_path);
121         strcatW(mono_lib_path, lib);
122         WideCharToMultiByte(CP_UTF8, 0, mono_lib_path, -1, mono_lib_path_a, MAX_PATH, NULL, NULL);
123
124         strcpyW(mono_etc_path, This->mono_path);
125         strcatW(mono_etc_path, etc);
126         WideCharToMultiByte(CP_UTF8, 0, mono_etc_path, -1, mono_etc_path_a, MAX_PATH, NULL, NULL);
127
128         if (!find_mono_dll(This->mono_path, mono_dll_path, This->mono_abi_version)) goto fail;
129
130         (*result)->mono_handle = LoadLibraryW(mono_dll_path);
131
132         if (!(*result)->mono_handle) goto fail;
133
134 #define LOAD_MONO_FUNCTION(x) do { \
135     (*result)->x = (void*)GetProcAddress((*result)->mono_handle, #x); \
136     if (!(*result)->x) { \
137         goto fail; \
138     } \
139 } while (0);
140
141         LOAD_MONO_FUNCTION(mono_assembly_get_image);
142         LOAD_MONO_FUNCTION(mono_assembly_open);
143         LOAD_MONO_FUNCTION(mono_config_parse);
144         LOAD_MONO_FUNCTION(mono_class_from_mono_type);
145         LOAD_MONO_FUNCTION(mono_class_from_name);
146         LOAD_MONO_FUNCTION(mono_class_get_method_from_name);
147         LOAD_MONO_FUNCTION(mono_domain_assembly_open);
148         LOAD_MONO_FUNCTION(mono_install_assembly_preload_hook);
149         LOAD_MONO_FUNCTION(mono_jit_cleanup);
150         LOAD_MONO_FUNCTION(mono_jit_exec);
151         LOAD_MONO_FUNCTION(mono_jit_init);
152         LOAD_MONO_FUNCTION(mono_jit_set_trace_options);
153         LOAD_MONO_FUNCTION(mono_object_get_domain);
154         LOAD_MONO_FUNCTION(mono_object_new);
155         LOAD_MONO_FUNCTION(mono_object_unbox);
156         LOAD_MONO_FUNCTION(mono_reflection_type_from_name);
157         LOAD_MONO_FUNCTION(mono_runtime_invoke);
158         LOAD_MONO_FUNCTION(mono_runtime_object_init);
159         LOAD_MONO_FUNCTION(mono_set_dirs);
160         LOAD_MONO_FUNCTION(mono_stringify_assembly_name);
161
162         /* GLib imports obsoleted by the 2.0 ABI */
163         if (This->mono_abi_version == 1)
164         {
165             (*result)->glib_handle = LoadLibraryW(glibdll);
166             if (!(*result)->glib_handle) goto fail;
167
168             (*result)->mono_free = (void*)GetProcAddress((*result)->glib_handle, "g_free");
169             if (!(*result)->mono_free) goto fail;
170         }
171         else
172         {
173             LOAD_MONO_FUNCTION(mono_free);
174         }
175
176 #undef LOAD_MONO_FUNCTION
177
178         (*result)->mono_set_dirs(mono_lib_path_a, mono_etc_path_a);
179
180         (*result)->mono_config_parse(NULL);
181
182         (*result)->mono_install_assembly_preload_hook(mono_assembly_search_hook_fn, *result);
183
184         trace_size = GetEnvironmentVariableA("WINE_MONO_TRACE", trace_setting, sizeof(trace_setting));
185
186         if (trace_size)
187         {
188             (*result)->mono_jit_set_trace_options(trace_setting);
189         }
190     }
191
192     return S_OK;
193
194 fail:
195     ERR("Could not load Mono into this process\n");
196     FreeLibrary((*result)->mono_handle);
197     FreeLibrary((*result)->glib_handle);
198     (*result)->mono_handle = NULL;
199     (*result)->glib_handle = NULL;
200     return E_FAIL;
201 }
202
203 static HRESULT CLRRuntimeInfo_GetRuntimeHost(CLRRuntimeInfo *This, RuntimeHost **result)
204 {
205     HRESULT hr = S_OK;
206     loaded_mono *ploaded_mono;
207
208     if (This->loaded_runtime)
209     {
210         *result = This->loaded_runtime;
211         return hr;
212     }
213
214     EnterCriticalSection(&runtime_list_cs);
215
216     hr = load_mono(This, &ploaded_mono);
217
218     if (SUCCEEDED(hr))
219         hr = RuntimeHost_Construct(This, ploaded_mono, &This->loaded_runtime);
220
221     LeaveCriticalSection(&runtime_list_cs);
222
223     if (SUCCEEDED(hr))
224         *result = This->loaded_runtime;
225
226     return hr;
227 }
228
229 void unload_all_runtimes(void)
230 {
231     int i;
232
233     for (i=0; i<NUM_RUNTIMES; i++)
234         if (runtimes[i].loaded_runtime)
235             RuntimeHost_Destroy(runtimes[i].loaded_runtime);
236 }
237
238 static HRESULT WINAPI CLRRuntimeInfo_QueryInterface(ICLRRuntimeInfo* iface,
239         REFIID riid,
240         void **ppvObject)
241 {
242     TRACE("%p %s %p\n", iface, debugstr_guid(riid), ppvObject);
243
244     if ( IsEqualGUID( riid, &IID_ICLRRuntimeInfo ) ||
245          IsEqualGUID( riid, &IID_IUnknown ) )
246     {
247         *ppvObject = iface;
248     }
249     else
250     {
251         FIXME("Unsupported interface %s\n", debugstr_guid(riid));
252         return E_NOINTERFACE;
253     }
254
255     ICLRRuntimeInfo_AddRef( iface );
256
257     return S_OK;
258 }
259
260 static ULONG WINAPI CLRRuntimeInfo_AddRef(ICLRRuntimeInfo* iface)
261 {
262     MSCOREE_LockModule();
263     return 2;
264 }
265
266 static ULONG WINAPI CLRRuntimeInfo_Release(ICLRRuntimeInfo* iface)
267 {
268     MSCOREE_UnlockModule();
269     return 1;
270 }
271
272 static HRESULT WINAPI CLRRuntimeInfo_GetVersionString(ICLRRuntimeInfo* iface,
273     LPWSTR pwzBuffer, DWORD *pcchBuffer)
274 {
275     struct CLRRuntimeInfo *This = (struct CLRRuntimeInfo*)iface;
276     DWORD buffer_size = *pcchBuffer;
277     HRESULT hr = S_OK;
278     char version[11];
279     DWORD size;
280
281     TRACE("%p %p %p\n", iface, pwzBuffer, pcchBuffer);
282
283     size = snprintf(version, sizeof(version), "v%u.%u.%u", This->major, This->minor, This->build);
284
285     assert(size <= sizeof(version));
286
287     *pcchBuffer = MultiByteToWideChar(CP_UTF8, 0, version, -1, NULL, 0);
288
289     if (pwzBuffer)
290     {
291         if (buffer_size >= *pcchBuffer)
292             MultiByteToWideChar(CP_UTF8, 0, version, -1, pwzBuffer, buffer_size);
293         else
294             hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
295     }
296
297     return hr;
298 }
299
300 static BOOL get_install_root(LPWSTR install_dir)
301 {
302     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};
303     const WCHAR install_root[] = {'I','n','s','t','a','l','l','R','o','o','t',0};
304
305     DWORD len;
306     HKEY key;
307
308     if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, dotnet_key, 0, KEY_READ, &key))
309         return FALSE;
310
311     len = MAX_PATH;
312     if (RegQueryValueExW(key, install_root, 0, NULL, (LPBYTE)install_dir, &len))
313     {
314         RegCloseKey(key);
315         return FALSE;
316     }
317     RegCloseKey(key);
318
319     return TRUE;
320 }
321
322 static HRESULT WINAPI CLRRuntimeInfo_GetRuntimeDirectory(ICLRRuntimeInfo* iface,
323     LPWSTR pwzBuffer, DWORD *pcchBuffer)
324 {
325     static const WCHAR slash[] = {'\\',0};
326     DWORD buffer_size = *pcchBuffer;
327     WCHAR system_dir[MAX_PATH];
328     WCHAR version[MAX_PATH];
329     DWORD version_size, size;
330     HRESULT hr = S_OK;
331
332     TRACE("%p %p %p\n", iface, pwzBuffer, pcchBuffer);
333
334     if (!get_install_root(system_dir))
335     {
336         ERR("error reading registry key for installroot\n");
337         return E_FAIL;
338     }
339     else
340     {
341         version_size = MAX_PATH;
342         ICLRRuntimeInfo_GetVersionString(iface, version, &version_size);
343         lstrcatW(system_dir, version);
344         lstrcatW(system_dir, slash);
345         size = lstrlenW(system_dir) + 1;
346     }
347
348     *pcchBuffer = size;
349
350     if (pwzBuffer)
351     {
352         if (buffer_size >= size)
353             strcpyW(pwzBuffer, system_dir);
354         else
355             hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
356     }
357
358     return hr;
359 }
360
361 static HRESULT WINAPI CLRRuntimeInfo_IsLoaded(ICLRRuntimeInfo* iface,
362     HANDLE hndProcess, BOOL *pbLoaded)
363 {
364     FIXME("%p %p %p\n", iface, hndProcess, pbLoaded);
365
366     return E_NOTIMPL;
367 }
368
369 static HRESULT WINAPI CLRRuntimeInfo_LoadErrorString(ICLRRuntimeInfo* iface,
370     UINT iResourceID, LPWSTR pwzBuffer, DWORD *pcchBuffer, LONG iLocaleid)
371 {
372     FIXME("%p %u %p %p %x\n", iface, iResourceID, pwzBuffer, pcchBuffer, iLocaleid);
373
374     return E_NOTIMPL;
375 }
376
377 static HRESULT WINAPI CLRRuntimeInfo_LoadLibrary(ICLRRuntimeInfo* iface,
378     LPCWSTR pwzDllName, HMODULE *phndModule)
379 {
380     WCHAR version[MAX_PATH];
381     HRESULT hr;
382     DWORD cchBuffer;
383
384     TRACE("%p %s %p\n", iface, debugstr_w(pwzDllName), phndModule);
385
386     cchBuffer = MAX_PATH;
387     hr = ICLRRuntimeInfo_GetVersionString(iface, version, &cchBuffer);
388     if (FAILED(hr)) return hr;
389
390     return LoadLibraryShim(pwzDllName, version, NULL, phndModule);
391 }
392
393 static HRESULT WINAPI CLRRuntimeInfo_GetProcAddress(ICLRRuntimeInfo* iface,
394     LPCSTR pszProcName, LPVOID *ppProc)
395 {
396     FIXME("%p %s %p\n", iface, debugstr_a(pszProcName), ppProc);
397
398     return E_NOTIMPL;
399 }
400
401 static HRESULT WINAPI CLRRuntimeInfo_GetInterface(ICLRRuntimeInfo* iface,
402     REFCLSID rclsid, REFIID riid, LPVOID *ppUnk)
403 {
404     struct CLRRuntimeInfo *This = (struct CLRRuntimeInfo*)iface;
405     RuntimeHost *host;
406     HRESULT hr;
407
408     TRACE("%p %s %s %p\n", iface, debugstr_guid(rclsid), debugstr_guid(riid), ppUnk);
409
410     hr = CLRRuntimeInfo_GetRuntimeHost(This, &host);
411
412     if (SUCCEEDED(hr))
413         hr = RuntimeHost_GetInterface(host, rclsid, riid, ppUnk);
414
415     return hr;
416 }
417
418 static HRESULT WINAPI CLRRuntimeInfo_IsLoadable(ICLRRuntimeInfo* iface,
419     BOOL *pbLoadable)
420 {
421     FIXME("%p %p\n", iface, pbLoadable);
422
423     return E_NOTIMPL;
424 }
425
426 static HRESULT WINAPI CLRRuntimeInfo_SetDefaultStartupFlags(ICLRRuntimeInfo* iface,
427     DWORD dwStartupFlags, LPCWSTR pwzHostConfigFile)
428 {
429     FIXME("%p %x %s\n", iface, dwStartupFlags, debugstr_w(pwzHostConfigFile));
430
431     return E_NOTIMPL;
432 }
433
434 static HRESULT WINAPI CLRRuntimeInfo_GetDefaultStartupFlags(ICLRRuntimeInfo* iface,
435     DWORD *pdwStartupFlags, LPWSTR pwzHostConfigFile, DWORD *pcchHostConfigFile)
436 {
437     FIXME("%p %p %p %p\n", iface, pdwStartupFlags, pwzHostConfigFile, pcchHostConfigFile);
438
439     return E_NOTIMPL;
440 }
441
442 static HRESULT WINAPI CLRRuntimeInfo_BindAsLegacyV2Runtime(ICLRRuntimeInfo* iface)
443 {
444     FIXME("%p\n", iface);
445
446     return E_NOTIMPL;
447 }
448
449 static HRESULT WINAPI CLRRuntimeInfo_IsStarted(ICLRRuntimeInfo* iface,
450     BOOL *pbStarted, DWORD *pdwStartupFlags)
451 {
452     FIXME("%p %p %p\n", iface, pbStarted, pdwStartupFlags);
453
454     return E_NOTIMPL;
455 }
456
457 const struct ICLRRuntimeInfoVtbl CLRRuntimeInfoVtbl = {
458     CLRRuntimeInfo_QueryInterface,
459     CLRRuntimeInfo_AddRef,
460     CLRRuntimeInfo_Release,
461     CLRRuntimeInfo_GetVersionString,
462     CLRRuntimeInfo_GetRuntimeDirectory,
463     CLRRuntimeInfo_IsLoaded,
464     CLRRuntimeInfo_LoadErrorString,
465     CLRRuntimeInfo_LoadLibrary,
466     CLRRuntimeInfo_GetProcAddress,
467     CLRRuntimeInfo_GetInterface,
468     CLRRuntimeInfo_IsLoadable,
469     CLRRuntimeInfo_SetDefaultStartupFlags,
470     CLRRuntimeInfo_GetDefaultStartupFlags,
471     CLRRuntimeInfo_BindAsLegacyV2Runtime,
472     CLRRuntimeInfo_IsStarted
473 };
474
475 HRESULT ICLRRuntimeInfo_GetRuntimeHost(ICLRRuntimeInfo *iface, RuntimeHost **result)
476 {
477     struct CLRRuntimeInfo *This = (struct CLRRuntimeInfo*)iface;
478
479     assert(This->ICLRRuntimeInfo_vtbl == &CLRRuntimeInfoVtbl);
480
481     return CLRRuntimeInfo_GetRuntimeHost(This, result);
482 }
483
484 static BOOL find_mono_dll(LPCWSTR path, LPWSTR dll_path, int abi_version)
485 {
486     static const WCHAR mono_dll[] = {'\\','b','i','n','\\','m','o','n','o','.','d','l','l',0};
487     static const WCHAR libmono_dll[] = {'\\','b','i','n','\\','l','i','b','m','o','n','o','.','d','l','l',0};
488     static const WCHAR mono2_dll[] = {'\\','b','i','n','\\','m','o','n','o','-','2','.','0','.','d','l','l',0};
489     static const WCHAR libmono2_dll[] = {'\\','b','i','n','\\','l','i','b','m','o','n','o','-','2','.','0','.','d','l','l',0};
490     DWORD attributes=INVALID_FILE_ATTRIBUTES;
491
492     if (abi_version == 1)
493     {
494         strcpyW(dll_path, path);
495         strcatW(dll_path, mono_dll);
496         attributes = GetFileAttributesW(dll_path);
497
498         if (attributes == INVALID_FILE_ATTRIBUTES)
499         {
500             strcpyW(dll_path, path);
501             strcatW(dll_path, libmono_dll);
502             attributes = GetFileAttributesW(dll_path);
503         }
504     }
505     else if (abi_version == 2)
506     {
507         strcpyW(dll_path, path);
508         strcatW(dll_path, mono2_dll);
509         attributes = GetFileAttributesW(dll_path);
510
511         if (attributes == INVALID_FILE_ATTRIBUTES)
512         {
513             strcpyW(dll_path, path);
514             strcatW(dll_path, libmono2_dll);
515             attributes = GetFileAttributesW(dll_path);
516         }
517     }
518
519     return (attributes != INVALID_FILE_ATTRIBUTES);
520 }
521
522 static BOOL get_mono_path_from_registry(LPWSTR path, int abi_version)
523 {
524     static const WCHAR mono_key[] = {'S','o','f','t','w','a','r','e','\\','N','o','v','e','l','l','\\','M','o','n','o',0};
525     static const WCHAR defaul_clr[] = {'D','e','f','a','u','l','t','C','L','R',0};
526     static const WCHAR install_root[] = {'S','d','k','I','n','s','t','a','l','l','R','o','o','t',0};
527     static const WCHAR slash[] = {'\\',0};
528
529     WCHAR version[64], version_key[MAX_PATH];
530     DWORD len;
531     HKEY key;
532     WCHAR dll_path[MAX_PATH];
533
534     if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, mono_key, 0, KEY_READ, &key))
535         return FALSE;
536
537     len = sizeof(version);
538     if (RegQueryValueExW(key, defaul_clr, 0, NULL, (LPBYTE)version, &len))
539     {
540         RegCloseKey(key);
541         return FALSE;
542     }
543     RegCloseKey(key);
544
545     lstrcpyW(version_key, mono_key);
546     lstrcatW(version_key, slash);
547     lstrcatW(version_key, version);
548
549     if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, version_key, 0, KEY_READ, &key))
550         return FALSE;
551
552     len = sizeof(WCHAR) * MAX_PATH;
553     if (RegQueryValueExW(key, install_root, 0, NULL, (LPBYTE)path, &len))
554     {
555         RegCloseKey(key);
556         return FALSE;
557     }
558     RegCloseKey(key);
559
560     return find_mono_dll(path, dll_path, abi_version);
561 }
562
563 static BOOL get_mono_path_from_folder(LPCWSTR folder, LPWSTR mono_path, int abi_version)
564 {
565     static const WCHAR mono_one_dot_zero[] = {'\\','m','o','n','o','-','1','.','0', 0};
566     static const WCHAR mono_two_dot_zero[] = {'\\','m','o','n','o','-','2','.','0', 0};
567     WCHAR mono_dll_path[MAX_PATH];
568     BOOL found = FALSE;
569
570     strcpyW(mono_path, folder);
571
572     if (abi_version == 1)
573         strcatW(mono_path, mono_one_dot_zero);
574     else if (abi_version == 2)
575         strcatW(mono_path, mono_two_dot_zero);
576
577     found = find_mono_dll(mono_path, mono_dll_path, abi_version);
578
579     return found;
580 }
581
582 static BOOL get_mono_path(LPWSTR path, int abi_version)
583 {
584     static const WCHAR subdir_mono[] = {'\\','m','o','n','o',0};
585     static const WCHAR sibling_mono[] = {'\\','.','.','\\','m','o','n','o',0};
586     WCHAR base_path[MAX_PATH];
587     const char *unix_data_dir;
588     WCHAR *dos_data_dir;
589     int build_tree=0;
590     static WCHAR* (CDECL *wine_get_dos_file_name)(const char*);
591
592     /* First try c:\windows\mono */
593     GetWindowsDirectoryW(base_path, MAX_PATH);
594     strcatW(base_path, subdir_mono);
595
596     if (get_mono_path_from_folder(base_path, path, abi_version))
597         return TRUE;
598
599     /* Next: /usr/share/wine/mono */
600     unix_data_dir = wine_get_data_dir();
601
602     if (!unix_data_dir)
603     {
604         unix_data_dir = wine_get_build_dir();
605         build_tree = 1;
606     }
607
608     if (unix_data_dir)
609     {
610         if (!wine_get_dos_file_name)
611             wine_get_dos_file_name = (void*)GetProcAddress(GetModuleHandleA("kernel32"), "wine_get_dos_file_name");
612
613         if (wine_get_dos_file_name)
614         {
615             dos_data_dir = wine_get_dos_file_name(unix_data_dir);
616
617             if (dos_data_dir)
618             {
619                 strcpyW(base_path, dos_data_dir);
620                 strcatW(base_path, build_tree ? sibling_mono : subdir_mono);
621
622                 HeapFree(GetProcessHeap(), 0, dos_data_dir);
623
624                 if (get_mono_path_from_folder(base_path, path, abi_version))
625                     return TRUE;
626             }
627         }
628     }
629
630     /* Last: the registry */
631     return get_mono_path_from_registry(path, abi_version);
632 }
633
634 static void find_runtimes(void)
635 {
636     int abi_version, i;
637     static const WCHAR libmono[] = {'\\','l','i','b','\\','m','o','n','o','\\',0};
638     static const WCHAR mscorlib[] = {'\\','m','s','c','o','r','l','i','b','.','d','l','l',0};
639     WCHAR mono_path[MAX_PATH], lib_path[MAX_PATH];
640     BOOL any_runtimes_found = FALSE;
641
642     if (runtimes_initialized) return;
643
644     EnterCriticalSection(&runtime_list_cs);
645
646     if (runtimes_initialized) goto end;
647
648     for (abi_version=NUM_ABI_VERSIONS; abi_version>0; abi_version--)
649     {
650         if (!get_mono_path(mono_path, abi_version))
651             continue;
652
653         for (i=0; i<NUM_RUNTIMES; i++)
654         {
655             if (runtimes[i].mono_abi_version == 0)
656             {
657                 strcpyW(lib_path, mono_path);
658                 strcatW(lib_path, libmono);
659                 strcatW(lib_path, runtimes[i].mono_libdir);
660                 strcatW(lib_path, mscorlib);
661
662                 if (GetFileAttributesW(lib_path) != INVALID_FILE_ATTRIBUTES)
663                 {
664                     runtimes[i].mono_abi_version = abi_version;
665
666                     strcpyW(runtimes[i].mono_path, mono_path);
667                     strcpyW(runtimes[i].mscorlib_path, lib_path);
668
669                     any_runtimes_found = TRUE;
670                 }
671             }
672         }
673     }
674
675     if (!any_runtimes_found)
676     {
677         /* Report all runtimes are available if Mono isn't installed.
678          * FIXME: Remove this when Mono is properly packaged. */
679         for (i=0; i<NUM_RUNTIMES; i++)
680             runtimes[i].mono_abi_version = -1;
681     }
682
683     runtimes_initialized = 1;
684
685 end:
686     LeaveCriticalSection(&runtime_list_cs);
687 }
688
689 struct InstalledRuntimeEnum
690 {
691     const struct IEnumUnknownVtbl *Vtbl;
692     LONG ref;
693     ULONG pos;
694 };
695
696 const struct IEnumUnknownVtbl InstalledRuntimeEnum_Vtbl;
697
698 static HRESULT WINAPI InstalledRuntimeEnum_QueryInterface(IEnumUnknown* iface,
699         REFIID riid,
700         void **ppvObject)
701 {
702     TRACE("%p %s %p\n", iface, debugstr_guid(riid), ppvObject);
703
704     if ( IsEqualGUID( riid, &IID_IEnumUnknown ) ||
705          IsEqualGUID( riid, &IID_IUnknown ) )
706     {
707         *ppvObject = iface;
708     }
709     else
710     {
711         FIXME("Unsupported interface %s\n", debugstr_guid(riid));
712         return E_NOINTERFACE;
713     }
714
715     IEnumUnknown_AddRef( iface );
716
717     return S_OK;
718 }
719
720 static ULONG WINAPI InstalledRuntimeEnum_AddRef(IEnumUnknown* iface)
721 {
722     struct InstalledRuntimeEnum *This = (struct InstalledRuntimeEnum*)iface;
723     ULONG ref = InterlockedIncrement(&This->ref);
724
725     MSCOREE_LockModule();
726
727     TRACE("(%p) refcount=%u\n", iface, ref);
728
729     return ref;
730 }
731
732 static ULONG WINAPI InstalledRuntimeEnum_Release(IEnumUnknown* iface)
733 {
734     struct InstalledRuntimeEnum *This = (struct InstalledRuntimeEnum*)iface;
735     ULONG ref = InterlockedDecrement(&This->ref);
736
737     MSCOREE_UnlockModule();
738
739     TRACE("(%p) refcount=%u\n", iface, ref);
740
741     if (ref == 0)
742     {
743         HeapFree(GetProcessHeap(), 0, This);
744     }
745
746     return ref;
747 }
748
749 static HRESULT WINAPI InstalledRuntimeEnum_Next(IEnumUnknown *iface, ULONG celt,
750     IUnknown **rgelt, ULONG *pceltFetched)
751 {
752     struct InstalledRuntimeEnum *This = (struct InstalledRuntimeEnum*)iface;
753     int num_fetched = 0;
754     HRESULT hr=S_OK;
755     IUnknown *item;
756
757     TRACE("(%p,%u,%p,%p)\n", iface, celt, rgelt, pceltFetched);
758
759     while (num_fetched < celt)
760     {
761         if (This->pos >= NUM_RUNTIMES)
762         {
763             hr = S_FALSE;
764             break;
765         }
766         if (runtimes[This->pos].mono_abi_version)
767         {
768             item = (IUnknown*)&runtimes[This->pos];
769             IUnknown_AddRef(item);
770             rgelt[num_fetched] = item;
771             num_fetched++;
772         }
773         This->pos++;
774     }
775
776     if (pceltFetched)
777         *pceltFetched = num_fetched;
778
779     return hr;
780 }
781
782 static HRESULT WINAPI InstalledRuntimeEnum_Skip(IEnumUnknown *iface, ULONG celt)
783 {
784     struct InstalledRuntimeEnum *This = (struct InstalledRuntimeEnum*)iface;
785     int num_fetched = 0;
786     HRESULT hr=S_OK;
787
788     TRACE("(%p,%u)\n", iface, celt);
789
790     while (num_fetched < celt)
791     {
792         if (This->pos >= NUM_RUNTIMES)
793         {
794             hr = S_FALSE;
795             break;
796         }
797         if (runtimes[This->pos].mono_abi_version)
798         {
799             num_fetched++;
800         }
801         This->pos++;
802     }
803
804     return hr;
805 }
806
807 static HRESULT WINAPI InstalledRuntimeEnum_Reset(IEnumUnknown *iface)
808 {
809     struct InstalledRuntimeEnum *This = (struct InstalledRuntimeEnum*)iface;
810
811     TRACE("(%p)\n", iface);
812
813     This->pos = 0;
814
815     return S_OK;
816 }
817
818 static HRESULT WINAPI InstalledRuntimeEnum_Clone(IEnumUnknown *iface, IEnumUnknown **ppenum)
819 {
820     struct InstalledRuntimeEnum *This = (struct InstalledRuntimeEnum*)iface;
821     struct InstalledRuntimeEnum *new_enum;
822
823     TRACE("(%p)\n", iface);
824
825     new_enum = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_enum));
826     if (!new_enum)
827         return E_OUTOFMEMORY;
828
829     new_enum->Vtbl = &InstalledRuntimeEnum_Vtbl;
830     new_enum->ref = 1;
831     new_enum->pos = This->pos;
832
833     *ppenum = (IEnumUnknown*)new_enum;
834
835     return S_OK;
836 }
837
838 const struct IEnumUnknownVtbl InstalledRuntimeEnum_Vtbl = {
839     InstalledRuntimeEnum_QueryInterface,
840     InstalledRuntimeEnum_AddRef,
841     InstalledRuntimeEnum_Release,
842     InstalledRuntimeEnum_Next,
843     InstalledRuntimeEnum_Skip,
844     InstalledRuntimeEnum_Reset,
845     InstalledRuntimeEnum_Clone
846 };
847
848 struct CLRMetaHost
849 {
850     const struct ICLRMetaHostVtbl *CLRMetaHost_vtbl;
851 };
852
853 static const struct CLRMetaHost GlobalCLRMetaHost;
854
855 static HRESULT WINAPI CLRMetaHost_QueryInterface(ICLRMetaHost* iface,
856         REFIID riid,
857         void **ppvObject)
858 {
859     TRACE("%s %p\n", debugstr_guid(riid), ppvObject);
860
861     if ( IsEqualGUID( riid, &IID_ICLRMetaHost ) ||
862          IsEqualGUID( riid, &IID_IUnknown ) )
863     {
864         *ppvObject = iface;
865     }
866     else
867     {
868         FIXME("Unsupported interface %s\n", debugstr_guid(riid));
869         return E_NOINTERFACE;
870     }
871
872     ICLRMetaHost_AddRef( iface );
873
874     return S_OK;
875 }
876
877 static ULONG WINAPI CLRMetaHost_AddRef(ICLRMetaHost* iface)
878 {
879     MSCOREE_LockModule();
880     return 2;
881 }
882
883 static ULONG WINAPI CLRMetaHost_Release(ICLRMetaHost* iface)
884 {
885     MSCOREE_UnlockModule();
886     return 1;
887 }
888
889 static BOOL parse_runtime_version(LPCWSTR version, DWORD *major, DWORD *minor, DWORD *build)
890 {
891     *major = 0;
892     *minor = 0;
893     *build = 0;
894
895     if (version[0] == 'v')
896     {
897         version++;
898         if (!isdigit(*version))
899             return FALSE;
900
901         while (isdigit(*version))
902             *major = *major * 10 + (*version++ - '0');
903
904         if (*version == 0)
905             return TRUE;
906
907         if (*version++ != '.' || !isdigit(*version))
908             return FALSE;
909
910         while (isdigit(*version))
911             *minor = *minor * 10 + (*version++ - '0');
912
913         if (*version == 0)
914             return TRUE;
915
916         if (*version++ != '.' || !isdigit(*version))
917             return FALSE;
918
919         while (isdigit(*version))
920             *build = *build * 10 + (*version++ - '0');
921
922         return *version == 0;
923     }
924     else
925         return FALSE;
926 }
927
928 static HRESULT WINAPI CLRMetaHost_GetRuntime(ICLRMetaHost* iface,
929     LPCWSTR pwzVersion, REFIID iid, LPVOID *ppRuntime)
930 {
931     int i;
932     DWORD major, minor, build;
933
934     TRACE("%s %s %p\n", debugstr_w(pwzVersion), debugstr_guid(iid), ppRuntime);
935
936     if (!pwzVersion)
937         return E_POINTER;
938
939     if (!parse_runtime_version(pwzVersion, &major, &minor, &build))
940     {
941         ERR("Cannot parse %s\n", debugstr_w(pwzVersion));
942         return CLR_E_SHIM_RUNTIME;
943     }
944
945     find_runtimes();
946
947     for (i=0; i<NUM_RUNTIMES; i++)
948     {
949         if (runtimes[i].major == major && runtimes[i].minor == minor &&
950             runtimes[i].build == build)
951         {
952             if (runtimes[i].mono_abi_version)
953                 return IUnknown_QueryInterface((IUnknown*)&runtimes[i], iid, ppRuntime);
954             else
955             {
956                 ERR("Mono is missing %s runtime\n", debugstr_w(pwzVersion));
957                 return CLR_E_SHIM_RUNTIME;
958             }
959         }
960     }
961
962     FIXME("Unrecognized version %s\n", debugstr_w(pwzVersion));
963     return CLR_E_SHIM_RUNTIME;
964 }
965
966 HRESULT WINAPI CLRMetaHost_GetVersionFromFile(ICLRMetaHost* iface,
967     LPCWSTR pwzFilePath, LPWSTR pwzBuffer, DWORD *pcchBuffer)
968 {
969     ASSEMBLY *assembly;
970     HRESULT hr;
971     LPSTR version;
972     ULONG buffer_size=*pcchBuffer;
973
974     TRACE("%s %p %p\n", debugstr_w(pwzFilePath), pwzBuffer, pcchBuffer);
975
976     hr = assembly_create(&assembly, pwzFilePath);
977
978     if (SUCCEEDED(hr))
979     {
980         hr = assembly_get_runtime_version(assembly, &version);
981
982         if (SUCCEEDED(hr))
983         {
984             *pcchBuffer = MultiByteToWideChar(CP_UTF8, 0, version, -1, NULL, 0);
985
986             if (pwzBuffer)
987             {
988                 if (buffer_size >= *pcchBuffer)
989                     MultiByteToWideChar(CP_UTF8, 0, version, -1, pwzBuffer, buffer_size);
990                 else
991                     hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
992             }
993         }
994
995         assembly_release(assembly);
996     }
997
998     return hr;
999 }
1000
1001 static HRESULT WINAPI CLRMetaHost_EnumerateInstalledRuntimes(ICLRMetaHost* iface,
1002     IEnumUnknown **ppEnumerator)
1003 {
1004     struct InstalledRuntimeEnum *new_enum;
1005
1006     TRACE("%p\n", ppEnumerator);
1007
1008     find_runtimes();
1009
1010     new_enum = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_enum));
1011     if (!new_enum)
1012         return E_OUTOFMEMORY;
1013
1014     new_enum->Vtbl = &InstalledRuntimeEnum_Vtbl;
1015     new_enum->ref = 1;
1016     new_enum->pos = 0;
1017
1018     *ppEnumerator = (IEnumUnknown*)new_enum;
1019
1020     return S_OK;
1021 }
1022
1023 static HRESULT WINAPI CLRMetaHost_EnumerateLoadedRuntimes(ICLRMetaHost* iface,
1024     HANDLE hndProcess, IEnumUnknown **ppEnumerator)
1025 {
1026     FIXME("%p %p\n", hndProcess, ppEnumerator);
1027
1028     return E_NOTIMPL;
1029 }
1030
1031 static HRESULT WINAPI CLRMetaHost_RequestRuntimeLoadedNotification(ICLRMetaHost* iface,
1032     RuntimeLoadedCallbackFnPtr pCallbackFunction)
1033 {
1034     FIXME("%p\n", pCallbackFunction);
1035
1036     return E_NOTIMPL;
1037 }
1038
1039 static HRESULT WINAPI CLRMetaHost_QueryLegacyV2RuntimeBinding(ICLRMetaHost* iface,
1040     REFIID riid, LPVOID *ppUnk)
1041 {
1042     FIXME("%s %p\n", debugstr_guid(riid), ppUnk);
1043
1044     return E_NOTIMPL;
1045 }
1046
1047 static HRESULT WINAPI CLRMetaHost_ExitProcess(ICLRMetaHost* iface, INT32 iExitCode)
1048 {
1049     FIXME("%i: stub\n", iExitCode);
1050
1051     ExitProcess(iExitCode);
1052 }
1053
1054 static const struct ICLRMetaHostVtbl CLRMetaHost_vtbl =
1055 {
1056     CLRMetaHost_QueryInterface,
1057     CLRMetaHost_AddRef,
1058     CLRMetaHost_Release,
1059     CLRMetaHost_GetRuntime,
1060     CLRMetaHost_GetVersionFromFile,
1061     CLRMetaHost_EnumerateInstalledRuntimes,
1062     CLRMetaHost_EnumerateLoadedRuntimes,
1063     CLRMetaHost_RequestRuntimeLoadedNotification,
1064     CLRMetaHost_QueryLegacyV2RuntimeBinding,
1065     CLRMetaHost_ExitProcess
1066 };
1067
1068 static const struct CLRMetaHost GlobalCLRMetaHost = {
1069     &CLRMetaHost_vtbl
1070 };
1071
1072 extern HRESULT CLRMetaHost_CreateInstance(REFIID riid, void **ppobj)
1073 {
1074     return ICLRMetaHost_QueryInterface((ICLRMetaHost*)&GlobalCLRMetaHost, riid, ppobj);
1075 }
1076
1077 static MonoAssembly* mono_assembly_search_hook_fn(MonoAssemblyName *aname, char **assemblies_path, void *user_data)
1078 {
1079     loaded_mono *mono = user_data;
1080     HRESULT hr=S_OK;
1081     MonoAssembly *result=NULL;
1082     char *stringname=NULL;
1083     LPWSTR stringnameW;
1084     int stringnameW_size;
1085     IAssemblyCache *asmcache;
1086     ASSEMBLY_INFO info;
1087     WCHAR path[MAX_PATH];
1088     char *pathA;
1089     MonoImageOpenStatus stat;
1090     static WCHAR fusiondll[] = {'f','u','s','i','o','n',0};
1091     HMODULE hfusion=NULL;
1092     static HRESULT WINAPI (*pCreateAssemblyCache)(IAssemblyCache**,DWORD);
1093
1094     stringname = mono->mono_stringify_assembly_name(aname);
1095
1096     TRACE("%s\n", debugstr_a(stringname));
1097
1098     if (!stringname) return NULL;
1099
1100     /* FIXME: We should search the given paths before the GAC. */
1101
1102     if (!pCreateAssemblyCache)
1103     {
1104         hr = LoadLibraryShim(fusiondll, NULL, NULL, &hfusion);
1105
1106         if (SUCCEEDED(hr))
1107         {
1108             pCreateAssemblyCache = (void*)GetProcAddress(hfusion, "CreateAssemblyCache");
1109             if (!pCreateAssemblyCache)
1110                 hr = E_FAIL;
1111         }
1112     }
1113
1114     if (SUCCEEDED(hr))
1115         hr = pCreateAssemblyCache(&asmcache, 0);
1116
1117     if (SUCCEEDED(hr))
1118     {
1119         stringnameW_size = MultiByteToWideChar(CP_UTF8, 0, stringname, -1, NULL, 0);
1120
1121         stringnameW = HeapAlloc(GetProcessHeap(), 0, stringnameW_size * sizeof(WCHAR));
1122         if (stringnameW)
1123             MultiByteToWideChar(CP_UTF8, 0, stringname, -1, stringnameW, stringnameW_size);
1124         else
1125             hr = E_OUTOFMEMORY;
1126
1127         if (SUCCEEDED(hr))
1128         {
1129             info.cbAssemblyInfo = sizeof(info);
1130             info.pszCurrentAssemblyPathBuf = path;
1131             info.cchBuf = MAX_PATH;
1132             path[0] = 0;
1133
1134             hr = IAssemblyCache_QueryAssemblyInfo(asmcache, 0, stringnameW, &info);
1135         }
1136
1137         HeapFree(GetProcessHeap(), 0, stringnameW);
1138
1139         IAssemblyCache_Release(asmcache);
1140     }
1141
1142     if (SUCCEEDED(hr))
1143     {
1144         TRACE("found: %s\n", debugstr_w(path));
1145
1146         pathA = WtoA(path);
1147
1148         if (pathA)
1149         {
1150             result = mono->mono_assembly_open(pathA, &stat);
1151
1152             if (!result)
1153                 ERR("Failed to load %s, status=%u\n", debugstr_w(path), stat);
1154
1155             HeapFree(GetProcessHeap(), 0, pathA);
1156         }
1157     }
1158
1159     mono->mono_free(stringname);
1160
1161     return result;
1162 }
1163
1164 HRESULT get_runtime_info(LPCWSTR exefile, LPCWSTR version, LPCWSTR config_file,
1165     DWORD startup_flags, DWORD runtimeinfo_flags, BOOL legacy, ICLRRuntimeInfo **result)
1166 {
1167     static const WCHAR dotconfig[] = {'.','c','o','n','f','i','g',0};
1168     static const DWORD supported_startup_flags = 0;
1169     static const DWORD supported_runtime_flags = RUNTIME_INFO_UPGRADE_VERSION;
1170     int i;
1171     WCHAR local_version[MAX_PATH];
1172     ULONG local_version_size = MAX_PATH;
1173     WCHAR local_config_file[MAX_PATH];
1174     HRESULT hr;
1175     parsed_config_file parsed_config;
1176
1177     if (startup_flags & ~supported_startup_flags)
1178         FIXME("unsupported startup flags %x\n", startup_flags & ~supported_startup_flags);
1179
1180     if (runtimeinfo_flags & ~supported_runtime_flags)
1181         FIXME("unsupported runtimeinfo flags %x\n", runtimeinfo_flags & ~supported_runtime_flags);
1182
1183     if (exefile && !config_file)
1184     {
1185         strcpyW(local_config_file, exefile);
1186         strcatW(local_config_file, dotconfig);
1187
1188         config_file = local_config_file;
1189     }
1190
1191     if (config_file)
1192     {
1193         int found=0;
1194         hr = parse_config_file(config_file, &parsed_config);
1195
1196         if (SUCCEEDED(hr))
1197         {
1198             supported_runtime *entry;
1199             LIST_FOR_EACH_ENTRY(entry, &parsed_config.supported_runtimes, supported_runtime, entry)
1200             {
1201                 hr = CLRMetaHost_GetRuntime(0, entry->version, &IID_ICLRRuntimeInfo, (void**)result);
1202                 if (SUCCEEDED(hr))
1203                 {
1204                     found = 1;
1205                     break;
1206                 }
1207             }
1208         }
1209         else
1210         {
1211             WARN("failed to parse config file %s, hr=%x\n", debugstr_w(config_file), hr);
1212         }
1213
1214         free_parsed_config_file(&parsed_config);
1215
1216         if (found)
1217             return S_OK;
1218     }
1219
1220     if (exefile && !version)
1221     {
1222         hr = CLRMetaHost_GetVersionFromFile(0, exefile, local_version, &local_version_size);
1223
1224         version = local_version;
1225
1226         if (FAILED(hr)) return hr;
1227     }
1228
1229     if (version)
1230     {
1231         return CLRMetaHost_GetRuntime(0, version, &IID_ICLRRuntimeInfo, (void**)result);
1232     }
1233
1234     if (runtimeinfo_flags & RUNTIME_INFO_UPGRADE_VERSION)
1235     {
1236         find_runtimes();
1237
1238         if (legacy)
1239             i = 2;
1240         else
1241             i = NUM_RUNTIMES;
1242
1243         while (i--)
1244         {
1245             if (runtimes[i].mono_abi_version)
1246                 return IUnknown_QueryInterface((IUnknown*)&runtimes[i],
1247                     &IID_ICLRRuntimeInfo, (void**)result);
1248         }
1249
1250         ERR("No %s.NET runtime installed\n", legacy ? "legacy " : "");
1251
1252         return CLR_E_SHIM_RUNTIME;
1253     }
1254
1255     return CLR_E_SHIM_RUNTIME;
1256 }
1257
1258 HRESULT force_get_runtime_info(ICLRRuntimeInfo **result)
1259 {
1260     return IUnknown_QueryInterface((IUnknown*)&runtimes[0], &IID_ICLRRuntimeInfo, (void**)result);
1261 }