Fixed leaking relocation table memory in JIT.
3 * =============================================================================
5 * Copyright (C) 2004-2008 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"
39 #include "x86/jit_x86.h"
41 using namespace SourcePawn;
43 #define CELLBOUNDMAX (INT_MAX/sizeof(cell_t))
44 #define STACKMARGIN ((cell_t)(16*sizeof(cell_t)))
46 BaseContext::BaseContext(BaseRuntime *pRuntime)
48 m_pRuntime = pRuntime;
49 m_pPlugin = m_pRuntime->m_pPlugin;
54 /* Initialize the null references */
56 if (FindPubvarByName("NULL_VECTOR", &index) == SP_ERROR_NONE)
59 GetPubvarByIndex(index, &pubvar);
60 m_pNullVec = pubvar->offs;
67 if (FindPubvarByName("NULL_STRING", &index) == SP_ERROR_NONE)
70 GetPubvarByIndex(index, &pubvar);
71 m_pNullString = pubvar->offs;
78 m_ctx.hp = m_pPlugin->data_size;
79 m_ctx.sp = m_pPlugin->mem_size - sizeof(cell_t);
81 m_ctx.n_err = SP_ERROR_NONE;
82 m_ctx.n_idx = SP_ERROR_NONE;
85 g_Jit.SetupContextVars(m_pRuntime, this, &m_ctx);
88 BaseContext::~BaseContext()
90 g_Jit.FreeContextVars(&m_ctx);
93 IVirtualMachine *BaseContext::GetVirtualMachine()
98 sp_context_t *BaseContext::GetContext()
100 return reinterpret_cast<sp_context_t *>((IPluginContext * )this);
103 sp_context_t *BaseContext::GetCtx()
108 bool BaseContext::IsDebugging()
113 int BaseContext::SetDebugBreak(void *newpfn, void *oldpfn)
115 return SP_ERROR_ABORTED;
118 IPluginDebugInfo *BaseContext::GetDebugInfo()
123 int BaseContext::Execute(uint32_t code_addr, cell_t *result)
125 return SP_ERROR_ABORTED;
128 void BaseContext::SetErrorMessage(const char *msg, va_list ap)
132 vsnprintf(m_MsgCache, sizeof(m_MsgCache), msg, ap);
135 void BaseContext::_SetErrorMessage(const char *msg, ...)
139 SetErrorMessage(msg, ap);
143 cell_t BaseContext::ThrowNativeErrorEx(int error, const char *msg, ...)
156 SetErrorMessage(msg, ap);
163 cell_t BaseContext::ThrowNativeError(const char *msg, ...)
170 m_ctx.n_err = SP_ERROR_NATIVE;
176 SetErrorMessage(msg, ap);
183 int BaseContext::HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr)
189 if (cells > CELLBOUNDMAX)
191 return SP_ERROR_ARAM;
194 assert(cells < CELLBOUNDMAX);
197 realmem = cells * sizeof(cell_t);
200 * Check if the space between the heap and stack is sufficient.
202 if ((cell_t)(m_ctx.sp - m_ctx.hp - realmem) < STACKMARGIN)
204 return SP_ERROR_HEAPLOW;
207 addr = (cell_t *)(m_pPlugin->memory + m_ctx.hp);
208 /* store size of allocation in cells */
209 *addr = (cell_t)cells;
211 m_ctx.hp += sizeof(cell_t);
213 *local_addr = m_ctx.hp;
222 return SP_ERROR_NONE;
225 int BaseContext::HeapPop(cell_t local_addr)
230 /* check the bounds of this address */
231 local_addr -= sizeof(cell_t);
232 if (local_addr < (cell_t)m_pPlugin->data_size || local_addr >= m_ctx.sp)
234 return SP_ERROR_INVALID_ADDRESS;
237 addr = (cell_t *)(m_pPlugin->memory + local_addr);
238 cellcount = (*addr) * sizeof(cell_t);
239 /* check if this memory count looks valid */
240 if ((signed)(m_ctx.hp - cellcount - sizeof(cell_t)) != local_addr)
242 return SP_ERROR_INVALID_ADDRESS;
245 m_ctx.hp = local_addr;
247 return SP_ERROR_NONE;
251 int BaseContext::HeapRelease(cell_t local_addr)
253 if (local_addr < (cell_t)m_pPlugin->data_size)
255 return SP_ERROR_INVALID_ADDRESS;
258 m_ctx.hp = local_addr - sizeof(cell_t);
260 return SP_ERROR_NONE;
263 int BaseContext::FindNativeByName(const char *name, uint32_t *index)
265 return m_pRuntime->FindNativeByName(name, index);
268 int BaseContext::GetNativeByIndex(uint32_t index, sp_native_t **native)
270 return m_pRuntime->GetNativeByIndex(index, native);
274 uint32_t BaseContext::GetNativesNum()
276 return m_pRuntime->GetNativesNum();
279 int BaseContext::FindPublicByName(const char *name, uint32_t *index)
281 return m_pRuntime->FindPublicByName(name, index);
284 int BaseContext::GetPublicByIndex(uint32_t index, sp_public_t **pblic)
286 return m_pRuntime->GetPublicByIndex(index, pblic);
289 uint32_t BaseContext::GetPublicsNum()
291 return m_pRuntime->GetPublicsNum();
294 int BaseContext::GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar)
296 return m_pRuntime->GetPubvarByIndex(index, pubvar);
299 int BaseContext::FindPubvarByName(const char *name, uint32_t *index)
301 return m_pRuntime->FindPubvarByName(name, index);
304 int BaseContext::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr)
306 return m_pRuntime->GetPubvarAddrs(index, local_addr, phys_addr);
309 uint32_t BaseContext::GetPubVarsNum()
311 return m_pRuntime->GetPubVarsNum();
314 int BaseContext::BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite)
316 return SP_ERROR_ABORTED;
319 int BaseContext::BindNative(const sp_nativeinfo_t *native)
321 return SP_ERROR_ABORTED;
324 int BaseContext::BindNativeToIndex(uint32_t index, SPVM_NATIVE_FUNC func)
326 return SP_ERROR_ABORTED;
329 int BaseContext::BindNativeToAny(SPVM_NATIVE_FUNC native)
331 return SP_ERROR_ABORTED;
334 int BaseContext::LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr)
336 if (((local_addr >= m_ctx.hp) && (local_addr < m_ctx.sp))
337 || (local_addr < 0) || ((ucell_t)local_addr >= m_pPlugin->mem_size))
339 return SP_ERROR_INVALID_ADDRESS;
344 *phys_addr = (cell_t *)(m_pPlugin->memory + local_addr);
347 return SP_ERROR_NONE;
350 int BaseContext::PushCell(cell_t value)
352 return SP_ERROR_ABORTED;
355 int BaseContext::PushCellsFromArray(cell_t array[], unsigned int numcells)
357 return SP_ERROR_ABORTED;
360 int BaseContext::PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells)
362 return SP_ERROR_ABORTED;
365 int BaseContext::LocalToString(cell_t local_addr, char **addr)
367 if (((local_addr >= m_ctx.hp) && (local_addr < m_ctx.sp))
368 || (local_addr < 0) || ((ucell_t)local_addr >= m_pPlugin->mem_size))
370 return SP_ERROR_INVALID_ADDRESS;
372 *addr = (char *)(m_pPlugin->memory + local_addr);
374 return SP_ERROR_NONE;
377 int BaseContext::PushString(cell_t *local_addr, char **phys_addr, const char *string)
379 return SP_ERROR_ABORTED;
382 int BaseContext::StringToLocal(cell_t local_addr, size_t bytes, const char *source)
387 if (((local_addr >= m_ctx.hp) && (local_addr < m_ctx.sp))
388 || (local_addr < 0) || ((ucell_t)local_addr >= m_pPlugin->mem_size))
390 return SP_ERROR_INVALID_ADDRESS;
395 return SP_ERROR_NONE;
398 len = strlen(source);
399 dest = (char *)(m_pPlugin->memory + local_addr);
406 memmove(dest, source, len);
409 return SP_ERROR_NONE;
412 inline int __CheckValidChar(char *c)
417 for (count=1; (*c & 0xC0) == 0x80; count++)
442 if (bytecount != count)
450 int BaseContext::StringToLocalUTF8(cell_t local_addr, size_t maxbytes, const char *source, size_t *wrtnbytes)
454 bool needtocheck = false;
456 if (((local_addr >= m_ctx.hp) && (local_addr < m_ctx.sp))
458 || ((ucell_t)local_addr >= m_pPlugin->mem_size))
460 return SP_ERROR_INVALID_ADDRESS;
465 return SP_ERROR_NONE;
468 len = strlen(source);
469 dest = (char *)(m_pPlugin->memory + local_addr);
471 if ((size_t)len >= maxbytes)
477 memmove(dest, source, len);
478 if ((dest[len-1] & 1<<7) && needtocheck)
480 len -= __CheckValidChar(dest+len-1);
489 return SP_ERROR_NONE;
492 IPluginFunction *BaseContext::GetFunctionById(funcid_t func_id)
494 return m_pRuntime->GetFunctionById(func_id);
497 IPluginFunction *BaseContext::GetFunctionByName(const char *public_name)
499 return m_pRuntime->GetFunctionByName(public_name);
502 int BaseContext::LocalToStringNULL(cell_t local_addr, char **addr)
505 if ((err = LocalToString(local_addr, addr)) != SP_ERROR_NONE)
510 if ((cell_t *)*addr == m_pNullString)
515 return SP_ERROR_NONE;
518 SourceMod::IdentityToken_t *BaseContext::GetIdentity()
520 SourceMod::IdentityToken_t *tok;
522 if (GetKey(1, (void **)&tok))
530 cell_t *BaseContext::GetNullRef(SP_NULL_TYPE type)
532 if (type == SP_NULL_VECTOR)
540 bool BaseContext::IsInExec()
545 int BaseContext::Execute2(IPluginFunction *function, const cell_t *params, unsigned int num_params, cell_t *result)
552 sp_public_t *pubfunc;
553 cell_t _ignore_result;
554 unsigned int public_id;
556 fnid = function->GetFunctionID();
560 public_id = fnid >> 1;
562 if (m_pRuntime->GetPublicByIndex(public_id, &pubfunc) != SP_ERROR_NONE)
564 return SP_ERROR_NOT_FOUND;
569 return SP_ERROR_INVALID_ADDRESS;
572 if (m_pRuntime->IsPaused())
574 return SP_ERROR_NOT_RUNNABLE;
577 if ((cell_t)(m_ctx.hp + 16*sizeof(cell_t)) > (cell_t)(m_ctx.sp - (sizeof(cell_t) * (num_params + 1))))
579 return SP_ERROR_STACKLOW;
584 result = &_ignore_result;
587 /* We got this far. It's time to start profiling. */
589 if ((m_pPlugin->prof_flags & SP_PROF_CALLBACKS) == SP_PROF_CALLBACKS)
591 serial = m_pPlugin->profiler->OnCallbackBegin(this, pubfunc);
594 /* See if we have to compile the callee. */
595 if ((fn = m_pRuntime->m_PubJitFuncs[public_id]) == NULL)
599 /* We might not have to - check pcode offset. */
600 if ((func_idx = FuncLookup((CompData *)m_pRuntime->m_pCo, pubfunc->code_offs)) != 0)
602 fn = m_pRuntime->GetJittedFunction(func_idx);
604 m_pRuntime->m_PubJitFuncs[public_id] = fn;
608 if ((fn = g_Jit.CompileFunction(m_pRuntime, pubfunc->code_offs, &ir)) == NULL)
612 m_pRuntime->m_PubJitFuncs[public_id] = fn;
616 /* Save our previous state. */
620 cell_t save_sp, save_hp, save_rp, save_cip;
624 save_exec = m_InExec;
625 save_n_idx = m_ctx.n_idx;
627 save_cip = m_ctx.err_cip;
629 /* Push parameters */
631 m_ctx.sp -= sizeof(cell_t) * (num_params + 1);
632 sp = (cell_t *)(m_pPlugin->memory + m_ctx.sp);
635 for (unsigned int i = 0; i < num_params; i++)
637 sp[i + 1] = params[i];
640 /* Clear internal state */
641 m_ctx.n_err = SP_ERROR_NONE;
643 m_MsgCache[0] = '\0';
647 /* Start the frame tracer */
649 ir = g_Jit.InvokeFunction(m_pRuntime, fn, result);
651 /* Restore some states, stop the frame tracer */
653 m_InExec = save_exec;
655 if (ir == SP_ERROR_NONE)
657 m_ctx.n_err = SP_ERROR_NONE;
658 if (m_ctx.sp != save_sp)
660 ir = SP_ERROR_STACKLEAK;
661 _SetErrorMessage("Stack leak detected: sp:%d should be %d!",
665 if (m_ctx.hp != save_hp)
667 ir = SP_ERROR_HEAPLEAK;
668 _SetErrorMessage("Heap leak detected: hp:%d should be %d!",
672 if (m_ctx.rp != save_rp)
674 ir = SP_ERROR_STACKLEAK;
675 _SetErrorMessage("Return stack leak detected: rp:%d should be %d!",
681 if (ir != SP_ERROR_NONE)
683 g_engine1.ReportError(m_pRuntime, ir, m_MsgCache, save_rp);
690 if ((m_pPlugin->prof_flags & SP_PROF_CALLBACKS) == SP_PROF_CALLBACKS)
692 m_pPlugin->profiler->OnCallbackEnd(serial);
695 m_ctx.err_cip = save_cip;
696 m_ctx.n_idx = save_n_idx;
697 m_ctx.n_err = SP_ERROR_NONE;
698 m_MsgCache[0] = '\0';
704 IPluginRuntime *BaseContext::GetRuntime()
709 DebugInfo::DebugInfo(sp_plugin_t *plugin) : m_pPlugin(plugin)
713 #define USHR(x) ((unsigned int)(x)>>1)
715 int DebugInfo::LookupFile(ucell_t addr, const char **filename)
719 high = m_pPlugin->debug.files_num;
722 while (high - low > 1)
724 mid = USHR(low + high);
725 if (m_pPlugin->debug.files[mid].addr <= addr)
735 return SP_ERROR_NOT_FOUND;
738 *filename = m_pPlugin->debug.stringbase + m_pPlugin->debug.files[low].name;
740 return SP_ERROR_NONE;
743 int DebugInfo::LookupFunction(ucell_t addr, const char **name)
746 sp_fdbg_symbol_t *sym;
747 sp_fdbg_arraydim_t *arr;
748 uint8_t *cursor = (uint8_t *)(m_pPlugin->debug.symbols);
750 max = m_pPlugin->debug.syms_num;
751 for (iter = 0; iter < max; iter++)
753 sym = (sp_fdbg_symbol_t *)cursor;
755 if (sym->ident == SP_SYM_FUNCTION
756 && sym->codestart <= addr
757 && sym->codeend > addr)
759 *name = m_pPlugin->debug.stringbase + sym->name;
760 return SP_ERROR_NONE;
763 if (sym->dimcount > 0)
765 cursor += sizeof(sp_fdbg_symbol_t);
766 arr = (sp_fdbg_arraydim_t *)cursor;
767 cursor += sizeof(sp_fdbg_arraydim_t) * sym->dimcount;
771 cursor += sizeof(sp_fdbg_symbol_t);
774 return SP_ERROR_NOT_FOUND;
778 int DebugInfo::LookupLine(ucell_t addr, uint32_t *line)
782 high = m_pPlugin->debug.lines_num;
785 while (high - low > 1)
787 mid = USHR(low + high);
788 if (m_pPlugin->debug.lines[mid].addr <= addr)
798 return SP_ERROR_NOT_FOUND;
801 /* Since the CIP occurs BEFORE the line, we have to add one */
802 *line = m_pPlugin->debug.lines[low].line + 1;
804 return SP_ERROR_NONE;
809 int BaseContext::GetLastNativeError()
814 cell_t *BaseContext::GetLocalParams()
816 return (cell_t *)(m_pPlugin->memory + m_ctx.frm + (2 * sizeof(cell_t)));
819 void BaseContext::SetKey(int k, void *value)
826 m_keys[k - 1] = value;
827 m_keys_set[k - 1] = true;
830 bool BaseContext::GetKey(int k, void **value)
832 if (k < 1 || k > 4 || m_keys_set[k - 1] == false)
837 *value = m_keys[k - 1];