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 VM API Version */
31 #define SOURCEPAWN_VM_API_VERSION 3
33 #if !defined SOURCEMOD_BUILD
34 #define SOURCEMOD_BUILD
37 #if defined SOURCEMOD_BUILD
40 struct IdentityToken_t;
46 class IVirtualMachine;
48 #define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */
49 #define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */
50 #define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */
52 #if defined SOURCEMOD_BUILD
54 * @brief Pseudo-NULL reference types.
58 SP_NULL_VECTOR = 0, /**< Float[3] reference */
59 SP_NULL_STRING = 1, /**< const String[1] reference */
64 * @brief Represents what a function needs to implement in order to be callable.
70 * @brief Pushes a cell onto the current call.
72 * @param cell Parameter value to push.
73 * @return Error code, if any.
75 virtual int PushCell(cell_t cell) =0;
78 * @brief Pushes a cell by reference onto the current call.
79 * NOTE: On Execute, the pointer passed will be modified if copyback is enabled.
80 * NOTE: By reference parameters are cached and thus are not read until execution.
81 * This means you cannot push a pointer, change it, and push it again and expect
82 * two different values to come out.
84 * @param cell Address containing parameter value to push.
85 * @param flags Copy-back flags.
86 * @return Error code, if any.
88 virtual int PushCellByRef(cell_t *cell, int flags=SM_PARAM_COPYBACK) =0;
91 * @brief Pushes a float onto the current call.
93 * @param number Parameter value to push.
94 * @return Error code, if any.
96 virtual int PushFloat(float number) =0;
99 * @brief Pushes a float onto the current call by reference.
100 * NOTE: On Execute, the pointer passed will be modified if copyback is enabled.
101 * NOTE: By reference parameters are cached and thus are not read until execution.
102 * This means you cannot push a pointer, change it, and push it again and expect
103 * two different values to come out.
105 * @param number Parameter value to push.
106 & @param flags Copy-back flags.
107 * @return Error code, if any.
109 virtual int PushFloatByRef(float *number, int flags=SM_PARAM_COPYBACK) =0;
112 * @brief Pushes an array of cells onto the current call.
114 * On Execute, the pointer passed will be modified if non-NULL and copy-back
117 * By reference parameters are cached and thus are not read until execution.
118 * This means you cannot push a pointer, change it, and push it again and expect
119 * two different values to come out.
121 * @param inarray Array to copy, NULL if no initial array should be copied.
122 * @param cells Number of cells to allocate and optionally read from the input array.
123 * @param flags Whether or not changes should be copied back to the input array.
124 * @return Error code, if any.
126 virtual int PushArray(cell_t *inarray, unsigned int cells, int flags=0) =0;
129 * @brief Pushes a string onto the current call.
131 * @param string String to push.
132 * @return Error code, if any.
134 virtual int PushString(const char *string) =0;
137 * @brief Pushes a string or string buffer.
138 * NOTE: On Execute, the pointer passed will be modified if copy-back is enabled.
140 * @param buffer Pointer to string buffer.
141 * @param length Length of buffer.
142 * @param sz_flags String flags.
143 * @param cp_flags Copy-back flags.
144 * @return Error code, if any.
146 virtual int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags) =0;
149 * @brief Cancels a function call that is being pushed but not yet executed.
150 * This can be used be reset for CallFunction() use.
152 virtual void Cancel() =0;
157 * @brief Encapsulates a function call in a plugin.
159 * NOTE: Function calls must be atomic to one execution context.
160 * NOTE: This object should not be deleted. It lives for the lifetime of the plugin.
162 class IPluginFunction : public ICallable
166 * @brief Executes the forward, resets the pushed parameter list, and performs any copybacks.
168 * @param result Pointer to store return value in.
169 * @return Error code, if any.
171 virtual int Execute(cell_t *result) =0;
174 * @brief Executes the function with the given parameter array.
175 * Parameters are read in forward order (i.e. index 0 is parameter #1)
176 * NOTE: You will get an error if you attempt to use CallFunction() with
177 * previously pushed parameters.
179 * @param params Array of cell parameters.
180 * @param num_params Number of parameters to push.
181 * @param result Pointer to store result of function on return.
182 * @return SourcePawn error code (if any).
184 virtual int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result) =0;
187 * @brief Returns which plugin this function belongs to.
189 * @return IPluginContext pointer to parent plugin.
191 virtual IPluginContext *GetParentContext() =0;
194 * @brief Returns whether the parent plugin is paused.
196 * @return True if runnable, false otherwise.
198 virtual bool IsRunnable() =0;
203 * @brief Interface to managing a debug context at runtime.
205 class IPluginDebugInfo
209 * @brief Given a code pointer, finds the file it is associated with.
211 * @param addr Code address offset.
212 * @param filename Pointer to store filename pointer in.
214 virtual int LookupFile(ucell_t addr, const char **filename) =0;
217 * @brief Given a code pointer, finds the function it is associated with.
219 * @param addr Code address offset.
220 * @param name Pointer to store function name pointer in.
222 virtual int LookupFunction(ucell_t addr, const char **name) =0;
225 * @brief Given a code pointer, finds the line it is associated with.
227 * @param addr Code address offset.
228 * @param line Pointer to store line number in.
230 virtual int LookupLine(ucell_t addr, uint32_t *line) =0;
234 * @brief Interface to managing a context at runtime.
239 /** Virtual destructor */
240 virtual ~IPluginContext() { };
243 * @brief Returns the parent IVirtualMachine.
245 * @return Parent virtual machine pointer.
247 virtual IVirtualMachine *GetVirtualMachine() =0;
250 * @brief Returns the child sp_context_t structure.
252 * @return Child sp_context_t structure.
254 virtual sp_context_t *GetContext() =0;
257 * @brief Returns true if the plugin is in debug mode.
259 * @return True if in debug mode, false otherwise.
261 virtual bool IsDebugging() =0;
264 * @brief Installs a debug break and returns the old one, if any.
265 * This will fail if the plugin is not debugging.
267 * @param newpfn New function pointer.
268 * @param oldpfn Pointer to retrieve old function pointer.
270 virtual int SetDebugBreak(SPVM_DEBUGBREAK newpfn, SPVM_DEBUGBREAK *oldpfn) =0;
273 * @brief Returns debug info.
275 * @return IPluginDebugInfo, or NULL if no debug info found.
277 virtual IPluginDebugInfo *GetDebugInfo() =0;
280 * @brief Allocates memory on the secondary stack of a plugin.
281 * Note that although called a heap, it is in fact a stack.
283 * @param cells Number of cells to allocate.
284 * @param local_addr Will be filled with data offset to heap.
285 * @param phys_addr Physical address to heap memory.
287 virtual int HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr) =0;
290 * @brief Pops a heap address off the heap stack. Use this to free memory allocated with
292 * Note that in SourcePawn, the heap is in fact a bottom-up stack. Deallocations
293 * with this native should be performed in precisely the REVERSE order.
295 * @param local_addr Local address to free.
297 virtual int HeapPop(cell_t local_addr) =0;
300 * @brief Releases a heap address using a different method than SP_HeapPop().
301 * This allows you to release in any order. However, if you allocate N
302 * objects, release only some of them, then begin allocating again,
303 * you cannot go back and starting freeing the originals.
304 * In other words, for each chain of allocations, if you start deallocating,
305 * then allocating more in a chain, you must only deallocate from the current
306 * allocation chain. This is basically HeapPop() except on a larger scale.
308 * @param local_addr Local address to free.
310 virtual int HeapRelease(cell_t local_addr) =0;
313 * @brief Finds a native by name.
315 * @param name Name of native.
316 * @param index Optionally filled with native index number.
318 virtual int FindNativeByName(const char *name, uint32_t *index) =0;
321 * @brief Gets native info by index.
323 * @param index Index number of native.
324 * @param native Optionally filled with pointer to native structure.
326 virtual int GetNativeByIndex(uint32_t index, sp_native_t **native) =0;
329 * @brief Gets the number of natives.
331 * @return Filled with the number of natives.
333 virtual uint32_t GetNativesNum() =0;
336 * @brief Finds a public function by name.
338 * @param name Name of public
339 * @param index Optionally filled with public index number.
341 virtual int FindPublicByName(const char *name, uint32_t *index) =0;
344 * @brief Gets public function info by index.
346 * @param index Public function index number.
347 * @param publicptr Optionally filled with pointer to public structure.
349 virtual int GetPublicByIndex(uint32_t index, sp_public_t **publicptr) =0;
352 * @brief Gets the number of public functions.
354 * @return Filled with the number of public functions.
356 virtual uint32_t GetPublicsNum() =0;
359 * @brief Gets public variable info by index.
361 * @param index Public variable index number.
362 * @param pubvar Optionally filled with pointer to pubvar structure.
364 virtual int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar) =0;
367 * @brief Finds a public variable by name.
369 * @param name Name of pubvar
370 * @param index Optionally filled with pubvar index number.
372 virtual int FindPubvarByName(const char *name, uint32_t *index) =0;
375 * @brief Gets the addresses of a public variable.
377 * @param index Index of public variable.
378 * @param local_addr Address to store local address in.
379 * @param phys_addr Address to store physically relocated in.
381 virtual int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) =0;
384 * @brief Returns the number of public variables.
386 * @return Number of public variables.
388 virtual uint32_t GetPubVarsNum() =0;
391 * @brief Round-about method of converting a plugin reference to a physical address
393 * @param local_addr Local address in plugin.
394 * @param phys_addr Optionally filled with relocated physical address.
396 virtual int LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr) =0;
399 * @brief Converts a local address to a physical string.
401 * @param local_addr Local address in plugin.
402 * @param addr Destination output pointer.
404 virtual int LocalToString(cell_t local_addr, char **addr) =0;
407 * @brief Converts a physical string to a local address.
409 * @param local_addr Local address in plugin.
410 * @param bytes Number of chars to write, including NULL terminator.
411 * @param source Source string to copy.
413 virtual int StringToLocal(cell_t local_addr, size_t bytes, const char *source) =0;
416 * @brief Converts a physical UTF-8 string to a local address.
417 * This function is the same as the ANSI version, except it will copy the maximum number of characters possible
418 * without accidentally chopping a multi-byte character.
420 * @param local_addr Local address in plugin.
421 * @param maxbytes Number of bytes to write, including NULL terminator.
422 * @param source Source string to copy.
423 * @param wrtnbytes Optionally set to the number of actual bytes written.
425 virtual int StringToLocalUTF8(cell_t local_addr,
428 size_t *wrtnbytes) =0;
431 * @brief Pushes a cell onto the stack. Increases the parameter count by one.
433 * @param value Cell value.
435 virtual int PushCell(cell_t value) =0;
438 * @brief Pushes an array of cells onto the stack. Increases the parameter count by one.
439 * If the function returns an error it will fail entirely, releasing anything allocated in the process.
440 * Note that this does not release the heap, so you should release it after
443 * @param local_addr Filled with local address to release.
444 * @param phys_addr Optionally filled with physical address of new array.
445 * @param array Cell array to copy.
446 * @param numcells Number of cells in the array to copy.
448 virtual int PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells) =0;
451 * @brief Pushes a string onto the stack (by reference) and increases the parameter count by one.
452 * Note that this does not release the heap, so you should release it after
455 * @param local_addr Filled with local address to release.
456 * @param phys_addr Optionally filled with physical address of new array.
457 * @param string Source string to push.
459 virtual int PushString(cell_t *local_addr, char **phys_addr, const char *string) =0;
462 * @brief Individually pushes each cell of an array of cells onto the stack. Increases the
463 * parameter count by the number of cells pushed.
464 * If the function returns an error it will fail entirely, releasing anything allocated in the process.
466 * @param array Array of cells to read from.
467 * @param numcells Number of cells to read.
469 virtual int PushCellsFromArray(cell_t array[], unsigned int numcells) =0;
472 * @brief Binds a list of native names and their function pointers to a context.
473 * If num is 0, the list is read until an entry with a NULL name is reached.
474 * If overwrite is non-zero, already registered natives will be overwritten.
476 * @param natives Array of natives.
477 * @param num Number of natives in array.
478 * @param overwrite Toggles overwrite.
480 virtual int BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite) =0;
483 * @brief Binds a single native. Overwrites any existing bind.
484 * If the context does not contain the native that will be binded the function will return
485 * with a SP_ERROR_NOT_FOUND error.
487 * @param native Pointer to native.
489 virtual int BindNative(const sp_nativeinfo_t *native) =0;
492 * @brief Binds a single native to any non-registered native.
494 * @param native Native to bind.
496 virtual int BindNativeToAny(SPVM_NATIVE_FUNC native) =0;
499 * @brief Executes a function ID located in this context.
501 * @param code_addr Address to execute at.
502 * @param result Pointer to store the return value (required).
503 * @return Error code (if any) from the VM.
505 virtual int Execute(uint32_t code_addr, cell_t *result) =0;
508 * @brief Throws a error and halts any current execution.
510 * @param error The error number to set.
511 * @param msg Custom error message format. NULL to use default.
512 * @param ... Message format arguments, if any.
513 * @return 0 for convenience.
515 virtual cell_t ThrowNativeErrorEx(int error, const char *msg, ...) =0;
518 * @brief Throws a generic native error and halts any current execution.
520 * @param msg Custom error message format. NULL to set no message.
521 * @param ... Message format arguments, if any.
522 * @return 0 for convenience.
524 virtual cell_t ThrowNativeError(const char *msg, ...) =0;
527 * @brief Returns a function by name.
529 * @param public_name Name of the function.
530 * @return A new IPluginFunction pointer, NULL if not found.
532 virtual IPluginFunction *GetFunctionByName(const char *public_name) =0;
535 * @brief Returns a function by its id.
537 * @param func_id Function ID.
538 * @return A new IPluginFunction pointer, NULL if not found.
540 virtual IPluginFunction *GetFunctionById(funcid_t func_id) =0;
542 #if defined SOURCEMOD_BUILD
544 * @brief Returns the identity token for this context.
545 * Note: This is a helper function for native calls and the Handle System.
547 * @return Identity token.
549 virtual SourceMod::IdentityToken_t *GetIdentity() =0;
552 * @brief Returns a NULL reference based on one of the available NULL
555 * @param type NULL reference type.
556 * @return cell_t address to compare to.
558 virtual cell_t *GetNullRef(SP_NULL_TYPE type) =0;
561 * @brief Converts a local address to a physical string, and allows
562 * for NULL_STRING to be set.
564 * @param local_addr Local address in plugin.
565 * @param addr Destination output pointer.
567 virtual int LocalToStringNULL(cell_t local_addr, char **addr) =0;
573 * @brief Information about a position in a call stack.
577 const char *filename; /**< NULL if not found */
578 unsigned int line; /**< 0 if not found */
579 const char *function; /**< NULL if not found */
583 * @brief Retrieves error information from a debug hook.
589 * @brief Returns the integer error code.
591 * @return Integer error code.
593 virtual int GetErrorCode() =0;
596 * @brief Returns a string describing the error.
598 * @return Error string.
600 virtual const char *GetErrorString() =0;
603 * @brief Returns whether debug info is available.
605 * @return True if debug info is available, false otherwise.
607 virtual bool DebugInfoAvailable() =0;
610 * @brief Returns a custom error message.
612 * @return A pointer to a custom error message, or NULL otherwise.
614 virtual const char *GetCustomErrorString() =0;
617 * @brief Returns trace info for a specific point in the backtrace, if any.
618 * The next subsequent call to GetTraceInfo() will return the next item in the call stack.
619 * Calls are retrieved in descending order (i.e. the first item is at the top of the stack/call sequence).
621 * @param trace An ErrorTraceInfo buffer to store information (NULL to ignore).
622 * @return True if successful, false if there are no more traces.
624 virtual bool GetTraceInfo(CallStackInfo *trace) =0;
627 * @brief Resets the trace to its original position (the call on the top of the stack).
629 virtual void ResetTrace() =0;
632 * @brief Retrieves the name of the last native called.
633 * Returns NULL if there was no native that caused the error.
635 * @param index Optional pointer to store index.
636 * @return Native name, or NULL if none.
638 virtual const char *GetLastNative(uint32_t *index) =0;
643 * @brief Provides callbacks for debug information.
648 virtual void OnContextExecuteError(IPluginContext *ctx, IContextTrace *error) =0;
653 * @brief Contains helper functions used by VMs and the host app
655 class ISourcePawnEngine
659 * @brief Loads a named file from a file pointer.
660 * Note: Using this means the memory will be allocated by the VM.
662 * @param fp File pointer. May be at any offset. Not closed on return.
663 * @param err Optional error code pointer.
664 * @return A new plugin structure.
666 virtual sp_plugin_t *LoadFromFilePointer(FILE *fp, int *err) =0;
669 * @brief Loads a file from a base memory address.
671 * @param base Base address of the plugin's memory region.
672 * @param plugin If NULL, a new plugin pointer is returned.
673 * Otherwise, the passed pointer is used.
674 * @param err Optional error code pointer.
675 * @return The resulting plugin pointer.
677 virtual sp_plugin_t *LoadFromMemory(void *base, sp_plugin_t *plugin, int *err) =0;
680 * Frees all of the memory associated with a plugin file.
681 * If allocated using SP_LoadFromMemory, the base and plugin pointer
682 * itself are not freed (so this may end up doing nothing).
684 virtual int FreeFromMemory(sp_plugin_t *plugin) =0;
687 * @brief Allocates large blocks of temporary memory.
689 * @param size Size of memory to allocate.
690 * @return Pointer to memory, NULL if allocation failed.
692 virtual void *BaseAlloc(size_t size) =0;
695 * @brief Frees memory allocated with BaseAlloc.
697 * @param memory Memory address to free.
699 virtual void BaseFree(void *memory) =0;
702 * @brief Allocates executable memory.
704 * @param size Size of memory to allocate.
705 * @return Pointer to memory, NULL if allocation failed.
707 virtual void *ExecAlloc(size_t size) =0;
710 * @brief Frees executable memory.
712 * @param address Address to free.
714 virtual void ExecFree(void *address) =0;
717 * @brief Sets the debug listener. This should only be called once.
718 * If called successively (using manual chaining), only the last function should
719 * attempt to call back into the same plugin. Otherwise, globally cached states
720 * can be accidentally overwritten.
722 * @param listener Pointer to an IDebugListener.
723 * @return Old IDebugListener, or NULL if none.
725 virtual IDebugListener *SetDebugListener(IDebugListener *listener) =0;
728 * @brief Returns the number of plugins on the call stack.
730 * @return Number of contexts in the call stack.
732 virtual unsigned int GetContextCallCount() =0;
737 * @brief Dummy class for encapsulating private compilation data.
742 /** Virtual destructor */
743 virtual ~ICompilation() { };
748 * @brief Outlines the interface a Virtual Machine (JIT) must expose
750 class IVirtualMachine
754 * @brief Returns the current API version.
756 virtual unsigned int GetAPIVersion() =0;
759 * @brief Returns the string name of a VM implementation.
761 virtual const char *GetVMName() =0;
764 * @brief Begins a new compilation
766 * @param plugin Pointer to a plugin structure.
767 * @return New compilation pointer.
769 virtual ICompilation *StartCompilation(sp_plugin_t *plugin) =0;
772 * @brief Sets a compilation option.
774 * @param co Pointer to a compilation.
775 * @param key Option key name.
776 * @param val Option value string.
777 * @return True if option could be set, false otherwise.
779 virtual bool SetCompilationOption(ICompilation *co, const char *key, const char *val) =0;
782 * @brief Finalizes a compilation into a new sp_context_t.
783 * Note: This will free the ICompilation pointer.
785 * @param co Compilation pointer.
786 * @param err Filled with error code on exit.
787 * @return New plugin context.
789 virtual sp_context_t *CompileToContext(ICompilation *co, int *err) =0;
792 * @brief Aborts a compilation and frees the ICompilation pointer.
794 * @param co Compilation pointer.
796 virtual void AbortCompilation(ICompilation *co) =0;
799 * @brief Frees any internal variable usage on a context.
801 * @param ctx Context structure pointer.
803 virtual void FreeContext(sp_context_t *ctx) =0;
806 * @brief Calls the "execute" function on a context.
808 * @param ctx Executes a function in a context.
809 * @param code_addr Index into the code section.
810 * @param result Pointer to store result into.
811 * @return Error code (if any).
813 virtual int ContextExecute(sp_context_t *ctx, uint32_t code_addr, cell_t *result) =0;
816 * @brief Given a context and a code address, returns the index of the function.
818 * @param ctx Context to search.
819 * @param code_addr Index into the code section.
820 * @param result Pointer to store result into.
821 * @return True if code index is valid, false otherwise.
823 virtual bool FunctionLookup(const sp_context_t *ctx, uint32_t code_addr, unsigned int *result) =0;
826 * @brief Returns the number of functions defined in the context.
828 * @param ctx Context to search.
829 * @return Number of functions.
831 virtual unsigned int FunctionCount(const sp_context_t *ctx) =0;
834 * @brief Returns a version string.
836 * @return Versioning string.
838 virtual const char *GetVersionString() =0;
841 * @brief Returns a string describing optimizations.
843 * @return String describing CPU specific optimizations.
845 virtual const char *GetCPUOptimizations() =0;
848 * @brief Given a context and a p-code address, returns the index of the function.
850 * @param ctx Context to search.
851 * @param code_addr Index into the p-code section.
852 * @param result Pointer to store result into.
853 * @return True if code index is valid, false otherwise.
855 virtual bool FunctionPLookup(const sp_context_t *ctx, uint32_t code_addr, unsigned int *result) =0;
858 * @brief Creates a fake native and binds it to a general callback function.
860 * @param callback Callback function to bind the native to.
861 * @param pData Private data to pass to the callback when the native is invoked.
862 * @return A new fake native function as a wrapper around the callback.
864 virtual SPVM_NATIVE_FUNC CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData) =0;
867 * @brief Destroys a fake native function wrapper.
869 * @param func Pointer to the fake native created by CreateFakeNative.
871 virtual void DestroyFakeNative(SPVM_NATIVE_FUNC func) =0;
875 #endif //_INCLUDE_SOURCEPAWN_VM_API_H_