3 * ================================================================
4 * SourcePawn, Copyright (C) 2004-2007 AlliedModders LLC.
6 * ================================================================
8 * This file is part of the SourceMod/SourcePawn SDK. This file may only be
9 * used or modified under the Terms and Conditions of its License Agreement,
10 * which is found in public/licenses/LICENSE.txt. As of this notice, derivative
11 * works must be licensed under the GNU General Public License (version 2 or
12 * greater). A copy of the GPL is included under public/licenses/GPL.txt.
14 * To view the latest information, see: http://www.sourcemod.net/license.php
19 #ifndef _INCLUDE_SOURCEPAWN_VM_API_H_
20 #define _INCLUDE_SOURCEPAWN_VM_API_H_
24 * @brief Contains all of the object structures used in the SourcePawn API.
28 #include "sp_vm_types.h"
30 /** SourcePawn Engine API Version */
31 #define SOURCEPAWN_ENGINE_API_VERSION 1
33 /** SourcePawn VM API Version */
34 #define SOURCEPAWN_VM_API_VERSION 3
36 #if !defined SOURCEMOD_BUILD
37 #define SOURCEMOD_BUILD
40 #if defined SOURCEMOD_BUILD
43 struct IdentityToken_t;
49 class IVirtualMachine;
51 #define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */
52 #define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */
53 #define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */
55 #if defined SOURCEMOD_BUILD
57 * @brief Pseudo-NULL reference types.
61 SP_NULL_VECTOR = 0, /**< Float[3] reference */
62 SP_NULL_STRING = 1, /**< const String[1] reference */
67 * @brief Represents what a function needs to implement in order to be callable.
73 * @brief Pushes a cell onto the current call.
75 * @param cell Parameter value to push.
76 * @return Error code, if any.
78 virtual int PushCell(cell_t cell) =0;
81 * @brief Pushes a cell by reference onto the current call.
82 * NOTE: On Execute, the pointer passed will be modified if copyback is enabled.
83 * NOTE: By reference parameters are cached and thus are not read until execution.
84 * This means you cannot push a pointer, change it, and push it again and expect
85 * two different values to come out.
87 * @param cell Address containing parameter value to push.
88 * @param flags Copy-back flags.
89 * @return Error code, if any.
91 virtual int PushCellByRef(cell_t *cell, int flags=SM_PARAM_COPYBACK) =0;
94 * @brief Pushes a float onto the current call.
96 * @param number Parameter value to push.
97 * @return Error code, if any.
99 virtual int PushFloat(float number) =0;
102 * @brief Pushes a float onto the current call by reference.
103 * NOTE: On Execute, the pointer passed will be modified if copyback is enabled.
104 * NOTE: By reference parameters are cached and thus are not read until execution.
105 * This means you cannot push a pointer, change it, and push it again and expect
106 * two different values to come out.
108 * @param number Parameter value to push.
109 & @param flags Copy-back flags.
110 * @return Error code, if any.
112 virtual int PushFloatByRef(float *number, int flags=SM_PARAM_COPYBACK) =0;
115 * @brief Pushes an array of cells onto the current call.
117 * On Execute, the pointer passed will be modified if non-NULL and copy-back
120 * By reference parameters are cached and thus are not read until execution.
121 * This means you cannot push a pointer, change it, and push it again and expect
122 * two different values to come out.
124 * @param inarray Array to copy, NULL if no initial array should be copied.
125 * @param cells Number of cells to allocate and optionally read from the input array.
126 * @param flags Whether or not changes should be copied back to the input array.
127 * @return Error code, if any.
129 virtual int PushArray(cell_t *inarray, unsigned int cells, int flags=0) =0;
132 * @brief Pushes a string onto the current call.
134 * @param string String to push.
135 * @return Error code, if any.
137 virtual int PushString(const char *string) =0;
140 * @brief Pushes a string or string buffer.
141 * NOTE: On Execute, the pointer passed will be modified if copy-back is enabled.
143 * @param buffer Pointer to string buffer.
144 * @param length Length of buffer.
145 * @param sz_flags String flags.
146 * @param cp_flags Copy-back flags.
147 * @return Error code, if any.
149 virtual int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags) =0;
152 * @brief Cancels a function call that is being pushed but not yet executed.
153 * This can be used be reset for CallFunction() use.
155 virtual void Cancel() =0;
160 * @brief Encapsulates a function call in a plugin.
162 * NOTE: Function calls must be atomic to one execution context.
163 * NOTE: This object should not be deleted. It lives for the lifetime of the plugin.
165 class IPluginFunction : public ICallable
169 * @brief Executes the forward, resets the pushed parameter list, and performs any copybacks.
171 * @param result Pointer to store return value in.
172 * @return Error code, if any.
174 virtual int Execute(cell_t *result) =0;
177 * @brief Executes the function with the given parameter array.
178 * Parameters are read in forward order (i.e. index 0 is parameter #1)
179 * NOTE: You will get an error if you attempt to use CallFunction() with
180 * previously pushed parameters.
182 * @param params Array of cell parameters.
183 * @param num_params Number of parameters to push.
184 * @param result Pointer to store result of function on return.
185 * @return SourcePawn error code (if any).
187 virtual int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result) =0;
190 * @brief Returns which plugin this function belongs to.
192 * @return IPluginContext pointer to parent plugin.
194 virtual IPluginContext *GetParentContext() =0;
197 * @brief Returns whether the parent plugin is paused.
199 * @return True if runnable, false otherwise.
201 virtual bool IsRunnable() =0;
206 * @brief Interface to managing a debug context at runtime.
208 class IPluginDebugInfo
212 * @brief Given a code pointer, finds the file it is associated with.
214 * @param addr Code address offset.
215 * @param filename Pointer to store filename pointer in.
217 virtual int LookupFile(ucell_t addr, const char **filename) =0;
220 * @brief Given a code pointer, finds the function it is associated with.
222 * @param addr Code address offset.
223 * @param name Pointer to store function name pointer in.
225 virtual int LookupFunction(ucell_t addr, const char **name) =0;
228 * @brief Given a code pointer, finds the line it is associated with.
230 * @param addr Code address offset.
231 * @param line Pointer to store line number in.
233 virtual int LookupLine(ucell_t addr, uint32_t *line) =0;
237 * @brief Interface to managing a context at runtime.
242 /** Virtual destructor */
243 virtual ~IPluginContext() { };
246 * @brief Returns the parent IVirtualMachine.
248 * @return Parent virtual machine pointer.
250 virtual IVirtualMachine *GetVirtualMachine() =0;
253 * @brief Returns the child sp_context_t structure.
255 * @return Child sp_context_t structure.
257 virtual sp_context_t *GetContext() =0;
260 * @brief Returns true if the plugin is in debug mode.
262 * @return True if in debug mode, false otherwise.
264 virtual bool IsDebugging() =0;
267 * @brief Installs a debug break and returns the old one, if any.
268 * This will fail if the plugin is not debugging.
270 * @param newpfn New function pointer.
271 * @param oldpfn Pointer to retrieve old function pointer.
273 virtual int SetDebugBreak(SPVM_DEBUGBREAK newpfn, SPVM_DEBUGBREAK *oldpfn) =0;
276 * @brief Returns debug info.
278 * @return IPluginDebugInfo, or NULL if no debug info found.
280 virtual IPluginDebugInfo *GetDebugInfo() =0;
283 * @brief Allocates memory on the secondary stack of a plugin.
284 * Note that although called a heap, it is in fact a stack.
286 * @param cells Number of cells to allocate.
287 * @param local_addr Will be filled with data offset to heap.
288 * @param phys_addr Physical address to heap memory.
290 virtual int HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr) =0;
293 * @brief Pops a heap address off the heap stack. Use this to free memory allocated with
295 * Note that in SourcePawn, the heap is in fact a bottom-up stack. Deallocations
296 * with this native should be performed in precisely the REVERSE order.
298 * @param local_addr Local address to free.
300 virtual int HeapPop(cell_t local_addr) =0;
303 * @brief Releases a heap address using a different method than SP_HeapPop().
304 * This allows you to release in any order. However, if you allocate N
305 * objects, release only some of them, then begin allocating again,
306 * you cannot go back and starting freeing the originals.
307 * In other words, for each chain of allocations, if you start deallocating,
308 * then allocating more in a chain, you must only deallocate from the current
309 * allocation chain. This is basically HeapPop() except on a larger scale.
311 * @param local_addr Local address to free.
313 virtual int HeapRelease(cell_t local_addr) =0;
316 * @brief Finds a native by name.
318 * @param name Name of native.
319 * @param index Optionally filled with native index number.
321 virtual int FindNativeByName(const char *name, uint32_t *index) =0;
324 * @brief Gets native info by index.
326 * @param index Index number of native.
327 * @param native Optionally filled with pointer to native structure.
329 virtual int GetNativeByIndex(uint32_t index, sp_native_t **native) =0;
332 * @brief Gets the number of natives.
334 * @return Filled with the number of natives.
336 virtual uint32_t GetNativesNum() =0;
339 * @brief Finds a public function by name.
341 * @param name Name of public
342 * @param index Optionally filled with public index number.
344 virtual int FindPublicByName(const char *name, uint32_t *index) =0;
347 * @brief Gets public function info by index.
349 * @param index Public function index number.
350 * @param publicptr Optionally filled with pointer to public structure.
352 virtual int GetPublicByIndex(uint32_t index, sp_public_t **publicptr) =0;
355 * @brief Gets the number of public functions.
357 * @return Filled with the number of public functions.
359 virtual uint32_t GetPublicsNum() =0;
362 * @brief Gets public variable info by index.
364 * @param index Public variable index number.
365 * @param pubvar Optionally filled with pointer to pubvar structure.
367 virtual int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar) =0;
370 * @brief Finds a public variable by name.
372 * @param name Name of pubvar
373 * @param index Optionally filled with pubvar index number.
375 virtual int FindPubvarByName(const char *name, uint32_t *index) =0;
378 * @brief Gets the addresses of a public variable.
380 * @param index Index of public variable.
381 * @param local_addr Address to store local address in.
382 * @param phys_addr Address to store physically relocated in.
384 virtual int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) =0;
387 * @brief Returns the number of public variables.
389 * @return Number of public variables.
391 virtual uint32_t GetPubVarsNum() =0;
394 * @brief Round-about method of converting a plugin reference to a physical address
396 * @param local_addr Local address in plugin.
397 * @param phys_addr Optionally filled with relocated physical address.
399 virtual int LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr) =0;
402 * @brief Converts a local address to a physical string.
404 * @param local_addr Local address in plugin.
405 * @param addr Destination output pointer.
407 virtual int LocalToString(cell_t local_addr, char **addr) =0;
410 * @brief Converts a physical string to a local address.
412 * @param local_addr Local address in plugin.
413 * @param bytes Number of chars to write, including NULL terminator.
414 * @param source Source string to copy.
416 virtual int StringToLocal(cell_t local_addr, size_t bytes, const char *source) =0;
419 * @brief Converts a physical UTF-8 string to a local address.
420 * This function is the same as the ANSI version, except it will copy the maximum number of characters possible
421 * without accidentally chopping a multi-byte character.
423 * @param local_addr Local address in plugin.
424 * @param maxbytes Number of bytes to write, including NULL terminator.
425 * @param source Source string to copy.
426 * @param wrtnbytes Optionally set to the number of actual bytes written.
428 virtual int StringToLocalUTF8(cell_t local_addr,
431 size_t *wrtnbytes) =0;
434 * @brief Pushes a cell onto the stack. Increases the parameter count by one.
436 * @param value Cell value.
438 virtual int PushCell(cell_t value) =0;
441 * @brief Pushes an array of cells onto the stack. Increases the parameter count by one.
442 * If the function returns an error it will fail entirely, releasing anything allocated in the process.
443 * Note that this does not release the heap, so you should release it after
446 * @param local_addr Filled with local address to release.
447 * @param phys_addr Optionally filled with physical address of new array.
448 * @param array Cell array to copy.
449 * @param numcells Number of cells in the array to copy.
451 virtual int PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells) =0;
454 * @brief Pushes a string onto the stack (by reference) and increases the parameter count by one.
455 * Note that this does not release the heap, so you should release it after
458 * @param local_addr Filled with local address to release.
459 * @param phys_addr Optionally filled with physical address of new array.
460 * @param string Source string to push.
462 virtual int PushString(cell_t *local_addr, char **phys_addr, const char *string) =0;
465 * @brief Individually pushes each cell of an array of cells onto the stack. Increases the
466 * parameter count by the number of cells pushed.
467 * If the function returns an error it will fail entirely, releasing anything allocated in the process.
469 * @param array Array of cells to read from.
470 * @param numcells Number of cells to read.
472 virtual int PushCellsFromArray(cell_t array[], unsigned int numcells) =0;
475 * @brief Binds a list of native names and their function pointers to a context.
476 * If num is 0, the list is read until an entry with a NULL name is reached.
477 * If overwrite is non-zero, already registered natives will be overwritten.
479 * @param natives Array of natives.
480 * @param num Number of natives in array.
481 * @param overwrite Toggles overwrite.
483 virtual int BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite) =0;
486 * @brief Binds a single native. Overwrites any existing bind.
487 * If the context does not contain the native that will be binded the function will return
488 * with a SP_ERROR_NOT_FOUND error.
490 * @param native Pointer to native.
492 virtual int BindNative(const sp_nativeinfo_t *native) =0;
495 * @brief Binds a single native to any non-registered native.
497 * @param native Native to bind.
499 virtual int BindNativeToAny(SPVM_NATIVE_FUNC native) =0;
502 * @brief Executes a function ID located in this context.
504 * @param code_addr Address to execute at.
505 * @param result Pointer to store the return value (required).
506 * @return Error code (if any) from the VM.
508 virtual int Execute(uint32_t code_addr, cell_t *result) =0;
511 * @brief Throws a error and halts any current execution.
513 * @param error The error number to set.
514 * @param msg Custom error message format. NULL to use default.
515 * @param ... Message format arguments, if any.
516 * @return 0 for convenience.
518 virtual cell_t ThrowNativeErrorEx(int error, const char *msg, ...) =0;
521 * @brief Throws a generic native error and halts any current execution.
523 * @param msg Custom error message format. NULL to set no message.
524 * @param ... Message format arguments, if any.
525 * @return 0 for convenience.
527 virtual cell_t ThrowNativeError(const char *msg, ...) =0;
530 * @brief Returns a function by name.
532 * @param public_name Name of the function.
533 * @return A new IPluginFunction pointer, NULL if not found.
535 virtual IPluginFunction *GetFunctionByName(const char *public_name) =0;
538 * @brief Returns a function by its id.
540 * @param func_id Function ID.
541 * @return A new IPluginFunction pointer, NULL if not found.
543 virtual IPluginFunction *GetFunctionById(funcid_t func_id) =0;
545 #if defined SOURCEMOD_BUILD
547 * @brief Returns the identity token for this context.
548 * Note: This is a helper function for native calls and the Handle System.
550 * @return Identity token.
552 virtual SourceMod::IdentityToken_t *GetIdentity() =0;
555 * @brief Returns a NULL reference based on one of the available NULL
558 * @param type NULL reference type.
559 * @return cell_t address to compare to.
561 virtual cell_t *GetNullRef(SP_NULL_TYPE type) =0;
564 * @brief Converts a local address to a physical string, and allows
565 * for NULL_STRING to be set.
567 * @param local_addr Local address in plugin.
568 * @param addr Destination output pointer.
570 virtual int LocalToStringNULL(cell_t local_addr, char **addr) =0;
576 * @brief Information about a position in a call stack.
580 const char *filename; /**< NULL if not found */
581 unsigned int line; /**< 0 if not found */
582 const char *function; /**< NULL if not found */
586 * @brief Retrieves error information from a debug hook.
592 * @brief Returns the integer error code.
594 * @return Integer error code.
596 virtual int GetErrorCode() =0;
599 * @brief Returns a string describing the error.
601 * @return Error string.
603 virtual const char *GetErrorString() =0;
606 * @brief Returns whether debug info is available.
608 * @return True if debug info is available, false otherwise.
610 virtual bool DebugInfoAvailable() =0;
613 * @brief Returns a custom error message.
615 * @return A pointer to a custom error message, or NULL otherwise.
617 virtual const char *GetCustomErrorString() =0;
620 * @brief Returns trace info for a specific point in the backtrace, if any.
621 * The next subsequent call to GetTraceInfo() will return the next item in the call stack.
622 * Calls are retrieved in descending order (i.e. the first item is at the top of the stack/call sequence).
624 * @param trace An ErrorTraceInfo buffer to store information (NULL to ignore).
625 * @return True if successful, false if there are no more traces.
627 virtual bool GetTraceInfo(CallStackInfo *trace) =0;
630 * @brief Resets the trace to its original position (the call on the top of the stack).
632 virtual void ResetTrace() =0;
635 * @brief Retrieves the name of the last native called.
636 * Returns NULL if there was no native that caused the error.
638 * @param index Optional pointer to store index.
639 * @return Native name, or NULL if none.
641 virtual const char *GetLastNative(uint32_t *index) =0;
646 * @brief Provides callbacks for debug information.
651 virtual void OnContextExecuteError(IPluginContext *ctx, IContextTrace *error) =0;
656 * @brief Contains helper functions used by VMs and the host app
658 class ISourcePawnEngine
662 * @brief Loads a named file from a file pointer.
663 * Note: Using this means the memory will be allocated by the VM.
665 * @param fp File pointer. May be at any offset. Not closed on return.
666 * @param err Optional error code pointer.
667 * @return A new plugin structure.
669 virtual sp_plugin_t *LoadFromFilePointer(FILE *fp, int *err) =0;
672 * @brief Loads a file from a base memory address.
674 * @param base Base address of the plugin's memory region.
675 * @param plugin If NULL, a new plugin pointer is returned.
676 * Otherwise, the passed pointer is used.
677 * @param err Optional error code pointer.
678 * @return The resulting plugin pointer.
680 virtual sp_plugin_t *LoadFromMemory(void *base, sp_plugin_t *plugin, int *err) =0;
683 * Frees all of the memory associated with a plugin file.
684 * If allocated using SP_LoadFromMemory, the base and plugin pointer
685 * itself are not freed (so this may end up doing nothing).
687 virtual int FreeFromMemory(sp_plugin_t *plugin) =0;
690 * @brief Allocates large blocks of temporary memory.
692 * @param size Size of memory to allocate.
693 * @return Pointer to memory, NULL if allocation failed.
695 virtual void *BaseAlloc(size_t size) =0;
698 * @brief Frees memory allocated with BaseAlloc.
700 * @param memory Memory address to free.
702 virtual void BaseFree(void *memory) =0;
705 * @brief Allocates executable memory.
707 * @param size Size of memory to allocate.
708 * @return Pointer to memory, NULL if allocation failed.
710 virtual void *ExecAlloc(size_t size) =0;
713 * @brief Frees executable memory.
715 * @param address Address to free.
717 virtual void ExecFree(void *address) =0;
720 * @brief Sets the debug listener. This should only be called once.
721 * If called successively (using manual chaining), only the last function should
722 * attempt to call back into the same plugin. Otherwise, globally cached states
723 * can be accidentally overwritten.
725 * @param listener Pointer to an IDebugListener.
726 * @return Old IDebugListener, or NULL if none.
728 virtual IDebugListener *SetDebugListener(IDebugListener *listener) =0;
731 * @brief Returns the number of plugins on the call stack.
733 * @return Number of contexts in the call stack.
735 virtual unsigned int GetContextCallCount() =0;
738 * @brief Returns the engine API version.
740 * @return Engine API version.
742 virtual unsigned int GetEngineAPIVersion() =0;
747 * @brief Dummy class for encapsulating private compilation data.
752 /** Virtual destructor */
753 virtual ~ICompilation() { };
758 * @brief Outlines the interface a Virtual Machine (JIT) must expose
760 class IVirtualMachine
764 * @brief Returns the current API version.
766 virtual unsigned int GetAPIVersion() =0;
769 * @brief Returns the string name of a VM implementation.
771 virtual const char *GetVMName() =0;
774 * @brief Begins a new compilation
776 * @param plugin Pointer to a plugin structure.
777 * @return New compilation pointer.
779 virtual ICompilation *StartCompilation(sp_plugin_t *plugin) =0;
782 * @brief Sets a compilation option.
784 * @param co Pointer to a compilation.
785 * @param key Option key name.
786 * @param val Option value string.
787 * @return True if option could be set, false otherwise.
789 virtual bool SetCompilationOption(ICompilation *co, const char *key, const char *val) =0;
792 * @brief Finalizes a compilation into a new sp_context_t.
793 * Note: This will free the ICompilation pointer.
795 * @param co Compilation pointer.
796 * @param err Filled with error code on exit.
797 * @return New plugin context.
799 virtual sp_context_t *CompileToContext(ICompilation *co, int *err) =0;
802 * @brief Aborts a compilation and frees the ICompilation pointer.
804 * @param co Compilation pointer.
806 virtual void AbortCompilation(ICompilation *co) =0;
809 * @brief Frees any internal variable usage on a context.
811 * @param ctx Context structure pointer.
813 virtual void FreeContext(sp_context_t *ctx) =0;
816 * @brief Calls the "execute" function on a context.
818 * @param ctx Executes a function in a context.
819 * @param code_addr Index into the code section.
820 * @param result Pointer to store result into.
821 * @return Error code (if any).
823 virtual int ContextExecute(sp_context_t *ctx, uint32_t code_addr, cell_t *result) =0;
826 * @brief Given a context and a code address, returns the index of the function.
828 * @param ctx Context to search.
829 * @param code_addr Index into the code section.
830 * @param result Pointer to store result into.
831 * @return True if code index is valid, false otherwise.
833 virtual bool FunctionLookup(const sp_context_t *ctx, uint32_t code_addr, unsigned int *result) =0;
836 * @brief Returns the number of functions defined in the context.
838 * @param ctx Context to search.
839 * @return Number of functions.
841 virtual unsigned int FunctionCount(const sp_context_t *ctx) =0;
844 * @brief Returns a version string.
846 * @return Versioning string.
848 virtual const char *GetVersionString() =0;
851 * @brief Returns a string describing optimizations.
853 * @return String describing CPU specific optimizations.
855 virtual const char *GetCPUOptimizations() =0;
858 * @brief Given a context and a p-code address, returns the index of the function.
860 * @param ctx Context to search.
861 * @param code_addr Index into the p-code section.
862 * @param result Pointer to store result into.
863 * @return True if code index is valid, false otherwise.
865 virtual bool FunctionPLookup(const sp_context_t *ctx, uint32_t code_addr, unsigned int *result) =0;
868 * @brief Creates a fake native and binds it to a general callback function.
870 * @param callback Callback function to bind the native to.
871 * @param pData Private data to pass to the callback when the native is invoked.
872 * @return A new fake native function as a wrapper around the callback.
874 virtual SPVM_NATIVE_FUNC CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData) =0;
877 * @brief Destroys a fake native function wrapper.
879 * @param func Pointer to the fake native created by CreateFakeNative.
881 virtual void DestroyFakeNative(SPVM_NATIVE_FUNC func) =0;
885 #endif //_INCLUDE_SOURCEPAWN_VM_API_H_