3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
36 #include "sp_vm_api.h"
37 #include "sp_vm_basecontext.h"
38 #include "sp_vm_engine.h"
40 #ifdef SOURCEMOD_BUILD
42 #include "DebugReporter.h"
45 using namespace SourcePawn;
47 extern SourcePawnEngine g_SourcePawn;
49 #define CELLBOUNDMAX (INT_MAX/sizeof(cell_t))
50 #define STACKMARGIN ((cell_t)(16*sizeof(cell_t)))
52 int GlobalDebugBreak(sp_context_t *ctx, uint32_t frm, uint32_t cip)
54 g_SourcePawn.RunTracer(ctx, frm, cip);
59 BaseContext::BaseContext(sp_context_t *_ctx)
63 ctx->dbreak = GlobalDebugBreak;
66 m_funcsnum = ctx->vmbase->FunctionCount(ctx);
74 * Note: Since the m_plugin member will never change,
75 * it is safe to assume the function count will never change
77 if (m_funcsnum && m_priv_funcs == NULL)
79 m_priv_funcs = new CFunction *[m_funcsnum];
80 memset(m_priv_funcs, 0, sizeof(CFunction *) * m_funcsnum);
86 if (ctx->plugin->info.publics_num && m_pub_funcs == NULL)
88 m_pub_funcs = new CFunction *[ctx->plugin->info.publics_num];
89 memset(m_pub_funcs, 0, sizeof(CFunction *) * ctx->plugin->info.publics_num);
94 /* Initialize the null references */
96 if (FindPubvarByName("NULL_VECTOR", &index) == SP_ERROR_NONE)
99 GetPubvarByIndex(index, &pubvar);
100 m_pNullVec = pubvar->offs;
105 if (FindPubvarByName("NULL_STRING", &index) == SP_ERROR_NONE)
108 GetPubvarByIndex(index, &pubvar);
109 m_pNullString = pubvar->offs;
111 m_pNullString = NULL;
115 void BaseContext::FlushFunctionCache()
119 for (uint32_t i=0; i<ctx->plugin->info.publics_num; i++)
121 delete m_pub_funcs[i];
122 m_pub_funcs[i] = NULL;
129 for (unsigned int i=0; i<m_funcsnum; i++)
131 delete m_priv_funcs[i];
132 m_priv_funcs[i] = NULL;
138 void BaseContext::RefreshFunctionCache()
143 for (uint32_t i=0; i<ctx->plugin->info.publics_num; i++)
149 if (GetPublicByIndex(i, &pub) != SP_ERROR_NONE)
153 m_pub_funcs[i]->Set(pub->code_offs, this, pub->funcid);
160 for (unsigned int i=0; i<m_funcsnum; i++)
162 if (!m_priv_funcs[i])
172 BaseContext::~BaseContext()
174 FlushFunctionCache();
175 delete [] m_pub_funcs;
178 delete [] m_priv_funcs;
183 void BaseContext::SetContext(sp_context_t *_ctx)
191 ctx->dbreak = GlobalDebugBreak;
192 RefreshFunctionCache();
195 IVirtualMachine *BaseContext::GetVirtualMachine()
197 return (IVirtualMachine *)ctx->vmbase;
200 sp_context_t *BaseContext::GetContext()
205 bool BaseContext::IsDebugging()
207 return (ctx->flags & SPFLAG_PLUGIN_DEBUG);
210 int BaseContext::SetDebugBreak(SPVM_DEBUGBREAK newpfn, SPVM_DEBUGBREAK *oldpfn)
214 return SP_ERROR_NOTDEBUGGING;
217 *oldpfn = ctx->dbreak;
218 ctx->dbreak = newpfn;
220 return SP_ERROR_NONE;
223 IPluginDebugInfo *BaseContext::GetDebugInfo()
232 int BaseContext::Execute(uint32_t code_addr, cell_t *result)
234 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
236 return SP_ERROR_NOT_RUNNABLE;
239 /* tada, prevent a crash */
240 cell_t _ignore_result;
243 result = &_ignore_result;
246 IVirtualMachine *vm = (IVirtualMachine *)ctx->vmbase;
248 uint32_t pushcount = ctx->pushcount;
251 if ((err = PushCell(pushcount++)) != SP_ERROR_NONE)
253 #if defined SOURCEMOD_BUILD
254 g_DbgReporter.GenerateCodeError(this, code_addr, err, "Stack error; cannot complete execution!");
256 return SP_ERROR_NOT_RUNNABLE;
260 cell_t save_sp = ctx->sp + (pushcount * sizeof(cell_t));
261 cell_t save_hp = ctx->hp;
262 uint32_t n_idx = ctx->n_idx;
264 bool wasExec = m_InExec;
266 /* Clear the error state, if any */
267 ctx->n_err = SP_ERROR_NONE;
270 m_MsgCache[0] = '\0';
273 g_SourcePawn.PushTracer(ctx);
275 err = vm->ContextExecute(ctx, code_addr, result);
280 * :TODO: Calling from a plugin in here will erase the cached message...
281 * Should that be documented?
283 g_SourcePawn.PopTracer(err, m_CustomMsg ? m_MsgCache : NULL);
285 #if defined SOURCEMOD_BUILD
286 if (err == SP_ERROR_NONE)
288 if (ctx->sp != save_sp)
290 g_DbgReporter.GenerateCodeError(this,
293 "Stack leak detected: sp:%d should be %d!",
297 if (ctx->hp != save_hp)
299 g_DbgReporter.GenerateCodeError(this,
302 "Heap leak detected: sp:%d should be %d!",
309 if (err != SP_ERROR_NONE)
316 ctx->n_err = SP_ERROR_NONE;
317 m_MsgCache[0] = '\0';
323 void BaseContext::SetErrorMessage(const char *msg, va_list ap)
327 vsnprintf(m_MsgCache, sizeof(m_MsgCache), msg, ap);
330 cell_t BaseContext::ThrowNativeErrorEx(int error, const char *msg, ...)
343 SetErrorMessage(msg, ap);
350 cell_t BaseContext::ThrowNativeError(const char *msg, ...)
357 ctx->n_err = SP_ERROR_NATIVE;
363 SetErrorMessage(msg, ap);
370 int BaseContext::HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr)
376 if (cells > CELLBOUNDMAX)
378 return SP_ERROR_ARAM;
381 assert(cells < CELLBOUNDMAX);
384 realmem = cells * sizeof(cell_t);
387 * Check if the space between the heap and stack is sufficient.
389 if ((cell_t)(ctx->sp - ctx->hp - realmem) < STACKMARGIN)
391 return SP_ERROR_HEAPLOW;
394 addr = (cell_t *)(ctx->memory + ctx->hp);
395 /* store size of allocation in cells */
396 *addr = (cell_t)cells;
398 ctx->hp += sizeof(cell_t);
400 *local_addr = ctx->hp;
409 return SP_ERROR_NONE;
412 int BaseContext::HeapPop(cell_t local_addr)
417 /* check the bounds of this address */
418 local_addr -= sizeof(cell_t);
419 if (local_addr < ctx->heap_base || local_addr >= ctx->sp)
421 return SP_ERROR_INVALID_ADDRESS;
424 addr = (cell_t *)(ctx->memory + local_addr);
425 cellcount = (*addr) * sizeof(cell_t);
426 /* check if this memory count looks valid */
427 if ((signed)(ctx->hp - cellcount - sizeof(cell_t)) != local_addr)
429 return SP_ERROR_INVALID_ADDRESS;
432 ctx->hp = local_addr;
434 return SP_ERROR_NONE;
438 int BaseContext::HeapRelease(cell_t local_addr)
440 if (local_addr < ctx->heap_base)
442 return SP_ERROR_INVALID_ADDRESS;
445 ctx->hp = local_addr - sizeof(cell_t);
447 return SP_ERROR_NONE;
450 int BaseContext::FindNativeByName(const char *name, uint32_t *index)
454 high = ctx->plugin->info.natives_num - 1;
456 for (uint32_t i=0; i<ctx->plugin->info.natives_num; i++)
458 if (strcmp(ctx->natives[i].name, name) == 0)
464 return SP_ERROR_NONE;
468 return SP_ERROR_NOT_FOUND;
471 int BaseContext::GetNativeByIndex(uint32_t index, sp_native_t **native)
473 if (index >= ctx->plugin->info.natives_num)
475 return SP_ERROR_INDEX;
480 *native = &(ctx->natives[index]);
483 return SP_ERROR_NONE;
487 uint32_t BaseContext::GetNativesNum()
489 return ctx->plugin->info.natives_num;
492 int BaseContext::FindPublicByName(const char *name, uint32_t *index)
497 high = ctx->plugin->info.publics_num - 1;
502 mid = (low + high) / 2;
503 diff = strcmp(ctx->publics[mid].name, name);
510 return SP_ERROR_NONE;
511 } else if (diff < 0) {
518 return SP_ERROR_NOT_FOUND;
521 int BaseContext::GetPublicByIndex(uint32_t index, sp_public_t **pblic)
523 if (index >= ctx->plugin->info.publics_num)
525 return SP_ERROR_INDEX;
530 *pblic = &(ctx->publics[index]);
533 return SP_ERROR_NONE;
536 uint32_t BaseContext::GetPublicsNum()
538 return ctx->plugin->info.publics_num;
541 int BaseContext::GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar)
543 if (index >= ctx->plugin->info.pubvars_num)
545 return SP_ERROR_INDEX;
550 *pubvar = &(ctx->pubvars[index]);
553 return SP_ERROR_NONE;
556 int BaseContext::FindPubvarByName(const char *name, uint32_t *index)
561 high = ctx->plugin->info.pubvars_num - 1;
566 mid = (low + high) / 2;
567 diff = strcmp(ctx->pubvars[mid].name, name);
574 return SP_ERROR_NONE;
575 } else if (diff < 0) {
582 return SP_ERROR_NOT_FOUND;
585 int BaseContext::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr)
587 if (index >= ctx->plugin->info.pubvars_num)
589 return SP_ERROR_INDEX;
592 *local_addr = ctx->plugin->info.pubvars[index].address;
593 *phys_addr = ctx->pubvars[index].offs;
595 return SP_ERROR_NONE;
598 uint32_t BaseContext::GetPubVarsNum()
600 return ctx->plugin->info.pubvars_num;
603 int BaseContext::BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite)
607 max = ctx->plugin->info.natives_num;
609 for (i=0; i<max; i++)
611 if ((ctx->natives[i].status == SP_NATIVE_BOUND) && !overwrite)
616 for (j=0; (natives[j].name) && (!num || j<num); j++)
618 if (!strcmp(ctx->natives[i].name, natives[j].name))
620 ctx->natives[i].pfn = natives[j].func;
621 ctx->natives[i].status = SP_NATIVE_BOUND;
626 return SP_ERROR_NONE;
629 int BaseContext::BindNative(const sp_nativeinfo_t *native)
634 if ((err = FindNativeByName(native->name, &index)) != SP_ERROR_NONE)
639 ctx->natives[index].pfn = native->func;
640 ctx->natives[index].status = SP_NATIVE_BOUND;
642 return SP_ERROR_NONE;
645 int BaseContext::BindNativeToAny(SPVM_NATIVE_FUNC native)
647 uint32_t nativesnum, i;
649 nativesnum = ctx->plugin->info.natives_num;
651 for (i=0; i<nativesnum; i++)
653 if (ctx->natives[i].status == SP_NATIVE_UNBOUND)
655 ctx->natives[i].pfn = native;
656 ctx->natives[i].status = SP_NATIVE_BOUND;
660 return SP_ERROR_NONE;
663 int BaseContext::LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr)
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;
672 *phys_addr = (cell_t *)(ctx->memory + local_addr);
675 return SP_ERROR_NONE;
678 int BaseContext::PushCell(cell_t value)
680 if ((ctx->hp + STACKMARGIN) > (cell_t)(ctx->sp - sizeof(cell_t)))
682 return SP_ERROR_STACKLOW;
685 ctx->sp -= sizeof(cell_t);
686 *(cell_t *)(ctx->memory + ctx->sp) = value;
689 return SP_ERROR_NONE;
692 int BaseContext::PushCellsFromArray(cell_t array[], unsigned int numcells)
697 for (i=0; i<numcells; i++)
699 if ((err = PushCell(array[i])) != SP_ERROR_NONE)
701 ctx->sp += (cell_t)(i * sizeof(cell_t));
707 return SP_ERROR_NONE;
710 int BaseContext::PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells)
715 if ((err = HeapAlloc(numcells, local_addr, &ph_addr)) != SP_ERROR_NONE)
720 memcpy(ph_addr, array, numcells * sizeof(cell_t));
722 if ((err = PushCell(*local_addr)) != SP_ERROR_NONE)
724 HeapRelease(*local_addr);
730 *phys_addr = ph_addr;
733 return SP_ERROR_NONE;
736 int BaseContext::LocalToString(cell_t local_addr, char **addr)
738 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
740 return SP_ERROR_INVALID_ADDRESS;
742 *addr = (char *)(ctx->memory + local_addr);
744 return SP_ERROR_NONE;
747 int BaseContext::PushString(cell_t *local_addr, char **phys_addr, const char *string)
751 unsigned int len, numcells = ((len=strlen(string)) + sizeof(cell_t)) / sizeof(cell_t);
753 if ((err = HeapAlloc(numcells, local_addr, (cell_t **)&ph_addr)) != SP_ERROR_NONE)
758 memcpy(ph_addr, string, len);
761 if ((err = PushCell(*local_addr)) != SP_ERROR_NONE)
763 HeapRelease(*local_addr);
769 *phys_addr = ph_addr;
772 return SP_ERROR_NONE;
775 int BaseContext::StringToLocal(cell_t local_addr, size_t bytes, const char *source)
780 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
782 return SP_ERROR_INVALID_ADDRESS;
787 return SP_ERROR_NONE;
790 len = strlen(source);
791 dest = (char *)(ctx->memory + local_addr);
798 memcpy(dest, source, len);
801 return SP_ERROR_NONE;
804 inline int __CheckValidChar(char *c)
809 for (count=1; (*c & 0xC0) == 0x80; count++)
834 if (bytecount != count)
842 int BaseContext::StringToLocalUTF8(cell_t local_addr, size_t maxbytes, const char *source, size_t *wrtnbytes)
846 bool needtocheck = false;
848 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
850 return SP_ERROR_INVALID_ADDRESS;
855 return SP_ERROR_NONE;
858 len = strlen(source);
859 dest = (char *)(ctx->memory + local_addr);
861 if ((size_t)len >= maxbytes)
867 memcpy(dest, source, len);
868 if ((dest[len-1] & 1<<7) && needtocheck)
870 len -= __CheckValidChar(dest+len-1);
879 return SP_ERROR_NONE;
882 #define USHR(x) ((unsigned int)(x)>>1)
884 int BaseContext::LookupFile(ucell_t addr, const char **filename)
888 high = ctx->plugin->debug.files_num;
891 while (high - low > 1)
893 mid = USHR(low + high);
894 if (ctx->files[mid].addr <= addr)
904 return SP_ERROR_NOT_FOUND;
907 *filename = ctx->files[low].name;
909 return SP_ERROR_NONE;
912 int BaseContext::LookupFunction(ucell_t addr, const char **name)
914 uint32_t iter, max = ctx->plugin->debug.syms_num;
916 for (iter=0; iter<max; iter++)
918 if ((ctx->symbols[iter].sym->ident == SP_SYM_FUNCTION)
919 && (ctx->symbols[iter].codestart <= addr)
920 && (ctx->symbols[iter].codeend > addr))
928 return SP_ERROR_NOT_FOUND;
931 *name = ctx->symbols[iter].name;
933 return SP_ERROR_NONE;
936 int BaseContext::LookupLine(ucell_t addr, uint32_t *line)
940 high = ctx->plugin->debug.lines_num;
943 while (high - low > 1)
945 mid = USHR(low + high);
946 if (ctx->lines[mid].addr <= addr)
956 return SP_ERROR_NOT_FOUND;
959 /* Since the CIP occurs BEFORE the line, we have to add one */
960 *line = ctx->lines[low].line + 1;
962 return SP_ERROR_NONE;
965 IPluginFunction *BaseContext::GetFunctionById(funcid_t func_id)
967 CFunction *pFunc = NULL;
972 if (func_id >= ctx->plugin->info.publics_num)
976 pFunc = m_pub_funcs[func_id];
979 m_pub_funcs[func_id] = new CFunction(ctx->publics[func_id].code_offs, this, ctx->publics[func_id].funcid);
980 pFunc = m_pub_funcs[func_id];
981 } else if (pFunc->IsInvalidated()) {
982 pFunc->Set(ctx->publics[func_id].code_offs, this, ctx->publics[func_id].funcid);
985 /* :TODO: currently not used */
989 if (!g_pVM->FunctionLookup(ctx, func_id, &index))
993 pFunc = m_priv_funcs[func_id];
996 m_priv_funcs[func_id] = new CFunction(save, this);
997 pFunc = m_priv_funcs[func_id];
1005 IPluginFunction *BaseContext::GetFunctionByName(const char *public_name)
1009 if (FindPublicByName(public_name, &index) != SP_ERROR_NONE)
1014 CFunction *pFunc = m_pub_funcs[index];
1017 sp_public_t *pub = NULL;
1018 GetPublicByIndex(index, &pub);
1021 m_pub_funcs[index] = new CFunction(pub->code_offs, this, pub->funcid);
1023 pFunc = m_pub_funcs[index];
1024 } else if (pFunc->IsInvalidated()) {
1025 sp_public_t *pub = NULL;
1026 GetPublicByIndex(index, &pub);
1029 pFunc->Set(pub->code_offs, this, pub->funcid);
1038 int BaseContext::LocalToStringNULL(cell_t local_addr, char **addr)
1041 if ((err = LocalToString(local_addr, addr)) != SP_ERROR_NONE)
1046 if ((cell_t *)*addr == m_pNullString)
1051 return SP_ERROR_NONE;
1054 #if defined SOURCEMOD_BUILD
1055 SourceMod::IdentityToken_t *BaseContext::GetIdentity()
1060 void BaseContext::SetIdentity(SourceMod::IdentityToken_t *token)
1065 cell_t *BaseContext::GetNullRef(SP_NULL_TYPE type)
1067 if (type == SP_NULL_VECTOR)