1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 #include <malloc.h>
25 #include <sal/alloca.h>
26 
27 #include <com/sun/star/uno/genfunc.hxx>
28 #include "com/sun/star/uno/RuntimeException.hpp"
29 #include <uno/data.h>
30 
31 #include "bridges/cpp_uno/shared/bridge.hxx"
32 #include "bridges/cpp_uno/shared/types.hxx"
33 #include "bridges/cpp_uno/shared/unointerfaceproxy.hxx"
34 #include "bridges/cpp_uno/shared/vtables.hxx"
35 
36 #include "share.hxx"
37 
38 using namespace ::rtl;
39 using namespace ::com::sun::star::uno;
40 
41 namespace
42 {
43 
44 //==================================================================================================
45 // The call instruction within the asm section of callVirtualMethod may throw
46 // exceptions.  So that the compiler handles this correctly, it is important
47 // that (a) callVirtualMethod might call dummy_can_throw_anything (although this
48 // never happens at runtime), which in turn can throw exceptions, and (b)
49 // callVirtualMethod is not inlined at its call site (so that any exceptions are
50 // caught which are thrown from the instruction calling callVirtualMethod):
51 static void callVirtualMethod(
52     void * pAdjustedThisPtr,
53     sal_Int32 nVtableIndex,
54     void * pRegisterReturn,
55     typelib_TypeClass eReturnType,
56     sal_Int32 * pStackLongs,
57     sal_Int32 nStackLongs );
58 // __attribute__((noinline));
59 
60 //==================================================================================================
61 static void callVirtualMethod(
62     void * pAdjustedThisPtr,
63     sal_Int32 nVtableIndex,
64     void * pRegisterReturn,
65     typelib_TypeClass eReturnType,
66     sal_Int32 * pStackLongs,
67     sal_Int32 nStackLongs )
68 {
69 	// parameter list is mixed list of * and values
70 	// reference parameters are pointers
71 
72 	OSL_ENSURE( pStackLongs && pAdjustedThisPtr, "### null ptr!" );
73 	OSL_ENSURE( (sizeof(void *) == 4) && (sizeof(sal_Int32) == 4), "### unexpected size of int!" );
74 	OSL_ENSURE( nStackLongs && pStackLongs, "### no stack in callVirtualMethod !" );
75 
76     // never called
77     if (! pAdjustedThisPtr) CPPU_CURRENT_NAMESPACE::dummy_can_throw_anything("xxx"); // address something
78 
79      /* figure out the address of the function we need to invoke */
80      unsigned long * mfunc;        // actual function to be invoked
81      int off;                      // offset used to find function
82      void (*ptr)();
83      off = nVtableIndex;
84      off = off * 4;                         // 4 bytes per slot
85      mfunc = *((unsigned long **)pAdjustedThisPtr);    // get the address of the vtable
86      mfunc = (unsigned long *)((char *)mfunc + off); // get the address from the vtable entry at offset
87      mfunc = *((unsigned long **)mfunc);                 // the function is stored at the address
88      ptr = (void (*)())mfunc;
89 
90 	volatile long edx = 0, eax = 0; // for register returns
91     void * stackptr;
92 	asm volatile (
93         "mov   %%esp, %6\n\t"
94 		// copy values
95 		"mov   %0, %%eax\n\t"
96 		"mov   %%eax, %%edx\n\t"
97 		"dec   %%edx\n\t"
98 		"shl   $2, %%edx\n\t"
99 		"add   %1, %%edx\n"
100 		"Lcopy:\n\t"
101 		"pushl 0(%%edx)\n\t"
102 		"sub   $4, %%edx\n\t"
103 		"dec   %%eax\n\t"
104 		"jne   Lcopy\n\t"
105 	:
106         : "m"(nStackLongs), "m"(pStackLongs), "m"(pAdjustedThisPtr),
107           "m"(nVtableIndex), "m"(eax), "m"(edx), "m"(stackptr)
108         : "eax", "edx" );
109 
110 	(*ptr)();
111 
112 	asm volatile (
113 		// save return registers
114  		"mov   %%eax, %4\n\t"
115  		"mov   %%edx, %5\n\t"
116 		// cleanup stack
117         "mov   %6, %%esp\n\t"
118 		:
119         : "m"(nStackLongs), "m"(pStackLongs), "m"(pAdjustedThisPtr),
120           "m"(nVtableIndex), "m"(eax), "m"(edx), "m"(stackptr)
121         : "eax", "edx" );
122 	switch( eReturnType )
123 	{
124 		case typelib_TypeClass_HYPER:
125 		case typelib_TypeClass_UNSIGNED_HYPER:
126 			((long*)pRegisterReturn)[1] = edx;
127 		case typelib_TypeClass_LONG:
128 		case typelib_TypeClass_UNSIGNED_LONG:
129 		case typelib_TypeClass_CHAR:
130 		case typelib_TypeClass_ENUM:
131 			((long*)pRegisterReturn)[0] = eax;
132 			break;
133 		case typelib_TypeClass_SHORT:
134 		case typelib_TypeClass_UNSIGNED_SHORT:
135 			*(unsigned short*)pRegisterReturn = eax;
136 			break;
137 		case typelib_TypeClass_BOOLEAN:
138 		case typelib_TypeClass_BYTE:
139 			*(unsigned char*)pRegisterReturn = eax;
140 			break;
141 		case typelib_TypeClass_FLOAT:
142 			asm ( "fstps %0" : : "m"(*(char *)pRegisterReturn) );
143 			break;
144 		case typelib_TypeClass_DOUBLE:
145 			asm ( "fstpl %0\n\t" : : "m"(*(char *)pRegisterReturn) );
146 			break;
147 	}
148 }
149 
150 //==================================================================================================
151 static void cpp_call(
152 	bridges::cpp_uno::shared::UnoInterfaceProxy * pThis,
153     bridges::cpp_uno::shared::VtableSlot aVtableSlot,
154 	typelib_TypeDescriptionReference * pReturnTypeRef,
155 	sal_Int32 nParams, typelib_MethodParameter * pParams,
156 	void * pUnoReturn, void * pUnoArgs[], uno_Any ** ppUnoExc )
157 {
158   	// max space for: [complex ret ptr], values|ptr ...
159   	char * pCppStack		=
160   		(char *)alloca( sizeof(sal_Int32) + ((nParams+2) * sizeof(sal_Int64)) );
161   	char * pCppStackStart	= pCppStack;
162 
163 	// return
164 	typelib_TypeDescription * pReturnTypeDescr = 0;
165 	TYPELIB_DANGER_GET( &pReturnTypeDescr, pReturnTypeRef );
166 	OSL_ENSURE( pReturnTypeDescr, "### expected return type description!" );
167 
168 	void * pCppReturn = 0; // if != 0 && != pUnoReturn, needs reconversion
169 
170 	if (pReturnTypeDescr)
171 	{
172 		if (bridges::cpp_uno::shared::isSimpleType( pReturnTypeDescr ))
173 		{
174 			pCppReturn = pUnoReturn; // direct way for simple types
175 		}
176 		else
177 		{
178 			// complex return via ptr
179 			pCppReturn = *(void **)pCppStack
180                 = (bridges::cpp_uno::shared::relatesToInterfaceType(
181                        pReturnTypeDescr )
182                    ? alloca( pReturnTypeDescr->nSize )
183                    : pUnoReturn); // direct way
184 			pCppStack += sizeof(void *);
185 		}
186 	}
187 	// push this
188     void * pAdjustedThisPtr = reinterpret_cast< void ** >(pThis->getCppI())
189         + aVtableSlot.offset;
190 	*(void**)pCppStack = pAdjustedThisPtr;
191 	pCppStack += sizeof( void* );
192 
193 	// stack space
194 	OSL_ENSURE( sizeof(void *) == sizeof(sal_Int32), "### unexpected size!" );
195 	// args
196 	void ** pCppArgs  = (void **)alloca( 3 * sizeof(void *) * nParams );
197 	// indizes of values this have to be converted (interface conversion cpp<=>uno)
198 	sal_Int32 * pTempIndizes = (sal_Int32 *)(pCppArgs + nParams);
199 	// type descriptions for reconversions
200 	typelib_TypeDescription ** ppTempParamTypeDescr = (typelib_TypeDescription **)(pCppArgs + (2 * nParams));
201 
202 	sal_Int32 nTempIndizes   = 0;
203 
204 	for ( sal_Int32 nPos = 0; nPos < nParams; ++nPos )
205 	{
206 		const typelib_MethodParameter & rParam = pParams[nPos];
207 		typelib_TypeDescription * pParamTypeDescr = 0;
208 		TYPELIB_DANGER_GET( &pParamTypeDescr, rParam.pTypeRef );
209 
210 		if (!rParam.bOut
211             && bridges::cpp_uno::shared::isSimpleType( pParamTypeDescr ))
212 		{
213 			uno_copyAndConvertData( pCppArgs[nPos] = pCppStack, pUnoArgs[nPos], pParamTypeDescr,
214 									pThis->getBridge()->getUno2Cpp() );
215 
216 			switch (pParamTypeDescr->eTypeClass)
217 			{
218 			case typelib_TypeClass_HYPER:
219 			case typelib_TypeClass_UNSIGNED_HYPER:
220 			case typelib_TypeClass_DOUBLE:
221 				pCppStack += sizeof(sal_Int32); // extra long
222 			}
223 			// no longer needed
224 			TYPELIB_DANGER_RELEASE( pParamTypeDescr );
225 		}
226 		else // ptr to complex value | ref
227 		{
228 			if (! rParam.bIn) // is pure out
229 			{
230 				// cpp out is constructed mem, uno out is not!
231 				uno_constructData(
232 					*(void **)pCppStack = pCppArgs[nPos] = alloca( pParamTypeDescr->nSize ),
233 					pParamTypeDescr );
234 				pTempIndizes[nTempIndizes] = nPos; // default constructed for cpp call
235 				// will be released at reconversion
236 				ppTempParamTypeDescr[nTempIndizes++] = pParamTypeDescr;
237 			}
238 			// is in/inout
239 			else if (bridges::cpp_uno::shared::relatesToInterfaceType(
240                          pParamTypeDescr ))
241 			{
242 				uno_copyAndConvertData(
243 					*(void **)pCppStack = pCppArgs[nPos] = alloca( pParamTypeDescr->nSize ),
244 					pUnoArgs[nPos], pParamTypeDescr,
245                     pThis->getBridge()->getUno2Cpp() );
246 
247 				pTempIndizes[nTempIndizes] = nPos; // has to be reconverted
248 				// will be released at reconversion
249 				ppTempParamTypeDescr[nTempIndizes++] = pParamTypeDescr;
250 			}
251 			else // direct way
252 			{
253 				*(void **)pCppStack = pCppArgs[nPos] = pUnoArgs[nPos];
254 				// no longer needed
255 				TYPELIB_DANGER_RELEASE( pParamTypeDescr );
256 			}
257 		}
258 		pCppStack += sizeof(sal_Int32); // standard parameter length
259 	}
260 
261 	try
262 	{
263 		OSL_ENSURE( !( (pCppStack - pCppStackStart ) & 3), "UNALIGNED STACK !!! (Please DO panic)" );
264 		callVirtualMethod(
265 			pAdjustedThisPtr, aVtableSlot.index,
266 			pCppReturn, pReturnTypeDescr->eTypeClass,
267 			(sal_Int32 *)pCppStackStart, (pCppStack - pCppStackStart) / sizeof(sal_Int32) );
268 		// NO exception occured...
269 		*ppUnoExc = 0;
270 
271 		// reconvert temporary params
272 		for ( ; nTempIndizes--; )
273 		{
274 			sal_Int32 nIndex = pTempIndizes[nTempIndizes];
275 			typelib_TypeDescription * pParamTypeDescr = ppTempParamTypeDescr[nTempIndizes];
276 
277 			if (pParams[nIndex].bIn)
278 			{
279 				if (pParams[nIndex].bOut) // inout
280 				{
281 					uno_destructData( pUnoArgs[nIndex], pParamTypeDescr, 0 ); // destroy uno value
282 					uno_copyAndConvertData( pUnoArgs[nIndex], pCppArgs[nIndex], pParamTypeDescr,
283 											pThis->getBridge()->getCpp2Uno() );
284 				}
285 			}
286 			else // pure out
287 			{
288 				uno_copyAndConvertData( pUnoArgs[nIndex], pCppArgs[nIndex], pParamTypeDescr,
289 										pThis->getBridge()->getCpp2Uno() );
290 			}
291 			// destroy temp cpp param => cpp: every param was constructed
292 			uno_destructData( pCppArgs[nIndex], pParamTypeDescr, cpp_release );
293 
294 			TYPELIB_DANGER_RELEASE( pParamTypeDescr );
295 		}
296 		// return value
297 		if (pCppReturn && pUnoReturn != pCppReturn)
298 		{
299 			uno_copyAndConvertData( pUnoReturn, pCppReturn, pReturnTypeDescr,
300 									pThis->getBridge()->getCpp2Uno() );
301 			uno_destructData( pCppReturn, pReturnTypeDescr, cpp_release );
302 		}
303 	}
304  	catch (...)
305  	{
306   		// fill uno exception
307 		fillUnoException( CPPU_CURRENT_NAMESPACE::__cxa_get_globals()->caughtExceptions, *ppUnoExc, pThis->getBridge()->getCpp2Uno() );
308 
309 		// temporary params
310 		for ( ; nTempIndizes--; )
311 		{
312 			sal_Int32 nIndex = pTempIndizes[nTempIndizes];
313 			// destroy temp cpp param => cpp: every param was constructed
314 			uno_destructData( pCppArgs[nIndex], ppTempParamTypeDescr[nTempIndizes], cpp_release );
315 			TYPELIB_DANGER_RELEASE( ppTempParamTypeDescr[nTempIndizes] );
316 		}
317 		// return type
318 		if (pReturnTypeDescr)
319 			TYPELIB_DANGER_RELEASE( pReturnTypeDescr );
320 	}
321 }
322 
323 }
324 
325 namespace bridges { namespace cpp_uno { namespace shared {
326 
327 void unoInterfaceProxyDispatch(
328 	uno_Interface * pUnoI, const typelib_TypeDescription * pMemberDescr,
329     void * pReturn, void * pArgs[], uno_Any ** ppException )
330 {
331 	// is my surrogate
332 	bridges::cpp_uno::shared::UnoInterfaceProxy * pThis
333         = static_cast< bridges::cpp_uno::shared::UnoInterfaceProxy * >(pUnoI);
334 	typelib_InterfaceTypeDescription * pTypeDescr = pThis->pTypeDescr;
335 
336 	switch (pMemberDescr->eTypeClass)
337 	{
338 	case typelib_TypeClass_INTERFACE_ATTRIBUTE:
339 	{
340         VtableSlot aVtableSlot(
341             getVtableSlot(
342                 reinterpret_cast<
343                     typelib_InterfaceAttributeTypeDescription const * >(
344                         pMemberDescr)));
345 		if (pReturn)
346 		{
347 			// dependent dispatch
348 			cpp_call(
349 				pThis, aVtableSlot,
350 				((typelib_InterfaceAttributeTypeDescription *)pMemberDescr)->pAttributeTypeRef,
351 				0, 0, // no params
352 				pReturn, pArgs, ppException );
353 		}
354 		else
355 		{
356 			// is SET
357 			typelib_MethodParameter aParam;
358 			aParam.pTypeRef =
359 				((typelib_InterfaceAttributeTypeDescription *)pMemberDescr)->pAttributeTypeRef;
360 			aParam.bIn		= sal_True;
361 			aParam.bOut		= sal_False;
362 
363 			typelib_TypeDescriptionReference * pReturnTypeRef = 0;
364 			OUString aVoidName( RTL_CONSTASCII_USTRINGPARAM("void") );
365 			typelib_typedescriptionreference_new(
366 				&pReturnTypeRef, typelib_TypeClass_VOID, aVoidName.pData );
367 
368 			// dependent dispatch
369             aVtableSlot.index += 1; // get, then set method
370 			cpp_call(
371 				pThis, aVtableSlot,
372 				pReturnTypeRef,
373 				1, &aParam,
374 				pReturn, pArgs, ppException );
375 
376 			typelib_typedescriptionreference_release( pReturnTypeRef );
377 		}
378 
379 		break;
380 	}
381 	case typelib_TypeClass_INTERFACE_METHOD:
382 	{
383         VtableSlot aVtableSlot(
384             getVtableSlot(
385                 reinterpret_cast<
386                     typelib_InterfaceMethodTypeDescription const * >(
387                         pMemberDescr)));
388 		switch (aVtableSlot.index)
389 		{
390 			// standard calls
391 		case 1: // acquire uno interface
392 			(*pUnoI->acquire)( pUnoI );
393 			*ppException = 0;
394 			break;
395 		case 2: // release uno interface
396 			(*pUnoI->release)( pUnoI );
397 			*ppException = 0;
398 			break;
399 		case 0: // queryInterface() opt
400 		{
401 			typelib_TypeDescription * pTD = 0;
402 			TYPELIB_DANGER_GET( &pTD, reinterpret_cast< Type * >( pArgs[0] )->getTypeLibType() );
403 			if (pTD)
404 			{
405                 uno_Interface * pInterface = 0;
406                 (*pThis->pBridge->getUnoEnv()->getRegisteredInterface)(
407                     pThis->pBridge->getUnoEnv(),
408                     (void **)&pInterface, pThis->oid.pData, (typelib_InterfaceTypeDescription *)pTD );
409 
410                 if (pInterface)
411                 {
412                     ::uno_any_construct(
413                         reinterpret_cast< uno_Any * >( pReturn ),
414                         &pInterface, pTD, 0 );
415                     (*pInterface->release)( pInterface );
416                     TYPELIB_DANGER_RELEASE( pTD );
417                     *ppException = 0;
418                     break;
419                 }
420                 TYPELIB_DANGER_RELEASE( pTD );
421             }
422 		} // else perform queryInterface()
423 		default:
424 			// dependent dispatch
425 			cpp_call(
426 				pThis, aVtableSlot,
427 				((typelib_InterfaceMethodTypeDescription *)pMemberDescr)->pReturnTypeRef,
428 				((typelib_InterfaceMethodTypeDescription *)pMemberDescr)->nParams,
429 				((typelib_InterfaceMethodTypeDescription *)pMemberDescr)->pParams,
430 				pReturn, pArgs, ppException );
431 		}
432 		break;
433 	}
434 	default:
435 	{
436 		::com::sun::star::uno::RuntimeException aExc(
437 			OUString( RTL_CONSTASCII_USTRINGPARAM("illegal member type description!") ),
438 			::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() );
439 
440 		Type const & rExcType = ::getCppuType( &aExc );
441 		// binary identical null reference
442 		::uno_type_any_construct( *ppException, &aExc, rExcType.getTypeLibType(), 0 );
443 	}
444 	}
445 }
446 
447 } } }
448