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;
65 if (ctx->prof_flags != 0)
67 ctx->profiler = sm_profiler;
72 m_funcsnum = ctx->vmbase->FunctionCount(ctx);
80 * Note: Since the m_plugin member will never change,
81 * it is safe to assume the function count will never change
83 if (m_funcsnum && m_priv_funcs == NULL)
85 m_priv_funcs = new CFunction *[m_funcsnum];
86 memset(m_priv_funcs, 0, sizeof(CFunction *) * m_funcsnum);
92 if (ctx->plugin->info.publics_num && m_pub_funcs == NULL)
94 m_pub_funcs = new CFunction *[ctx->plugin->info.publics_num];
95 memset(m_pub_funcs, 0, sizeof(CFunction *) * ctx->plugin->info.publics_num);
100 /* Initialize the null references */
102 if (FindPubvarByName("NULL_VECTOR", &index) == SP_ERROR_NONE)
105 GetPubvarByIndex(index, &pubvar);
106 m_pNullVec = pubvar->offs;
111 if (FindPubvarByName("NULL_STRING", &index) == SP_ERROR_NONE)
114 GetPubvarByIndex(index, &pubvar);
115 m_pNullString = pubvar->offs;
117 m_pNullString = NULL;
121 void BaseContext::FlushFunctionCache()
125 for (uint32_t i=0; i<ctx->plugin->info.publics_num; i++)
127 delete m_pub_funcs[i];
128 m_pub_funcs[i] = NULL;
135 for (unsigned int i=0; i<m_funcsnum; i++)
137 delete m_priv_funcs[i];
138 m_priv_funcs[i] = NULL;
144 void BaseContext::RefreshFunctionCache()
149 for (uint32_t i=0; i<ctx->plugin->info.publics_num; i++)
155 if (GetPublicByIndex(i, &pub) != SP_ERROR_NONE)
159 m_pub_funcs[i]->Set(pub->code_offs, this, pub->funcid, i);
166 for (unsigned int i=0; i<m_funcsnum; i++)
168 if (!m_priv_funcs[i])
178 BaseContext::~BaseContext()
180 FlushFunctionCache();
181 delete [] m_pub_funcs;
184 delete [] m_priv_funcs;
189 void BaseContext::SetContext(sp_context_t *_ctx)
198 ctx->dbreak = GlobalDebugBreak;
200 if (ctx->prof_flags != 0)
202 ctx->profiler = sm_profiler;
205 RefreshFunctionCache();
208 IVirtualMachine *BaseContext::GetVirtualMachine()
210 return (IVirtualMachine *)ctx->vmbase;
213 sp_context_t *BaseContext::GetContext()
218 bool BaseContext::IsDebugging()
220 return (ctx->flags & SPFLAG_PLUGIN_DEBUG);
223 int BaseContext::SetDebugBreak(SPVM_DEBUGBREAK newpfn, SPVM_DEBUGBREAK *oldpfn)
227 return SP_ERROR_NOTDEBUGGING;
230 *oldpfn = ctx->dbreak;
231 ctx->dbreak = newpfn;
233 return SP_ERROR_NONE;
236 IPluginDebugInfo *BaseContext::GetDebugInfo()
245 int BaseContext::Execute(uint32_t code_addr, cell_t *result)
247 if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
249 return SP_ERROR_NOT_RUNNABLE;
252 /* tada, prevent a crash */
253 cell_t _ignore_result;
256 result = &_ignore_result;
259 IVirtualMachine *vm = (IVirtualMachine *)ctx->vmbase;
261 uint32_t pushcount = ctx->pushcount;
264 if ((err = PushCell(pushcount++)) != SP_ERROR_NONE)
266 #if defined SOURCEMOD_BUILD
267 g_DbgReporter.GenerateCodeError(this, code_addr, err, "Stack error; cannot complete execution!");
269 return SP_ERROR_NOT_RUNNABLE;
273 cell_t save_sp = ctx->sp + (pushcount * sizeof(cell_t));
274 cell_t save_hp = ctx->hp;
275 uint32_t n_idx = ctx->n_idx;
277 bool wasExec = m_InExec;
279 /* Clear the error state, if any */
280 ctx->n_err = SP_ERROR_NONE;
283 m_MsgCache[0] = '\0';
286 g_SourcePawn.PushTracer(ctx);
288 err = vm->ContextExecute(ctx, code_addr, result);
293 * :TODO: Calling from a plugin in here will erase the cached message...
294 * Should that be documented?
296 g_SourcePawn.PopTracer(err, m_CustomMsg ? m_MsgCache : NULL);
298 #if defined SOURCEMOD_BUILD
299 if (err == SP_ERROR_NONE)
301 if (ctx->sp != save_sp)
303 g_DbgReporter.GenerateCodeError(this,
306 "Stack leak detected: sp:%d should be %d!",
310 if (ctx->hp != save_hp)
312 g_DbgReporter.GenerateCodeError(this,
315 "Heap leak detected: sp:%d should be %d!",
322 if (err != SP_ERROR_NONE)
329 ctx->n_err = SP_ERROR_NONE;
330 m_MsgCache[0] = '\0';
336 void BaseContext::SetErrorMessage(const char *msg, va_list ap)
340 vsnprintf(m_MsgCache, sizeof(m_MsgCache), msg, ap);
343 cell_t BaseContext::ThrowNativeErrorEx(int error, const char *msg, ...)
356 SetErrorMessage(msg, ap);
363 cell_t BaseContext::ThrowNativeError(const char *msg, ...)
370 ctx->n_err = SP_ERROR_NATIVE;
376 SetErrorMessage(msg, ap);
383 int BaseContext::HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr)
389 if (cells > CELLBOUNDMAX)
391 return SP_ERROR_ARAM;
394 assert(cells < CELLBOUNDMAX);
397 realmem = cells * sizeof(cell_t);
400 * Check if the space between the heap and stack is sufficient.
402 if ((cell_t)(ctx->sp - ctx->hp - realmem) < STACKMARGIN)
404 return SP_ERROR_HEAPLOW;
407 addr = (cell_t *)(ctx->memory + ctx->hp);
408 /* store size of allocation in cells */
409 *addr = (cell_t)cells;
411 ctx->hp += sizeof(cell_t);
413 *local_addr = ctx->hp;
422 return SP_ERROR_NONE;
425 int BaseContext::HeapPop(cell_t local_addr)
430 /* check the bounds of this address */
431 local_addr -= sizeof(cell_t);
432 if (local_addr < ctx->heap_base || local_addr >= ctx->sp)
434 return SP_ERROR_INVALID_ADDRESS;
437 addr = (cell_t *)(ctx->memory + local_addr);
438 cellcount = (*addr) * sizeof(cell_t);
439 /* check if this memory count looks valid */
440 if ((signed)(ctx->hp - cellcount - sizeof(cell_t)) != local_addr)
442 return SP_ERROR_INVALID_ADDRESS;
445 ctx->hp = local_addr;
447 return SP_ERROR_NONE;
451 int BaseContext::HeapRelease(cell_t local_addr)
453 if (local_addr < ctx->heap_base)
455 return SP_ERROR_INVALID_ADDRESS;
458 ctx->hp = local_addr - sizeof(cell_t);
460 return SP_ERROR_NONE;
463 int BaseContext::FindNativeByName(const char *name, uint32_t *index)
467 high = ctx->plugin->info.natives_num - 1;
469 for (uint32_t i=0; i<ctx->plugin->info.natives_num; i++)
471 if (strcmp(ctx->natives[i].name, name) == 0)
477 return SP_ERROR_NONE;
481 return SP_ERROR_NOT_FOUND;
484 int BaseContext::GetNativeByIndex(uint32_t index, sp_native_t **native)
486 if (index >= ctx->plugin->info.natives_num)
488 return SP_ERROR_INDEX;
493 *native = &(ctx->natives[index]);
496 return SP_ERROR_NONE;
500 uint32_t BaseContext::GetNativesNum()
502 return ctx->plugin->info.natives_num;
505 int BaseContext::FindPublicByName(const char *name, uint32_t *index)
510 high = ctx->plugin->info.publics_num - 1;
515 mid = (low + high) / 2;
516 diff = strcmp(ctx->publics[mid].name, name);
523 return SP_ERROR_NONE;
524 } else if (diff < 0) {
531 return SP_ERROR_NOT_FOUND;
534 int BaseContext::GetPublicByIndex(uint32_t index, sp_public_t **pblic)
536 if (index >= ctx->plugin->info.publics_num)
538 return SP_ERROR_INDEX;
543 *pblic = &(ctx->publics[index]);
546 return SP_ERROR_NONE;
549 uint32_t BaseContext::GetPublicsNum()
551 return ctx->plugin->info.publics_num;
554 int BaseContext::GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar)
556 if (index >= ctx->plugin->info.pubvars_num)
558 return SP_ERROR_INDEX;
563 *pubvar = &(ctx->pubvars[index]);
566 return SP_ERROR_NONE;
569 int BaseContext::FindPubvarByName(const char *name, uint32_t *index)
574 high = ctx->plugin->info.pubvars_num - 1;
579 mid = (low + high) / 2;
580 diff = strcmp(ctx->pubvars[mid].name, name);
587 return SP_ERROR_NONE;
588 } else if (diff < 0) {
595 return SP_ERROR_NOT_FOUND;
598 int BaseContext::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr)
600 if (index >= ctx->plugin->info.pubvars_num)
602 return SP_ERROR_INDEX;
605 *local_addr = ctx->plugin->info.pubvars[index].address;
606 *phys_addr = ctx->pubvars[index].offs;
608 return SP_ERROR_NONE;
611 uint32_t BaseContext::GetPubVarsNum()
613 return ctx->plugin->info.pubvars_num;
616 int BaseContext::BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite)
620 max = ctx->plugin->info.natives_num;
622 for (i=0; i<max; i++)
624 if ((ctx->natives[i].status == SP_NATIVE_BOUND) && !overwrite)
629 for (j=0; (natives[j].name) && (!num || j<num); j++)
631 if (!strcmp(ctx->natives[i].name, natives[j].name))
633 ctx->natives[i].pfn = natives[j].func;
634 ctx->natives[i].status = SP_NATIVE_BOUND;
639 return SP_ERROR_NONE;
642 int BaseContext::BindNative(const sp_nativeinfo_t *native)
647 if ((err = FindNativeByName(native->name, &index)) != SP_ERROR_NONE)
652 ctx->natives[index].pfn = native->func;
653 ctx->natives[index].status = SP_NATIVE_BOUND;
655 return SP_ERROR_NONE;
658 int BaseContext::BindNativeToIndex(uint32_t index, SPVM_NATIVE_FUNC func)
663 if ((err = GetNativeByIndex(index, &native)) != SP_ERROR_NONE)
668 ctx->natives[index].pfn = func;
669 ctx->natives[index].status = SP_NATIVE_BOUND;
671 return SP_ERROR_NONE;
674 int BaseContext::BindNativeToAny(SPVM_NATIVE_FUNC native)
676 uint32_t nativesnum, i;
678 nativesnum = ctx->plugin->info.natives_num;
680 for (i=0; i<nativesnum; i++)
682 if (ctx->natives[i].status == SP_NATIVE_UNBOUND)
684 ctx->natives[i].pfn = native;
685 ctx->natives[i].status = SP_NATIVE_BOUND;
689 return SP_ERROR_NONE;
692 int BaseContext::LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr)
694 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
696 return SP_ERROR_INVALID_ADDRESS;
701 *phys_addr = (cell_t *)(ctx->memory + local_addr);
704 return SP_ERROR_NONE;
707 int BaseContext::PushCell(cell_t value)
709 if ((ctx->hp + STACKMARGIN) > (cell_t)(ctx->sp - sizeof(cell_t)))
711 return SP_ERROR_STACKLOW;
714 ctx->sp -= sizeof(cell_t);
715 *(cell_t *)(ctx->memory + ctx->sp) = value;
718 return SP_ERROR_NONE;
721 int BaseContext::PushCellsFromArray(cell_t array[], unsigned int numcells)
726 for (i=0; i<numcells; i++)
728 if ((err = PushCell(array[i])) != SP_ERROR_NONE)
730 ctx->sp += (cell_t)(i * sizeof(cell_t));
736 return SP_ERROR_NONE;
739 int BaseContext::PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells)
744 if ((err = HeapAlloc(numcells, local_addr, &ph_addr)) != SP_ERROR_NONE)
749 memcpy(ph_addr, array, numcells * sizeof(cell_t));
751 if ((err = PushCell(*local_addr)) != SP_ERROR_NONE)
753 HeapRelease(*local_addr);
759 *phys_addr = ph_addr;
762 return SP_ERROR_NONE;
765 int BaseContext::LocalToString(cell_t local_addr, char **addr)
767 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
769 return SP_ERROR_INVALID_ADDRESS;
771 *addr = (char *)(ctx->memory + local_addr);
773 return SP_ERROR_NONE;
776 int BaseContext::PushString(cell_t *local_addr, char **phys_addr, const char *string)
780 unsigned int len, numcells = ((len=strlen(string)) + sizeof(cell_t)) / sizeof(cell_t);
782 if ((err = HeapAlloc(numcells, local_addr, (cell_t **)&ph_addr)) != SP_ERROR_NONE)
787 memcpy(ph_addr, string, len);
790 if ((err = PushCell(*local_addr)) != SP_ERROR_NONE)
792 HeapRelease(*local_addr);
798 *phys_addr = ph_addr;
801 return SP_ERROR_NONE;
804 int BaseContext::StringToLocal(cell_t local_addr, size_t bytes, const char *source)
809 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
811 return SP_ERROR_INVALID_ADDRESS;
816 return SP_ERROR_NONE;
819 len = strlen(source);
820 dest = (char *)(ctx->memory + local_addr);
827 memmove(dest, source, len);
830 return SP_ERROR_NONE;
833 inline int __CheckValidChar(char *c)
838 for (count=1; (*c & 0xC0) == 0x80; count++)
863 if (bytecount != count)
871 int BaseContext::StringToLocalUTF8(cell_t local_addr, size_t maxbytes, const char *source, size_t *wrtnbytes)
875 bool needtocheck = false;
877 if (((local_addr >= ctx->hp) && (local_addr < ctx->sp)) || (local_addr < 0) || ((ucell_t)local_addr >= ctx->mem_size))
879 return SP_ERROR_INVALID_ADDRESS;
884 return SP_ERROR_NONE;
887 len = strlen(source);
888 dest = (char *)(ctx->memory + local_addr);
890 if ((size_t)len >= maxbytes)
896 memmove(dest, source, len);
897 if ((dest[len-1] & 1<<7) && needtocheck)
899 len -= __CheckValidChar(dest+len-1);
908 return SP_ERROR_NONE;
911 #define USHR(x) ((unsigned int)(x)>>1)
913 int BaseContext::LookupFile(ucell_t addr, const char **filename)
917 high = ctx->plugin->debug.files_num;
920 while (high - low > 1)
922 mid = USHR(low + high);
923 if (ctx->files[mid].addr <= addr)
933 return SP_ERROR_NOT_FOUND;
936 *filename = ctx->files[low].name;
938 return SP_ERROR_NONE;
941 int BaseContext::LookupFunction(ucell_t addr, const char **name)
943 uint32_t iter, max = ctx->plugin->debug.syms_num;
945 for (iter=0; iter<max; iter++)
947 if ((ctx->symbols[iter].sym->ident == SP_SYM_FUNCTION)
948 && (ctx->symbols[iter].codestart <= addr)
949 && (ctx->symbols[iter].codeend > addr))
957 return SP_ERROR_NOT_FOUND;
960 *name = ctx->symbols[iter].name;
962 return SP_ERROR_NONE;
965 int BaseContext::LookupLine(ucell_t addr, uint32_t *line)
969 high = ctx->plugin->debug.lines_num;
972 while (high - low > 1)
974 mid = USHR(low + high);
975 if (ctx->lines[mid].addr <= addr)
985 return SP_ERROR_NOT_FOUND;
988 /* Since the CIP occurs BEFORE the line, we have to add one */
989 *line = ctx->lines[low].line + 1;
991 return SP_ERROR_NONE;
994 IPluginFunction *BaseContext::GetFunctionById(funcid_t func_id)
996 CFunction *pFunc = NULL;
1001 if (func_id >= ctx->plugin->info.publics_num)
1005 pFunc = m_pub_funcs[func_id];
1008 m_pub_funcs[func_id] = new CFunction(ctx->publics[func_id].code_offs,
1010 ctx->publics[func_id].funcid,
1012 pFunc = m_pub_funcs[func_id];
1014 else if (pFunc->IsInvalidated())
1016 pFunc->Set(ctx->publics[func_id].code_offs,
1018 ctx->publics[func_id].funcid,
1022 /* :TODO: currently not used */
1026 if (!g_pVM->FunctionLookup(ctx, func_id, &index))
1030 pFunc = m_priv_funcs[func_id];
1033 m_priv_funcs[func_id] = new CFunction(save, this);
1034 pFunc = m_priv_funcs[func_id];
1042 IPluginFunction *BaseContext::GetFunctionByName(const char *public_name)
1046 if (FindPublicByName(public_name, &index) != SP_ERROR_NONE)
1051 CFunction *pFunc = m_pub_funcs[index];
1054 sp_public_t *pub = NULL;
1055 GetPublicByIndex(index, &pub);
1058 m_pub_funcs[index] = new CFunction(pub->code_offs, this, pub->funcid, index);
1060 pFunc = m_pub_funcs[index];
1062 else if (pFunc->IsInvalidated())
1064 sp_public_t *pub = NULL;
1065 GetPublicByIndex(index, &pub);
1068 pFunc->Set(pub->code_offs, this, pub->funcid, index);
1079 int BaseContext::LocalToStringNULL(cell_t local_addr, char **addr)
1082 if ((err = LocalToString(local_addr, addr)) != SP_ERROR_NONE)
1087 if ((cell_t *)*addr == m_pNullString)
1092 return SP_ERROR_NONE;
1095 #if defined SOURCEMOD_BUILD
1096 SourceMod::IdentityToken_t *BaseContext::GetIdentity()
1101 void BaseContext::SetIdentity(SourceMod::IdentityToken_t *token)
1106 cell_t *BaseContext::GetNullRef(SP_NULL_TYPE type)
1108 if (type == SP_NULL_VECTOR)
1117 bool BaseContext::IsInExec()