2 * ================================================================
3 * SourcePawn (C)2004-2007 AlliedModders LLC. All rights reserved.
4 * ================================================================
6 * This file is not open source and may not be copied without explicit
7 * written permission of AlliedModders LLC. This file may not be redistributed
8 * in whole or significant part.
9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
18 #include "sp_vm_api.h"
19 #include "sp_vm_basecontext.h"
20 #include "sp_vm_engine.h"
22 using namespace SourcePawn;
24 extern SourcePawnEngine g_SourcePawn;
26 #define CELLBOUNDMAX (INT_MAX/sizeof(cell_t))
27 #define STACKMARGIN ((cell_t)(16*sizeof(cell_t)))
29 int GlobalDebugBreak(sp_context_t *ctx, uint32_t frm, uint32_t cip)
31 g_SourcePawn.RunTracer(ctx, frm, cip);
36 BaseContext::BaseContext(sp_context_t *_ctx)
40 ctx->dbreak = GlobalDebugBreak;
43 m_funcsnum = ctx->vmbase->FunctionCount(ctx);
48 * Note: Since the m_plugin member will never change,
49 * it is safe to assume the function count will never change
51 if (m_funcsnum && m_priv_funcs == NULL)
53 m_priv_funcs = new CFunction *[m_funcsnum];
54 memset(m_priv_funcs, 0, sizeof(CFunction *) * m_funcsnum);
59 if (ctx->plugin->info.publics_num && m_pub_funcs == NULL)
61 m_pub_funcs = new CFunction *[ctx->plugin->info.publics_num];
62 memset(m_pub_funcs, 0, sizeof(CFunction *) * ctx->plugin->info.publics_num);
68 void BaseContext::FlushFunctionCache(bool remove)
72 for (uint32_t i=0; i<ctx->plugin->info.publics_num; i++)
76 delete m_pub_funcs[i];
77 m_pub_funcs[i] = NULL;
78 } else if (m_pub_funcs[i]) {
79 m_pub_funcs[i]->Invalidate();
86 for (unsigned int i=0; i<m_funcsnum; i++)
90 delete m_priv_funcs[i];
91 m_priv_funcs[i] = NULL;
92 } else if (m_priv_funcs[i]) {
93 m_priv_funcs[i]->Invalidate();
99 BaseContext::~BaseContext()
101 FlushFunctionCache(true);
102 delete [] m_pub_funcs;
104 delete [] m_priv_funcs;
108 void BaseContext::SetContext(sp_context_t *_ctx)
116 ctx->dbreak = GlobalDebugBreak;
117 FlushFunctionCache(false);
120 IVirtualMachine *BaseContext::GetVirtualMachine()
122 return (IVirtualMachine *)ctx->vmbase;
125 sp_context_t *BaseContext::GetContext()
130 bool BaseContext::IsDebugging()
132 return (ctx->flags & SPFLAG_PLUGIN_DEBUG);
135 int BaseContext::SetDebugBreak(SPVM_DEBUGBREAK newpfn, SPVM_DEBUGBREAK *oldpfn)
139 return SP_ERROR_NOTDEBUGGING;
142 *oldpfn = ctx->dbreak;
143 ctx->dbreak = newpfn;
145 return SP_ERROR_NONE;
148 IPluginDebugInfo *BaseContext::GetDebugInfo()
153 int BaseContext::Execute(uint32_t code_addr, cell_t *result)
155 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
157 return SP_ERROR_NOT_RUNNABLE;
160 IVirtualMachine *vm = (IVirtualMachine *)ctx->vmbase;
162 uint32_t pushcount = ctx->pushcount;
165 PushCell(pushcount++);
168 cell_t save_sp = ctx->sp;
169 cell_t save_hp = ctx->hp;
171 bool wasExec = m_InExec;
173 /* Clear the error state, if any */
174 ctx->n_err = SP_ERROR_NONE;
177 m_MsgCache[0] = '\0';
180 g_SourcePawn.PushTracer(ctx);
182 err = vm->ContextExecute(ctx, code_addr, result);
187 * :TODO: Calling from a plugin in here will erase the cached message...
188 * Should that be documented?
190 g_SourcePawn.PopTracer(err, m_CustomMsg ? m_MsgCache : NULL);
193 if (err == SP_ERROR_NONE)
195 assert(ctx->sp - pushcount * sizeof(cell_t) == save_sp);
196 assert(ctx->hp == save_hp);
199 if (err != SP_ERROR_NONE)
208 void BaseContext::SetErrorMessage(const char *msg, va_list ap)
212 vsnprintf(m_MsgCache, sizeof(m_MsgCache), msg, ap);
215 cell_t BaseContext::ThrowNativeErrorEx(int error, const char *msg, ...)
228 SetErrorMessage(msg, ap);
235 cell_t BaseContext::ThrowNativeError(const char *msg, ...)
242 ctx->n_err = SP_ERROR_NATIVE;
248 SetErrorMessage(msg, ap);
255 int BaseContext::HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr)
261 if (cells > CELLBOUNDMAX)
263 return SP_ERROR_ARAM;
266 assert(cells < CELLBOUNDMAX);
269 realmem = cells * sizeof(cell_t);
272 * Check if the space between the heap and stack is sufficient.
274 if ((cell_t)(ctx->sp - ctx->hp - realmem) < STACKMARGIN)
276 return SP_ERROR_HEAPLOW;
279 addr = (cell_t *)(ctx->memory + ctx->hp);
280 /* store size of allocation in cells */
281 *addr = (cell_t)cells;
283 ctx->hp += sizeof(cell_t);
285 *local_addr = ctx->hp;
294 return SP_ERROR_NONE;
297 int BaseContext::HeapPop(cell_t local_addr)
302 /* check the bounds of this address */
303 local_addr -= sizeof(cell_t);
304 if (local_addr < ctx->heap_base || local_addr >= ctx->sp)
306 return SP_ERROR_INVALID_ADDRESS;
309 addr = (cell_t *)(ctx->memory + local_addr);
310 cellcount = (*addr) * sizeof(cell_t);
311 /* check if this memory count looks valid */
312 if ((signed)(ctx->hp - cellcount - sizeof(cell_t)) != local_addr)
314 return SP_ERROR_INVALID_ADDRESS;
317 ctx->hp = local_addr;
319 return SP_ERROR_NONE;
323 int BaseContext::HeapRelease(cell_t local_addr)
325 if (local_addr < ctx->heap_base)
327 return SP_ERROR_INVALID_ADDRESS;
330 ctx->hp = local_addr - sizeof(cell_t);
332 return SP_ERROR_NONE;
335 int BaseContext::FindNativeByName(const char *name, uint32_t *index)
339 high = ctx->plugin->info.natives_num - 1;
341 for (uint32_t i=0; i<ctx->plugin->info.natives_num; i++)
343 if (strcmp(ctx->natives[i].name, name) == 0)
349 return SP_ERROR_NONE;
353 return SP_ERROR_NOT_FOUND;
356 int BaseContext::GetNativeByIndex(uint32_t index, sp_native_t **native)
358 if (index >= ctx->plugin->info.natives_num)
360 return SP_ERROR_INDEX;
365 *native = &(ctx->natives[index]);
368 return SP_ERROR_NONE;
372 uint32_t BaseContext::GetNativesNum()
374 return ctx->plugin->info.natives_num;
377 int BaseContext::FindPublicByName(const char *name, uint32_t *index)
382 high = ctx->plugin->info.publics_num - 1;
387 mid = (low + high) / 2;
388 diff = strcmp(ctx->publics[mid].name, name);
395 return SP_ERROR_NONE;
396 } else if (diff < 0) {
403 return SP_ERROR_NOT_FOUND;
406 int BaseContext::GetPublicByIndex(uint32_t index, sp_public_t **pblic)
408 if (index >= ctx->plugin->info.publics_num)
410 return SP_ERROR_INDEX;
415 *pblic = &(ctx->publics[index]);
418 return SP_ERROR_NONE;
421 uint32_t BaseContext::GetPublicsNum()
423 return ctx->plugin->info.publics_num;
426 int BaseContext::GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar)
428 if (index >= ctx->plugin->info.pubvars_num)
430 return SP_ERROR_INDEX;
435 *pubvar = &(ctx->pubvars[index]);
438 return SP_ERROR_NONE;
441 int BaseContext::FindPubvarByName(const char *name, uint32_t *index)
446 high = ctx->plugin->info.pubvars_num - 1;
451 mid = (low + high) / 2;
452 diff = strcmp(ctx->pubvars[mid].name, name);
459 return SP_ERROR_NONE;
460 } else if (diff < 0) {
467 return SP_ERROR_NOT_FOUND;
470 int BaseContext::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr)
472 if (index >= ctx->plugin->info.pubvars_num)
474 return SP_ERROR_INDEX;
477 *local_addr = ctx->plugin->info.pubvars[index].address;
478 *phys_addr = ctx->pubvars[index].offs;
480 return SP_ERROR_NONE;
483 uint32_t BaseContext::GetPubVarsNum()
485 return ctx->plugin->info.pubvars_num;
488 int BaseContext::BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite)
492 max = ctx->plugin->info.natives_num;
494 for (i=0; i<max; i++)
496 if ((ctx->natives[i].status == SP_NATIVE_BOUND) && !overwrite)
501 for (j=0; (natives[j].name) && (!num || j<num); j++)
503 if (!strcmp(ctx->natives[i].name, natives[j].name))
505 ctx->natives[i].pfn = natives[j].func;
506 ctx->natives[i].status = SP_NATIVE_BOUND;
511 return SP_ERROR_NONE;
514 int BaseContext::BindNative(const sp_nativeinfo_t *native)
519 if ((err = FindNativeByName(native->name, &index)) != SP_ERROR_NONE)
524 ctx->natives[index].pfn = native->func;
525 ctx->natives[index].status = SP_NATIVE_BOUND;
527 return SP_ERROR_NONE;
530 int BaseContext::BindNativeToAny(SPVM_NATIVE_FUNC native)
532 uint32_t nativesnum, i;
534 nativesnum = ctx->plugin->info.natives_num;
536 for (i=0; i<nativesnum; i++)
538 if (ctx->natives[i].status == SP_NATIVE_UNBOUND)
540 ctx->natives[i].pfn = native;
541 ctx->natives[i].status = SP_NATIVE_BOUND;
545 return SP_ERROR_NONE;
548 int BaseContext::LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr)
550 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
552 return SP_ERROR_INVALID_ADDRESS;
557 *phys_addr = (cell_t *)(ctx->memory + local_addr);
560 return SP_ERROR_NONE;
563 int BaseContext::PushCell(cell_t value)
565 if ((ctx->hp + STACKMARGIN) > (cell_t)(ctx->sp - sizeof(cell_t)))
567 return SP_ERROR_STACKLOW;
570 ctx->sp -= sizeof(cell_t);
571 *(cell_t *)(ctx->memory + ctx->sp) = value;
574 return SP_ERROR_NONE;
577 int BaseContext::PushCellsFromArray(cell_t array[], unsigned int numcells)
582 for (i=0; i<numcells; i++)
584 if ((err = PushCell(array[i])) != SP_ERROR_NONE)
586 ctx->sp += (cell_t)(i * sizeof(cell_t));
592 return SP_ERROR_NONE;
595 int BaseContext::PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells)
600 if ((err = HeapAlloc(numcells, local_addr, &ph_addr)) != SP_ERROR_NONE)
605 memcpy(ph_addr, array, numcells * sizeof(cell_t));
607 if ((err = PushCell(*local_addr)) != SP_ERROR_NONE)
609 HeapRelease(*local_addr);
615 *phys_addr = ph_addr;
618 return SP_ERROR_NONE;
621 int BaseContext::LocalToString(cell_t local_addr, char **addr)
623 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
625 return SP_ERROR_INVALID_ADDRESS;
627 *addr = (char *)(ctx->memory + local_addr);
629 return SP_ERROR_NONE;
632 int BaseContext::PushString(cell_t *local_addr, char **phys_addr, const char *string)
636 unsigned int len, numcells = ((len=strlen(string)) + sizeof(cell_t)) / sizeof(cell_t);
638 if ((err = HeapAlloc(numcells, local_addr, (cell_t **)&ph_addr)) != SP_ERROR_NONE)
643 memcpy(ph_addr, string, len);
646 if ((err = PushCell(*local_addr)) != SP_ERROR_NONE)
648 HeapRelease(*local_addr);
654 *phys_addr = ph_addr;
657 return SP_ERROR_NONE;
660 int BaseContext::StringToLocal(cell_t local_addr, size_t chars, const char *source)
665 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
667 return SP_ERROR_INVALID_ADDRESS;
670 len = strlen(source);
671 dest = (char *)(ctx->memory + local_addr);
673 if ((size_t)len >= chars)
679 return SP_ERROR_NONE;
682 memcpy(dest, source, len);
685 return SP_ERROR_NONE;
688 inline int __CheckValidChar(char *c)
693 for (count=1; (*c & 0xC0) == 0x80; count++)
718 if (bytecount != count)
726 int BaseContext::StringToLocalUTF8(cell_t local_addr, size_t maxbytes, const char *source, size_t *wrtnbytes)
730 bool needtocheck = false;
732 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
734 return SP_ERROR_INVALID_ADDRESS;
737 len = strlen(source);
738 dest = (char *)(ctx->memory + local_addr);
740 if ((size_t)len >= maxbytes)
747 return SP_ERROR_NONE;
750 memcpy(dest, source, len);
751 if ((dest[len-1] & 1<<7) && needtocheck)
753 len -= __CheckValidChar(dest+len-1);
762 return SP_ERROR_NONE;
765 #define USHR(x) ((unsigned int)(x)>>1)
767 int BaseContext::LookupFile(ucell_t addr, const char **filename)
771 high = ctx->plugin->debug.files_num;
774 while (high - low > 1)
776 mid = USHR(low + high);
777 if (ctx->files[mid].addr <= addr)
787 return SP_ERROR_NOT_FOUND;
790 *filename = ctx->files[low].name;
792 return SP_ERROR_NONE;
795 int BaseContext::LookupFunction(ucell_t addr, const char **name)
797 uint32_t iter, max = ctx->plugin->debug.syms_num;
799 for (iter=0; iter<max; iter++)
801 if ((ctx->symbols[iter].sym->ident == SP_SYM_FUNCTION)
802 && (ctx->symbols[iter].codestart <= addr)
803 && (ctx->symbols[iter].codeend > addr))
811 return SP_ERROR_NOT_FOUND;
814 *name = ctx->symbols[iter].name;
816 return SP_ERROR_NONE;
819 int BaseContext::LookupLine(ucell_t addr, uint32_t *line)
823 high = ctx->plugin->debug.lines_num;
826 while (high - low > 1)
828 mid = USHR(low + high);
829 if (ctx->lines[mid].addr <= addr)
839 return SP_ERROR_NOT_FOUND;
842 /* Since the CIP occurs BEFORE the line, we have to add one */
843 *line = ctx->lines[low].line + 1;
845 return SP_ERROR_NONE;
848 IPluginFunction *BaseContext::GetFunctionById(funcid_t func_id)
850 CFunction *pFunc = NULL;
855 if (func_id >= ctx->plugin->info.publics_num)
859 pFunc = m_pub_funcs[func_id];
862 m_pub_funcs[func_id] = new CFunction(ctx->publics[func_id].code_offs, this);
863 pFunc = m_pub_funcs[func_id];
864 } else if (pFunc->IsInvalidated()) {
865 pFunc->Set(ctx->publics[func_id].code_offs, this);
868 /* :TODO: currently not used */
872 if (!g_pVM->FunctionLookup(ctx, func_id, &index))
876 pFunc = m_priv_funcs[func_id];
879 m_priv_funcs[func_id] = new CFunction(save, this);
880 pFunc = m_priv_funcs[func_id];
889 IPluginFunction *BaseContext::GetFunctionByName(const char *public_name)
893 if (FindPublicByName(public_name, &index) != SP_ERROR_NONE)
898 CFunction *pFunc = m_pub_funcs[index];
901 sp_public_t *pub = NULL;
902 GetPublicByIndex(index, &pub);
905 m_pub_funcs[index] = new CFunction(pub->code_offs, this);
907 pFunc = m_pub_funcs[index];
908 } else if (pFunc->IsInvalidated()) {
909 sp_public_t *pub = NULL;
910 GetPublicByIndex(index, &pub);
913 pFunc->Set(pub->code_offs, this);
922 #if defined SOURCEMOD_BUILD
923 SourceMod::IdentityToken_t *BaseContext::GetIdentity()
928 void BaseContext::SetIdentity(SourceMod::IdentityToken_t *token)