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 2
33 #if defined SOURCEMOD_BUILD
36 struct IdentityToken_t;
42 class IVirtualMachine;
44 #define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */
45 #define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */
46 #define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */
49 * @brief Represents what a function needs to implement in order to be callable.
55 * @brief Pushes a cell onto the current call.
57 * @param cell Parameter value to push.
58 * @return Error code, if any.
60 virtual int PushCell(cell_t cell) =0;
63 * @brief Pushes a cell by reference onto the current call.
64 * NOTE: On Execute, the pointer passed will be modified if copyback is enabled.
65 * NOTE: By reference parameters are cached and thus are not read until execution.
66 * This means you cannot push a pointer, change it, and push it again and expect
67 * two different values to come out.
69 * @param cell Address containing parameter value to push.
70 * @param flags Copy-back flags.
71 * @return Error code, if any.
73 virtual int PushCellByRef(cell_t *cell, int flags=SM_PARAM_COPYBACK) =0;
76 * @brief Pushes a float onto the current call.
78 * @param number Parameter value to push.
79 * @return Error code, if any.
81 virtual int PushFloat(float number) =0;
84 * @brief Pushes a float onto the current call by reference.
85 * NOTE: On Execute, the pointer passed will be modified if copyback is enabled.
86 * NOTE: By reference parameters are cached and thus are not read until execution.
87 * This means you cannot push a pointer, change it, and push it again and expect
88 * two different values to come out.
90 * @param number Parameter value to push.
91 & @param flags Copy-back flags.
92 * @return Error code, if any.
94 virtual int PushFloatByRef(float *number, int flags=SM_PARAM_COPYBACK) =0;
97 * @brief Pushes an array of cells onto the current call.
99 * On Execute, the pointer passed will be modified if non-NULL and copy-back
102 * By reference parameters are cached and thus are not read until execution.
103 * This means you cannot push a pointer, change it, and push it again and expect
104 * two different values to come out.
106 * @param inarray Array to copy, NULL if no initial array should be copied.
107 * @param cells Number of cells to allocate and optionally read from the input array.
108 * @param flags Whether or not changes should be copied back to the input array.
109 * @return Error code, if any.
111 virtual int PushArray(cell_t *inarray, unsigned int cells, int flags=0) =0;
114 * @brief Pushes a string onto the current call.
116 * @param string String to push.
117 * @return Error code, if any.
119 virtual int PushString(const char *string) =0;
122 * @brief Pushes a string or string buffer.
123 * NOTE: On Execute, the pointer passed will be modified if copy-back is enabled.
125 * @param buffer Pointer to string buffer.
126 * @param length Length of buffer.
127 * @param sz_flags String flags.
128 * @param cp_flags Copy-back flags.
129 * @return Error code, if any.
131 virtual int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags) =0;
134 * @brief Cancels a function call that is being pushed but not yet executed.
135 * This can be used be reset for CallFunction() use.
137 virtual void Cancel() =0;
142 * @brief Encapsulates a function call in a plugin.
144 * NOTE: Function calls must be atomic to one execution context.
145 * NOTE: This object should not be deleted. It lives for the lifetime of the plugin.
147 class IPluginFunction : public ICallable
151 * @brief Executes the forward, resets the pushed parameter list, and performs any copybacks.
153 * @param result Pointer to store return value in.
154 * @return Error code, if any.
156 virtual int Execute(cell_t *result) =0;
159 * @brief Executes the function with the given parameter array.
160 * Parameters are read in forward order (i.e. index 0 is parameter #1)
161 * NOTE: You will get an error if you attempt to use CallFunction() with
162 * previously pushed parameters.
164 * @param params Array of cell parameters.
165 * @param num_params Number of parameters to push.
166 * @param result Pointer to store result of function on return.
167 * @return SourcePawn error code (if any).
169 virtual int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result) =0;
172 * @brief Returns which plugin this function belongs to.
174 * @return IPluginContext pointer to parent plugin.
176 virtual IPluginContext *GetParentContext() =0;
179 * @brief Returns whether the parent plugin is paused.
181 * @return True if runnable, false otherwise.
183 virtual bool IsRunnable() =0;
188 * @brief Interface to managing a debug context at runtime.
190 class IPluginDebugInfo
194 * @brief Given a code pointer, finds the file it is associated with.
196 * @param addr Code address offset.
197 * @param filename Pointer to store filename pointer in.
199 virtual int LookupFile(ucell_t addr, const char **filename) =0;
202 * @brief Given a code pointer, finds the function it is associated with.
204 * @param addr Code address offset.
205 * @param name Pointer to store function name pointer in.
207 virtual int LookupFunction(ucell_t addr, const char **name) =0;
210 * @brief Given a code pointer, finds the line it is associated with.
212 * @param addr Code address offset.
213 * @param line Pointer to store line number in.
215 virtual int LookupLine(ucell_t addr, uint32_t *line) =0;
219 * @brief Interface to managing a context at runtime.
224 /** Virtual destructor */
225 virtual ~IPluginContext() { };
228 * @brief Returns the parent IVirtualMachine.
230 * @return Parent virtual machine pointer.
232 virtual IVirtualMachine *GetVirtualMachine() =0;
235 * @brief Returns the child sp_context_t structure.
237 * @return Child sp_context_t structure.
239 virtual sp_context_t *GetContext() =0;
242 * @brief Returns true if the plugin is in debug mode.
244 * @return True if in debug mode, false otherwise.
246 virtual bool IsDebugging() =0;
249 * @brief Installs a debug break and returns the old one, if any.
250 * This will fail if the plugin is not debugging.
252 * @param newpfn New function pointer.
253 * @param oldpfn Pointer to retrieve old function pointer.
255 virtual int SetDebugBreak(SPVM_DEBUGBREAK newpfn, SPVM_DEBUGBREAK *oldpfn) =0;
258 * @brief Returns debug info.
260 * @return IPluginDebugInfo, or NULL if no debug info found.
262 virtual IPluginDebugInfo *GetDebugInfo() =0;
265 * @brief Allocates memory on the secondary stack of a plugin.
266 * Note that although called a heap, it is in fact a stack.
268 * @param cells Number of cells to allocate.
269 * @param local_addr Will be filled with data offset to heap.
270 * @param phys_addr Physical address to heap memory.
272 virtual int HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr) =0;
275 * @brief Pops a heap address off the heap stack. Use this to free memory allocated with
277 * Note that in SourcePawn, the heap is in fact a bottom-up stack. Deallocations
278 * with this native should be performed in precisely the REVERSE order.
280 * @param local_addr Local address to free.
282 virtual int HeapPop(cell_t local_addr) =0;
285 * @brief Releases a heap address using a different method than SP_HeapPop().
286 * This allows you to release in any order. However, if you allocate N
287 * objects, release only some of them, then begin allocating again,
288 * you cannot go back and starting freeing the originals.
289 * In other words, for each chain of allocations, if you start deallocating,
290 * then allocating more in a chain, you must only deallocate from the current
291 * allocation chain. This is basically HeapPop() except on a larger scale.
293 * @param local_addr Local address to free.
295 virtual int HeapRelease(cell_t local_addr) =0;
298 * @brief Finds a native by name.
300 * @param name Name of native.
301 * @param index Optionally filled with native index number.
303 virtual int FindNativeByName(const char *name, uint32_t *index) =0;
306 * @brief Gets native info by index.
308 * @param index Index number of native.
309 * @param native Optionally filled with pointer to native structure.
311 virtual int GetNativeByIndex(uint32_t index, sp_native_t **native) =0;
314 * @brief Gets the number of natives.
316 * @return Filled with the number of natives.
318 virtual uint32_t GetNativesNum() =0;
321 * @brief Finds a public function by name.
323 * @param name Name of public
324 * @param index Optionally filled with public index number.
326 virtual int FindPublicByName(const char *name, uint32_t *index) =0;
329 * @brief Gets public function info by index.
331 * @param index Public function index number.
332 * @param publicptr Optionally filled with pointer to public structure.
334 virtual int GetPublicByIndex(uint32_t index, sp_public_t **publicptr) =0;
337 * @brief Gets the number of public functions.
339 * @return Filled with the number of public functions.
341 virtual uint32_t GetPublicsNum() =0;
344 * @brief Gets public variable info by index.
346 * @param index Public variable index number.
347 * @param pubvar Optionally filled with pointer to pubvar structure.
349 virtual int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar) =0;
352 * @brief Finds a public variable by name.
354 * @param name Name of pubvar
355 * @param index Optionally filled with pubvar index number.
357 virtual int FindPubvarByName(const char *name, uint32_t *index) =0;
360 * @brief Gets the addresses of a public variable.
362 * @param index Index of public variable.
363 * @param local_addr Address to store local address in.
364 * @param phys_addr Address to store physically relocated in.
366 virtual int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) =0;
369 * @brief Returns the number of public variables.
371 * @return Number of public variables.
373 virtual uint32_t GetPubVarsNum() =0;
376 * @brief Round-about method of converting a plugin reference to a physical address
378 * @param local_addr Local address in plugin.
379 * @param phys_addr Optionally filled with relocated physical address.
381 virtual int LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr) =0;
384 * @brief Converts a local address to a physical string.
386 * @param local_addr Local address in plugin.
387 * @param addr Destination output pointer.
389 virtual int LocalToString(cell_t local_addr, char **addr) =0;
392 * @brief Converts a physical string to a local address.
394 * @param local_addr Local address in plugin.
395 * @param bytes Number of chars to write, including NULL terminator.
396 * @param source Source string to copy.
398 virtual int StringToLocal(cell_t local_addr, size_t bytes, const char *source) =0;
401 * @brief Converts a physical UTF-8 string to a local address.
402 * This function is the same as the ANSI version, except it will copy the maximum number of characters possible
403 * without accidentally chopping a multi-byte character.
405 * @param local_addr Local address in plugin.
406 * @param maxbytes Number of bytes to write, including NULL terminator.
407 * @param source Source string to copy.
408 * @param wrtnbytes Optionally set to the number of actual bytes written.
410 virtual int StringToLocalUTF8(cell_t local_addr,
413 size_t *wrtnbytes) =0;
416 * @brief Pushes a cell onto the stack. Increases the parameter count by one.
418 * @param value Cell value.
420 virtual int PushCell(cell_t value) =0;
423 * @brief Pushes an array of cells onto the stack. Increases the parameter count by one.
424 * If the function returns an error it will fail entirely, releasing anything allocated in the process.
425 * Note that this does not release the heap, so you should release it after
428 * @param local_addr Filled with local address to release.
429 * @param phys_addr Optionally filled with physical address of new array.
430 * @param array Cell array to copy.
431 * @param numcells Number of cells in the array to copy.
433 virtual int PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells) =0;
436 * @brief Pushes a string onto the stack (by reference) and increases the parameter count by one.
437 * Note that this does not release the heap, so you should release it after
440 * @param local_addr Filled with local address to release.
441 * @param phys_addr Optionally filled with physical address of new array.
442 * @param string Source string to push.
444 virtual int PushString(cell_t *local_addr, char **phys_addr, const char *string) =0;
447 * @brief Individually pushes each cell of an array of cells onto the stack. Increases the
448 * parameter count by the number of cells pushed.
449 * If the function returns an error it will fail entirely, releasing anything allocated in the process.
451 * @param array Array of cells to read from.
452 * @param numcells Number of cells to read.
454 virtual int PushCellsFromArray(cell_t array[], unsigned int numcells) =0;
457 * @brief Binds a list of native names and their function pointers to a context.
458 * If num is 0, the list is read until an entry with a NULL name is reached.
459 * If overwrite is non-zero, already registered natives will be overwritten.
461 * @param natives Array of natives.
462 * @param num Number of natives in array.
463 * @param overwrite Toggles overwrite.
465 virtual int BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite) =0;
468 * @brief Binds a single native. Overwrites any existing bind.
469 * If the context does not contain the native that will be binded the function will return
470 * with a SP_ERROR_NOT_FOUND error.
472 * @param native Pointer to native.
474 virtual int BindNative(const sp_nativeinfo_t *native) =0;
477 * @brief Binds a single native to any non-registered native.
479 * @param native Native to bind.
481 virtual int BindNativeToAny(SPVM_NATIVE_FUNC native) =0;
484 * @brief Executes a function ID located in this context.
486 * @param code_addr Address to execute at.
487 * @param result Pointer to store the return value (required).
488 * @return Error code (if any) from the VM.
490 virtual int Execute(uint32_t code_addr, cell_t *result) =0;
493 * @brief Throws a error and halts any current execution.
495 * @param error The error number to set.
496 * @param msg Custom error message format. NULL to use default.
497 * @param ... Message format arguments, if any.
498 * @return 0 for convenience.
500 virtual cell_t ThrowNativeErrorEx(int error, const char *msg, ...) =0;
503 * @brief Throws a generic native error and halts any current execution.
505 * @param msg Custom error message format. NULL to set no message.
506 * @param ... Message format arguments, if any.
507 * @return 0 for convenience.
509 virtual cell_t ThrowNativeError(const char *msg, ...) =0;
512 * @brief Returns a function by name.
514 * @param public_name Name of the function.
515 * @return A new IPluginFunction pointer, NULL if not found.
517 virtual IPluginFunction *GetFunctionByName(const char *public_name) =0;
520 * @brief Returns a function by its id.
522 * @param func_id Function ID.
523 * @return A new IPluginFunction pointer, NULL if not found.
525 virtual IPluginFunction *GetFunctionById(funcid_t func_id) =0;
527 #if defined SOURCEMOD_BUILD
529 * @brief Returns the identity token for this context.
530 * Note: This is a helper function for native calls and the Handle System.
532 * @return Identity token.
534 virtual SourceMod::IdentityToken_t *GetIdentity() =0;
540 * @brief Information about a position in a call stack.
544 const char *filename; /**< NULL if not found */
545 unsigned int line; /**< 0 if not found */
546 const char *function; /**< NULL if not found */
550 * @brief Retrieves error information from a debug hook.
556 * @brief Returns the integer error code.
558 * @return Integer error code.
560 virtual int GetErrorCode() =0;
563 * @brief Returns a string describing the error.
565 * @return Error string.
567 virtual const char *GetErrorString() =0;
570 * @brief Returns whether debug info is available.
572 * @return True if debug info is available, false otherwise.
574 virtual bool DebugInfoAvailable() =0;
577 * @brief Returns a custom error message.
579 * @return A pointer to a custom error message, or NULL otherwise.
581 virtual const char *GetCustomErrorString() =0;
584 * @brief Returns trace info for a specific point in the backtrace, if any.
585 * The next subsequent call to GetTraceInfo() will return the next item in the call stack.
586 * Calls are retrieved in descending order (i.e. the first item is at the top of the stack/call sequence).
588 * @param trace An ErrorTraceInfo buffer to store information (NULL to ignore).
589 * @return True if successful, false if there are no more traces.
591 virtual bool GetTraceInfo(CallStackInfo *trace) =0;
594 * @brief Resets the trace to its original position (the call on the top of the stack).
596 virtual void ResetTrace() =0;
599 * @brief Retrieves the name of the last native called.
600 * Returns NULL if there was no native that caused the error.
602 * @param index Optional pointer to store index.
603 * @return Native name, or NULL if none.
605 virtual const char *GetLastNative(uint32_t *index) =0;
610 * @brief Provides callbacks for debug information.
615 virtual void OnContextExecuteError(IPluginContext *ctx, IContextTrace *error) =0;
620 * @brief Contains helper functions used by VMs and the host app
622 class ISourcePawnEngine
626 * @brief Loads a named file from a file pointer.
627 * Note: Using this means the memory will be allocated by the VM.
629 * @param fp File pointer. May be at any offset. Not closed on return.
630 * @param err Optional error code pointer.
631 * @return A new plugin structure.
633 virtual sp_plugin_t *LoadFromFilePointer(FILE *fp, int *err) =0;
636 * @brief Loads a file from a base memory address.
638 * @param base Base address of the plugin's memory region.
639 * @param plugin If NULL, a new plugin pointer is returned.
640 * Otherwise, the passed pointer is used.
641 * @param err Optional error code pointer.
642 * @return The resulting plugin pointer.
644 virtual sp_plugin_t *LoadFromMemory(void *base, sp_plugin_t *plugin, int *err) =0;
647 * Frees all of the memory associated with a plugin file.
648 * If allocated using SP_LoadFromMemory, the base and plugin pointer
649 * itself are not freed (so this may end up doing nothing).
651 virtual int FreeFromMemory(sp_plugin_t *plugin) =0;
654 * @brief Allocates large blocks of temporary memory.
656 * @param size Size of memory to allocate.
657 * @return Pointer to memory, NULL if allocation failed.
659 virtual void *BaseAlloc(size_t size) =0;
662 * @brief Frees memory allocated with BaseAlloc.
664 * @param memory Memory address to free.
666 virtual void BaseFree(void *memory) =0;
669 * @brief Allocates executable memory.
671 * @param size Size of memory to allocate.
672 * @return Pointer to memory, NULL if allocation failed.
674 virtual void *ExecAlloc(size_t size) =0;
677 * @brief Frees executable memory.
679 * @param address Address to free.
681 virtual void ExecFree(void *address) =0;
684 * @brief Sets the debug listener. This should only be called once.
685 * If called successively (using manual chaining), only the last function should
686 * attempt to call back into the same plugin. Otherwise, globally cached states
687 * can be accidentally overwritten.
689 * @param listener Pointer to an IDebugListener.
690 * @return Old IDebugListener, or NULL if none.
692 virtual IDebugListener *SetDebugListener(IDebugListener *listener) =0;
695 * @brief Returns the number of plugins on the call stack.
697 * @return Number of contexts in the call stack.
699 virtual unsigned int GetContextCallCount() =0;
704 * @brief Dummy class for encapsulating private compilation data.
709 /** Virtual destructor */
710 virtual ~ICompilation() { };
715 * @brief Outlines the interface a Virtual Machine (JIT) must expose
717 class IVirtualMachine
721 * @brief Returns the current API version.
723 virtual unsigned int GetAPIVersion() =0;
726 * @brief Returns the string name of a VM implementation.
728 virtual const char *GetVMName() =0;
731 * @brief Begins a new compilation
733 * @param plugin Pointer to a plugin structure.
734 * @return New compilation pointer.
736 virtual ICompilation *StartCompilation(sp_plugin_t *plugin) =0;
739 * @brief Sets a compilation option.
741 * @param co Pointer to a compilation.
742 * @param key Option key name.
743 * @param val Option value string.
744 * @return True if option could be set, false otherwise.
746 virtual bool SetCompilationOption(ICompilation *co, const char *key, const char *val) =0;
749 * @brief Finalizes a compilation into a new sp_context_t.
750 * Note: This will free the ICompilation pointer.
752 * @param co Compilation pointer.
753 * @param err Filled with error code on exit.
754 * @return New plugin context.
756 virtual sp_context_t *CompileToContext(ICompilation *co, int *err) =0;
759 * @brief Aborts a compilation and frees the ICompilation pointer.
761 * @param co Compilation pointer.
763 virtual void AbortCompilation(ICompilation *co) =0;
766 * @brief Frees any internal variable usage on a context.
768 * @param ctx Context structure pointer.
770 virtual void FreeContext(sp_context_t *ctx) =0;
773 * @brief Calls the "execute" function on a context.
775 * @param ctx Executes a function in a context.
776 * @param code_addr Index into the code section.
777 * @param result Pointer to store result into.
778 * @return Error code (if any).
780 virtual int ContextExecute(sp_context_t *ctx, uint32_t code_addr, cell_t *result) =0;
783 * @brief Given a context and a code address, returns the index of the function.
785 * @param ctx Context to search.
786 * @param code_addr Index into the code section.
787 * @param result Pointer to store result into.
788 * @return True if code index is valid, false otherwise.
790 virtual bool FunctionLookup(const sp_context_t *ctx, uint32_t code_addr, unsigned int *result) =0;
793 * @brief Returns the number of functions defined in the context.
795 * @param ctx Context to search.
796 * @return Number of functions.
798 virtual unsigned int FunctionCount(const sp_context_t *ctx) =0;
801 * @brief Returns a version string.
803 * @return Versioning string.
805 virtual const char *GetVersionString() =0;
808 * @brief Returns a string describing optimizations.
810 * @return String describing CPU specific optimizations.
812 virtual const char *GetCPUOptimizations() =0;
815 * @brief Given a context and a p-code address, returns the index of the function.
817 * @param ctx Context to search.
818 * @param code_addr Index into the p-code section.
819 * @param result Pointer to store result into.
820 * @return True if code index is valid, false otherwise.
822 virtual bool FunctionPLookup(const sp_context_t *ctx, uint32_t code_addr, unsigned int *result) =0;
825 * @brief Creates a fake native and binds it to a general callback function.
827 * @param callback Callback function to bind the native to.
828 * @param pData Private data to pass to the callback when the native is invoked.
829 * @return A new fake native function as a wrapper around the callback.
831 virtual SPVM_NATIVE_FUNC CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData) =0;
834 * @brief Destroys a fake native function wrapper.
836 * @param function Pointer to the fake native created by CreateFakeNative.
839 virtual void DestroyFakenative(SPVM_NATIVE_FUNC func) =0;
843 #endif //_INCLUDE_SOURCEPAWN_VM_API_H_