engineFunctions.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _ENGINEFUNCTIONS_H_
  23. #define _ENGINEFUNCTIONS_H_
  24. #ifndef _ENGINEEXPORTS_H_
  25. #include "console/engineExports.h"
  26. #endif
  27. #ifndef _ENGINETYPEINFO_H_
  28. #include "console/engineTypeInfo.h"
  29. #endif
  30. /// @file
  31. /// Structures for function-type engine export information.
  32. #ifdef TORQUE_COMPILER_VISUALC
  33. #define TORQUE_API extern "C" __declspec( dllexport )
  34. #elif defined( TORQUE_COMPILER_GCC )
  35. #define TORQUE_API extern "C" __attribute__( ( visibility( "default" ) ) )
  36. #else
  37. #error Unsupported compiler.
  38. #endif
  39. // #pragma pack is bugged in GCC in that the packing in place at the template instantiation
  40. // sites rather than their definition sites is used. Enable workarounds.
  41. #ifdef TORQUE_COMPILER_GCC
  42. #define _PACK_BUG_WORKAROUNDS
  43. #endif
  44. /// Structure storing the default argument values for a function invocation
  45. /// frame.
  46. struct EngineFunctionDefaultArguments
  47. {
  48. /// Number of default arguments for the function call frame.
  49. ///
  50. /// @warn This is @b NOT the size of the memory block returned by getArgs() and also
  51. /// not the number of elements it contains.
  52. U32 mNumDefaultArgs;
  53. /// Return a pointer to the variable-sized array of default argument values.
  54. ///
  55. /// @warn The arguments must be stored @b IMMEDIATELY after #mNumDefaultArgs.
  56. /// @warn This is a @b FULL frame and not just the default arguments, i.e. it starts with the
  57. /// first argument that the function takes and ends with the last argument it takes.
  58. /// @warn If the compiler's #pragma pack is buggy, the elements in this structure are allowed
  59. /// to be 4-byte aligned rather than byte-aligned as they should be.
  60. const U8* getArgs() const
  61. {
  62. return ( const U8* ) &( mNumDefaultArgs ) + sizeof( mNumDefaultArgs );
  63. }
  64. };
  65. // Need byte-aligned packing for the default argument structures.
  66. #ifdef _WIN64
  67. #pragma pack( push, 4 )
  68. #else
  69. #pragma pack( push, 1 )
  70. #endif
  71. // Structure encapsulating default arguments to an engine API function.
  72. template< typename T >
  73. struct _EngineFunctionDefaultArguments {};
  74. template<typename ...ArgTs>
  75. struct _EngineFunctionDefaultArguments< void(ArgTs...) > : public EngineFunctionDefaultArguments
  76. {
  77. template<typename T> using DefVST = typename EngineTypeTraits<T>::DefaultArgumentValueStoreType;
  78. std::tuple<DefVST<ArgTs> ...> mArgs;
  79. private:
  80. using SelfType = _EngineFunctionDefaultArguments< void(ArgTs...) >;
  81. template<size_t ...> struct Seq {};
  82. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  83. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  84. template<typename ...TailTs, size_t ...I>
  85. void copyHelper(std::tuple<DefVST<TailTs> ...> defaultArgs, Seq<I...>) {
  86. constexpr size_t offset = (sizeof...(ArgTs) - sizeof...(TailTs));
  87. std::tie(std::get<I + offset>(mArgs)...) = defaultArgs;
  88. }
  89. template<typename ...TailTs> using MaybeVoidEnabled = typename std::enable_if<sizeof...(TailTs) <= sizeof...(ArgTs), void>::type;
  90. template<typename ...TailTs> MaybeVoidEnabled<TailTs...> tailInit(DefVST<TailTs> ...tail) {
  91. mNumDefaultArgs = sizeof...(TailTs);
  92. copyHelper(std::make_tuple(tail...), typename Gens<sizeof...(TailTs)>::type());
  93. };
  94. public:
  95. template<typename ...TailTs> _EngineFunctionDefaultArguments(DefVST<TailTs> ...tail)
  96. {
  97. tailInit(tail...);
  98. }
  99. };
  100. #pragma pack( pop )
  101. // Helper to allow flags argument to DEFINE_FUNCTION to be empty.
  102. struct _EngineFunctionFlags
  103. {
  104. U32 val;
  105. _EngineFunctionFlags()
  106. : val( 0 ) {}
  107. _EngineFunctionFlags( U32 val )
  108. : val( val ) {}
  109. operator U32() const { return val; }
  110. };
  111. ///
  112. enum EngineFunctionFlags
  113. {
  114. /// Function is a callback into the control layer. If this flag is not set,
  115. /// the function is a call-in.
  116. EngineFunctionCallout = BIT( 0 ),
  117. };
  118. /// A function exported by the engine for interfacing with the control layer.
  119. ///
  120. /// A function can either be a call-in, transfering control flow from the control layer to the engine, or a call-out,
  121. /// transfering control flow from the engine to the control layer.
  122. ///
  123. /// All engine API functions use the native C (@c cdecl) calling convention.
  124. ///
  125. /// Be aware that there a no implicit parameters to functions. This, for example, means that methods will simply
  126. /// list an object type parameter as their first argument but otherwise be indistinguishable from other functions.
  127. ///
  128. /// Variadic functions are supported.
  129. ///
  130. /// @section engineFunction_strings String Arguments and Return Values
  131. ///
  132. /// Strings passed through the API are assumed to be owned by the caller. They must persist for the entire duration
  133. /// of a call.
  134. ///
  135. /// Strings returned by a function are assumed to be in transient storage that will be overwritten by subsequent API
  136. /// calls. If the caller wants to preserve a string, it is responsible to copying strings to its own memory. This will
  137. /// happen with most higher-level control layers anyway.
  138. ///
  139. /// @section engineFunction_defaultargs Default Arguments
  140. ///
  141. /// As the engine API export system is set up to not require hand-written code in generated wrappers per se, the
  142. /// export system seeks to include a maximum possible amount of information in the export structures.
  143. /// To this end, where applicable, information about suggested default values for arguments to the engine API
  144. /// functions is stored in the export structures. It is up to the wrapper generator if and how it makes use of
  145. /// this information.
  146. ///
  147. /// Default arguments are represented by capturing raw stack frame vectors of the arguments to functions. These
  148. /// frames could be used as default images for passing arguments in stack frames, though wrapper generators
  149. /// may actually want to read out individual argument values and include them in function prototypes within
  150. /// the generated code.
  151. ///
  152. /// @section engineFunction_callin Call-ins
  153. ///
  154. /// Call-ins are exposed as native entry points. The control layer must be able to natively
  155. /// marshall arguments and call DLL function exports using C calling conventions.
  156. ///
  157. /// @section engineFunction_callout Call-outs
  158. ///
  159. /// Call-outs are exposed as pointer-sized memory locations into which the control layer needs
  160. /// to install addresses of functions that receive the call from the engine back into the control
  161. /// layer. The function has to follow C calling conventions and
  162. ///
  163. /// A call-out will initially be set to NULL and while being NULL, will simply cause the engine
  164. /// to skip and ignore the call-out. This allows the control layer to only install call-outs
  165. /// it is actually interested in.
  166. ///
  167. class EngineFunctionInfo : public EngineExport
  168. {
  169. public:
  170. DECLARE_CLASS( EngineFunctionInfo, EngineExport );
  171. protected:
  172. /// A combination of EngineFunctionFlags.
  173. BitSet32 mFunctionFlags;
  174. /// The type of the function.
  175. const EngineTypeInfo* mFunctionType;
  176. /// Default values for the function arguments.
  177. const EngineFunctionDefaultArguments* mDefaultArgumentValues;
  178. /// Name of the DLL symbol denoting the address of the exported entity.
  179. const char* mBindingName;
  180. /// Full function prototype string. Useful for quick printing and most importantly,
  181. /// this will be the only place containing information about the argument names.
  182. const char* mPrototypeString;
  183. /// Address of either the function implementation or the variable taking the address
  184. /// of a call-out.
  185. void* mAddress;
  186. /// Next function in the global link chain of engine functions.
  187. EngineFunctionInfo* mNextFunction;
  188. /// First function in the global link chain of engine functions.
  189. static EngineFunctionInfo* smFirstFunction;
  190. public:
  191. ///
  192. EngineFunctionInfo( const char* name,
  193. EngineExportScope* scope,
  194. const char* docString,
  195. const char* protoypeString,
  196. const char* bindingName,
  197. const EngineTypeInfo* functionType,
  198. const EngineFunctionDefaultArguments* defaultArgs,
  199. void* address,
  200. U32 flags );
  201. /// Return the name of the function.
  202. const char* getFunctionName() const { return getExportName(); }
  203. /// Return the function's full prototype string including the return type, function name,
  204. /// and argument list.
  205. const char* getPrototypeString() const { return mPrototypeString; }
  206. /// Return the DLL export symbol name.
  207. const char* getBindingName() const { return mBindingName; }
  208. /// Test whether this is a callout function.
  209. bool isCallout() const { return mFunctionFlags.test( EngineFunctionCallout ); }
  210. /// Test whether the function is variadic, i.e. takes a variable number of arguments.
  211. bool isVariadic() const { return mFunctionType->isVariadic(); }
  212. /// Return the type of this function.
  213. const EngineTypeInfo* getFunctionType() const { return mFunctionType; }
  214. /// Return the return type of the function.
  215. const EngineTypeInfo* getReturnType() const { return getFunctionType()->getArgumentTypeTable()->getReturnType(); }
  216. /// Return the number of arguments that this function takes. If the function is variadic,
  217. /// this is the number of fixed arguments.
  218. U32 getNumArguments() const { return getFunctionType()->getArgumentTypeTable()->getNumArguments(); }
  219. ///
  220. const EngineTypeInfo* getArgumentType( U32 index ) const { return ( *( getFunctionType()->getArgumentTypeTable() ) )[ index ]; }
  221. /// Return the vector storing the default argument values.
  222. const EngineFunctionDefaultArguments* getDefaultArguments() const { return mDefaultArgumentValues; }
  223. /// Reset all callout function pointers back to NULL. This deactivates all callbacks.
  224. static void resetAllCallouts();
  225. };
  226. ///
  227. ///
  228. /// Due to the given argument types and return type being directly used as is, it is not possible
  229. /// to use this macro with engine types that have more complex value passing semantics (like e.g.
  230. /// String). Use engineAPI in this case.
  231. ///
  232. /// @note The method of defining functions exposed by this macro is very low-level. To more
  233. /// conveniently define API functions and methods, use the facilities provided in engineAPI.h.
  234. ///
  235. /// @see engineAPI.h
  236. #define DEFINE_CALLIN( bindingName, exportName, scope, returnType, args, defaultArgs, flags, doc ) \
  237. TORQUE_API returnType bindingName args; \
  238. namespace { namespace _ ## bindingName { \
  239. _EngineFunctionDefaultArguments< void args > sDefaultArgs defaultArgs; \
  240. EngineFunctionInfo sFunctionInfo( \
  241. #exportName, \
  242. &_SCOPE< scope >()(), \
  243. doc, \
  244. #returnType " " #exportName #args, \
  245. #bindingName, \
  246. TYPE< returnType args >(), \
  247. &sDefaultArgs, \
  248. ( void* ) &bindingName, \
  249. _EngineFunctionFlags( flags ) \
  250. ); \
  251. } } \
  252. TORQUE_API returnType bindingName args
  253. ///
  254. ///
  255. /// Not all control layers may be able to access data variables in a DLL so this macro exposes
  256. /// both the variable and a set_XXX function to set the variable programmatically.
  257. #define DEFINE_CALLOUT( bindingName, exportName, scope, returnType, args, flags, doc ) \
  258. TORQUE_API returnType ( *bindingName ) args; \
  259. TORQUE_API void set_ ## bindingName( returnType ( *fn ) args ) \
  260. { bindingName = fn; } \
  261. returnType ( *bindingName ) args; \
  262. namespace { \
  263. ::EngineFunctionInfo _cb ## bindingName( \
  264. #exportName, \
  265. &::_SCOPE< scope >()(), \
  266. doc, \
  267. #returnType " " #exportName #args, \
  268. #bindingName, \
  269. ::TYPE< returnType args >(), \
  270. NULL, \
  271. ( void* ) &bindingName, \
  272. EngineFunctionCallout | EngineFunctionFlags( flags ) \
  273. ); \
  274. }
  275. #endif // !_ENGINEFUNCTIONS_H_