xref: /PHP-8.1/ext/com_dotnet/com_dotnet.c (revision 01b3fc03)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: Wez Furlong  <wez@thebrainroom.com>                          |
14    +----------------------------------------------------------------------+
15  */
16 
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20 
21 #include "php.h"
22 
23 #if HAVE_MSCOREE_H
24 # include "php_ini.h"
25 # include "ext/standard/info.h"
26 # include "php_com_dotnet.h"
27 # include "php_com_dotnet_internal.h"
28 # include "Zend/zend_exceptions.h"
29 # include <mscoree.h>
30 
31 /* Since there is no official public mscorlib.h header file, and since
32  * generating your own version from the elusive binary .tlb file takes a lot of
33  * hacking and results in a 3MB header file (!), we opt for this slightly
34  * voodoo approach.  The following is just enough definition to be able to
35  * reach the _AppDomain::CreateInstance method that we need to use to be able
36  * to fire up .Net objects.  We used to use IDispatch for this, but it would
37  * not always work.
38  *
39  * The following info was obtained using OleView to export the IDL from
40  * mscorlib.tlb.  Note that OleView is unable to generate C headers for this
41  * particular tlb... hence this mess.
42  */
43 
44 const GUID IID_mscorlib_System_AppDomain = {
45 0x05F696DC, 0x2B29, 0x3663, {0xAD, 0x8B, 0xC4, 0x38, 0x9C, 0xF2, 0xA7, 0x13 }};
46 
47 typedef struct _Imscorlib_System_AppDomain IAppDomain;
48 
49 struct _Imscorlib_System_AppDomainVtbl {
50 	BEGIN_INTERFACE
51 
52 	HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
53 		IAppDomain * This,
54 		/* [in] */ REFIID riid,
55 		/* [iid_is][out] */ void **ppvObject);
56 
57 	ULONG ( STDMETHODCALLTYPE *AddRef )(
58 		IAppDomain * This);
59 
60 	ULONG ( STDMETHODCALLTYPE *Release )(
61 		IAppDomain * This);
62 
63 	/* this is padding to get CreateInstance into the correct position */
64 #define DUMMY_METHOD(x)		HRESULT ( STDMETHODCALLTYPE *dummy_##x )(IAppDomain *This)
65 
66 	DUMMY_METHOD(GetTypeInfoCount);
67 	DUMMY_METHOD(GetTypeInfo);
68 	DUMMY_METHOD(GetIDsOfNames);
69 	DUMMY_METHOD(Invoke);
70 	DUMMY_METHOD(ToString);
71 	DUMMY_METHOD(Equals);
72 	DUMMY_METHOD(GetHashCode);
73 	DUMMY_METHOD(GetType);
74 	DUMMY_METHOD(InitializeLifetimeService);
75 	DUMMY_METHOD(GetLifetimeService);
76 	DUMMY_METHOD(Evidence);
77 	DUMMY_METHOD(add_DomainUnload);
78 	DUMMY_METHOD(remove_DomainUnload);
79 	DUMMY_METHOD(add_AssemblyLoad);
80 	DUMMY_METHOD(remove_AssemblyLoad);
81 	DUMMY_METHOD(add_ProcessExit);
82 	DUMMY_METHOD(remove_ProcessExit);
83 	DUMMY_METHOD(add_TypeResolve);
84 	DUMMY_METHOD(remove_TypeResolve);
85 	DUMMY_METHOD(add_ResourceResolve);
86 	DUMMY_METHOD(remove_ResourceResolve);
87 	DUMMY_METHOD(add_AssemblyResolve);
88 	DUMMY_METHOD(remove_AssemblyResolve);
89 	DUMMY_METHOD(add_UnhandledException);
90 	DUMMY_METHOD(remove_UnhandledException);
91 	DUMMY_METHOD(DefineDynamicAssembly);
92 	DUMMY_METHOD(DefineDynamicAssembly_2);
93 	DUMMY_METHOD(DefineDynamicAssembly_3);
94 	DUMMY_METHOD(DefineDynamicAssembly_4);
95 	DUMMY_METHOD(DefineDynamicAssembly_5);
96 	DUMMY_METHOD(DefineDynamicAssembly_6);
97 	DUMMY_METHOD(DefineDynamicAssembly_7);
98 	DUMMY_METHOD(DefineDynamicAssembly_8);
99 	DUMMY_METHOD(DefineDynamicAssembly_9);
100 
101 	HRESULT ( STDMETHODCALLTYPE *CreateInstance )(IAppDomain * This, BSTR AssemblyName, BSTR typeName, IUnknown **pRetVal);
102 	HRESULT ( STDMETHODCALLTYPE *CreateInstanceFrom )(IAppDomain * This, BSTR AssemblyFile, BSTR typeName, IUnknown **pRetVal);
103 
104 	/* more methods live here */
105 
106 	END_INTERFACE
107 };
108 
109 struct _Imscorlib_System_AppDomain {
110 	struct _Imscorlib_System_AppDomainVtbl *lpVtbl;
111 };
112 
113 
114 struct dotnet_runtime_stuff {
115 	ICorRuntimeHost *dotnet_host;
116 	IAppDomain 		*dotnet_domain;
117 	DISPID create_instance;
118 };
119 
120 /* We link dynamically to mscoree.dll to avoid the hard dependency on .NET
121  * framework, which is only required if a dotnet instance is to be created.
122  */
dotnet_bind_runtime(LPVOID FAR * ppv)123 static HRESULT dotnet_bind_runtime(LPVOID FAR *ppv)
124 {
125 	HRESULT hr;
126 	HMODULE mscoree;
127 	typedef HRESULT (STDAPICALLTYPE *cbtr_t)(LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor, REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
128 	cbtr_t CorBindToRuntime;
129 	OLECHAR *oleversion;
130 	char *version;
131 
132 	mscoree = LoadLibraryA("mscoree.dll");
133 	if (mscoree == NULL) {
134 		return S_FALSE;
135 	}
136 
137 	CorBindToRuntime = (cbtr_t) GetProcAddress(mscoree, "CorBindToRuntime");
138 	if (CorBindToRuntime == NULL) {
139 		FreeLibrary(mscoree);
140 		return S_FALSE;
141 	}
142 
143 	version = INI_STR("com.dotnet_version");
144 	if (version == NULL || *version == '\0') {
145 		oleversion = NULL;
146 	} else {
147 		oleversion = php_com_string_to_olestring(version, strlen(version), COMG(code_page));
148 	}
149 
150 	hr = CorBindToRuntime(oleversion, NULL, &CLSID_CorRuntimeHost, &IID_ICorRuntimeHost, ppv);
151 
152 	efree(oleversion);
153 	FreeLibrary(mscoree);
154 
155 	return hr;
156 }
157 
dotnet_init(char ** p_where)158 static HRESULT dotnet_init(char **p_where)
159 {
160 	HRESULT hr;
161 	struct dotnet_runtime_stuff *stuff;
162 	IUnknown *unk = NULL;
163 	char *where = "";
164 
165 	stuff = malloc(sizeof(*stuff));
166 	if (!stuff) {
167 		return S_FALSE;
168 	}
169 	memset(stuff, 0, sizeof(*stuff));
170 
171 	where = "dotnet_bind_runtime";
172 	hr = dotnet_bind_runtime((LPVOID*)&stuff->dotnet_host);
173 	if (FAILED(hr))
174 		goto out;
175 
176 	/* fire up the host and get the domain object */
177 	where = "ICorRuntimeHost_Start\n";
178 	hr = ICorRuntimeHost_Start(stuff->dotnet_host);
179 	if (FAILED(hr))
180 		goto out;
181 
182 	where = "ICorRuntimeHost_GetDefaultDomain";
183 	hr = ICorRuntimeHost_GetDefaultDomain(stuff->dotnet_host, &unk);
184 	if (FAILED(hr))
185 		goto out;
186 
187 	where = "QI: System._AppDomain";
188 	hr = IUnknown_QueryInterface(unk, &IID_mscorlib_System_AppDomain, (LPVOID*)&stuff->dotnet_domain);
189 	if (FAILED(hr))
190 		goto out;
191 
192 	COMG(dotnet_runtime_stuff) = stuff;
193 
194 out:
195 	if (unk) {
196 		IUnknown_Release(unk);
197 	}
198 	if (COMG(dotnet_runtime_stuff) == NULL) {
199 		/* clean up */
200 		if (stuff->dotnet_domain) {
201 			IUnknown_Release(stuff->dotnet_domain);
202 		}
203 		if (stuff->dotnet_host) {
204 			ICorRuntimeHost_Stop(stuff->dotnet_host);
205 			ICorRuntimeHost_Release(stuff->dotnet_host);
206 		}
207 		free(stuff);
208 
209 		*p_where = where;
210 
211 		return hr;
212 	}
213 
214 	return S_OK;
215 }
216 
217 /* {{{ com_dotnet_create_instance - ctor for DOTNET class */
PHP_METHOD(dotnet,__construct)218 PHP_METHOD(dotnet, __construct)
219 {
220 	zval *object = getThis();
221 	php_com_dotnet_object *obj;
222 	char *assembly_name, *datatype_name;
223 	size_t assembly_name_len, datatype_name_len;
224 	struct dotnet_runtime_stuff *stuff;
225 	OLECHAR *oleassembly, *oletype;
226 	BSTR oleassembly_sys, oletype_sys;
227 	HRESULT hr;
228 	int ret = FAILURE;
229 	char *where = "";
230 	IUnknown *unk = NULL;
231 	zend_long cp = GetACP();
232 	const struct php_win32_cp *cp_it;
233 
234 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l",
235 			&assembly_name, &assembly_name_len,
236 			&datatype_name, &datatype_name_len,
237 			&cp)) {
238 		RETURN_THROWS();
239 	}
240 
241 	php_com_initialize();
242 	stuff = (struct dotnet_runtime_stuff*)COMG(dotnet_runtime_stuff);
243 	if (stuff == NULL) {
244 		hr = dotnet_init(&where);
245 		if (FAILED(hr)) {
246 			char buf[1024];
247 			char *err = php_win32_error_to_msg(hr);
248 			snprintf(buf, sizeof(buf), "Failed to init .Net runtime [%s] %s", where, err);
249 			php_win32_error_msg_free(err);
250 			php_com_throw_exception(hr, buf);
251 			RETURN_THROWS();
252 		}
253 		stuff = (struct dotnet_runtime_stuff*)COMG(dotnet_runtime_stuff);
254 
255 	} else if (stuff->dotnet_domain == NULL) {
256 		where = "ICorRuntimeHost_GetDefaultDomain";
257 		hr = ICorRuntimeHost_GetDefaultDomain(stuff->dotnet_host, &unk);
258 		if (FAILED(hr)) {
259 			char buf[1024];
260 			char *err = php_win32_error_to_msg(hr);
261 			snprintf(buf, sizeof(buf), "Failed to re-init .Net domain [%s] %s", where, err);
262 			php_win32_error_msg_free(err);
263 			php_com_throw_exception(hr, buf);
264 			ZVAL_NULL(object);
265 			RETURN_THROWS();
266 		}
267 
268 		where = "QI: System._AppDomain";
269 		hr = IUnknown_QueryInterface(unk, &IID_mscorlib_System_AppDomain, (LPVOID*)&stuff->dotnet_domain);
270 		if (FAILED(hr)) {
271 			char buf[1024];
272 			char *err = php_win32_error_to_msg(hr);
273 			snprintf(buf, sizeof(buf), "Failed to re-init .Net domain [%s] %s", where, err);
274 			php_win32_error_msg_free(err);
275 			php_com_throw_exception(hr, buf);
276 			ZVAL_NULL(object);
277 			RETURN_THROWS();
278 		}
279 	}
280 
281 	obj = CDNO_FETCH(object);
282 
283 	cp_it = php_win32_cp_get_by_id((DWORD)cp);
284 	if (!cp_it) {
285 		php_com_throw_exception(E_INVALIDARG, "Could not create .Net object - invalid codepage!");
286 		RETURN_THROWS();
287 	}
288 	obj->code_page = (int)cp_it->id;
289 
290 	oletype = php_com_string_to_olestring(datatype_name, datatype_name_len, obj->code_page);
291 	oleassembly = php_com_string_to_olestring(assembly_name, assembly_name_len, obj->code_page);
292 	oletype_sys = SysAllocString(oletype);
293 	oleassembly_sys = SysAllocString(oleassembly);
294 	where = "CreateInstance";
295 	hr = stuff->dotnet_domain->lpVtbl->CreateInstance(stuff->dotnet_domain, oleassembly_sys, oletype_sys, &unk);
296 	efree(oletype);
297 	efree(oleassembly);
298 	SysFreeString(oletype_sys);
299 	SysFreeString(oleassembly_sys);
300 
301 	if (SUCCEEDED(hr)) {
302 		VARIANT unwrapped;
303 		IObjectHandle *handle = NULL;
304 
305 		where = "QI: IObjectHandle";
306 		hr = IUnknown_QueryInterface(unk, &IID_IObjectHandle, &handle);
307 
308 		if (SUCCEEDED(hr)) {
309 			where = "IObjectHandle_Unwrap";
310 			hr = IObjectHandle_Unwrap(handle, &unwrapped);
311 			if (SUCCEEDED(hr)) {
312 
313 				if (V_VT(&unwrapped) == VT_UNKNOWN) {
314 					where = "Unwrapped, QI for IDispatch";
315 					hr = IUnknown_QueryInterface(V_UNKNOWN(&unwrapped), &IID_IDispatch, &V_DISPATCH(&obj->v));
316 
317 					if (SUCCEEDED(hr)) {
318 						V_VT(&obj->v) = VT_DISPATCH;
319 
320 						/* get its type-info */
321 						IDispatch_GetTypeInfo(V_DISPATCH(&obj->v), 0, LANG_NEUTRAL, &obj->typeinfo);
322 						ret = SUCCESS;
323 					}
324 				} else if (V_VT(&unwrapped) == VT_DISPATCH) {
325 					/* unwrapped is now the dispatch pointer we want */
326 					V_DISPATCH(&obj->v) = V_DISPATCH(&unwrapped);
327 					V_VT(&obj->v) = VT_DISPATCH;
328 
329 					/* get its type-info */
330 					IDispatch_GetTypeInfo(V_DISPATCH(&obj->v), 0, LANG_NEUTRAL, &obj->typeinfo);
331 
332 					ret = SUCCESS;
333 				} else {
334 					/* shouldn't happen, but let's be ready for it */
335 					VariantClear(&unwrapped);
336 					hr = E_INVALIDARG;
337 				}
338 			}
339 			IObjectHandle_Release(handle);
340 		}
341 		IUnknown_Release(unk);
342 	}
343 
344 	if (ret == FAILURE) {
345 		char buf[1024];
346 		char *err = php_win32_error_to_msg(hr);
347 		snprintf(buf, sizeof(buf), "Failed to instantiate .Net object [%s] [0x%08x] %s", where, hr, err);
348 		php_win32_error_msg_free(err);
349 		php_com_throw_exception(hr, buf);
350 		RETURN_THROWS();
351 	}
352 }
353 /* }}} */
354 
php_com_dotnet_mshutdown(void)355 void php_com_dotnet_mshutdown(void)
356 {
357 	struct dotnet_runtime_stuff *stuff = COMG(dotnet_runtime_stuff);
358 
359 	if (stuff->dotnet_domain) {
360 		IDispatch_Release(stuff->dotnet_domain);
361 	}
362 	if (stuff->dotnet_host) {
363 		ICorRuntimeHost_Stop(stuff->dotnet_host);
364 		ICorRuntimeHost_Release(stuff->dotnet_host);
365 		stuff->dotnet_host = NULL;
366 	}
367 	free(stuff);
368 	COMG(dotnet_runtime_stuff) = NULL;
369 }
370 
php_com_dotnet_rshutdown(void)371 void php_com_dotnet_rshutdown(void)
372 {
373 	struct dotnet_runtime_stuff *stuff = COMG(dotnet_runtime_stuff);
374 
375 	if (stuff->dotnet_domain) {
376 		IDispatch_Release(stuff->dotnet_domain);
377 		stuff->dotnet_domain = NULL;
378 	}
379 }
380 
381 #endif /* HAVE_MSCOREE_H */
382