engineFunctions.h 16 KB

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