cell AMX_NATIVE_CALL pawn_regex_exreplace(AMX* amx, cell* params) { const char *string = NULL, *replace = NULL; cell* addr = NULL; amx_GetAddr(amx, params[1], &addr); amx_StrParam(amx, params[1], string); amx_StrParam(amx, params[3], replace); if(string) { int id=(int)params[2]; if(id>=0 && id<TotalExpressions) { int r=NULL; UChar* str = (UChar* )string; onig_region_clear(rexpression[id].zreg); r = onig_search(rexpression[id].RegExpr, str, str+strlen(string), str, str+strlen(string), rexpression[id].zreg, ONIG_OPTION_NONE); if(r>=0) { std::string asd = std::string(string); asd.replace(asd.begin()+r, asd.begin()+rexpression[id].zreg->end[rexpression[id].zreg->num_regs-1], replace); amx_SetString(addr, asd.c_str(), 0, 0, params[1]); } else if(r<ONIG_MISMATCH) { UChar s[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(s, r); logprintf("[REGEX ERROR]: %s\n", s); return -1; } return r; } logprintf("[REGEX ERROR]: Call regex_exreplace with undefined parameter at index %d", id); return -1; } return -1337; }
static cell SetTimer_(AMX * amx, cell func, cell delay, cell interval, cell count, cell format, cell * params) { // Advanced version of SetTimer. Takes four main parameters so that we can // have offsets on timers (so they may start after 10ms, then run once every // 5ms say), and a COUNT for how many times to run the function! // First, find the given function. //logprintf("Adding"); if (delay >= -1 && interval >= 0 && count >= -1) { char * fname; STR_PARAM(amx, func, fname); int idx; if (amx_FindPublic(amx, fname, &idx)) { logprintf("fixes.plugin: Could not find function %s.", fname); } else { struct timer_s * timer; try { timer = new struct timer_s; } catch (...) { logprintf("fixes.plugin: Unable to allocate memory."); return 0; } timer->id = ++gCurrentTimer; timer->amx = amx; timer->func = idx; timer->interval = interval * 1000; // Need to somehow get the current time. There is a handy trick here // with negative numbers (i.e -1 being "almost straight away"). timer->trigger = MicrosecondTime() + delay * 1000; timer->params = 0; timer->repeat = count; gTimers.push(timer); // Add this timer to the map of timers. gHandles[gCurrentTimer] = timer; //logprintf("Added %d", timer->trigger); if (format) { char * fmat; STR_PARAM(amx, format, fmat); idx = 0; for ( ; ; ) { switch (*fmat++) { case '\0': { if (gCurrentTimer == 0xFFFFFFFF) { logprintf("fixes.plugin: 4294967295 timers created."); } return (cell)gCurrentTimer; } case 'i': case 'f': case 'x': case 'h': case 'b': case 'c': case 'l': case 'I': case 'F': case 'X': case 'H': case 'B': case 'C': case 'L': { struct params_s * p0 = (struct params_s *)malloc(sizeof (struct params_s)); if (p0) { cell * cstr; amx_GetAddr(amx, params[idx++], &cstr); p0->free = 0; p0->type = PARAM_TYPE_CELL; p0->numData = *cstr; //params[idx++]; // Construct the list backwards. Means we don't // need to worry about finding the latest one OR // the push order, so serves two purposes. p0->next = timer->params; timer->params = p0; } else { DestroyTimer(timer); logprintf("fixes.plugin: Unable to allocate memory."); return 0; } break; } case 's': case 'S': { cell * cstr; int len; amx_GetAddr(amx, params[idx++], &cstr); amx_StrLen(cstr, &len); struct params_s * p0 = (struct params_s *)malloc(sizeof (struct params_s) + len * sizeof (cell) + sizeof (cell)); if (p0) { p0->free = 0; p0->type = PARAM_TYPE_STRING; p0->numData = len + 1; memcpy(p0->arrayData, cstr, len * sizeof (cell) + sizeof (cell)); p0->next = timer->params; timer->params = p0; } else { DestroyTimer(timer); logprintf("fixes.plugin: Unable to allocate memory."); return 0; } break; } case 'a': case 'A': { switch (*fmat) { case 'i': case 'x': case 'h': case 'b': case 'I': case 'X': case 'H': case 'B': { cell * cstr; amx_GetAddr(amx, params[idx++], &cstr); int len = params[idx]; struct params_s * p0 = (struct params_s *)malloc(sizeof (struct params_s) + len * sizeof (cell)); if (p0) { p0->free = 0; p0->type = PARAM_TYPE_ARRAY; p0->numData = len; memcpy(p0->arrayData, cstr, len * sizeof (cell)); p0->next = timer->params; timer->params = p0; } else { DestroyTimer(timer); logprintf("fixes.plugin: Unable to allocate memory."); return 0; } break; } default: { logprintf("fixes.plugin: Array with no length."); } } break; } } } } else { if (gCurrentTimer == 0xFFFFFFFF) { logprintf("fixes.plugin: 4294967295 timers created."); } return (cell)gCurrentTimer; } } } else { logprintf("fixes.plugin: Invalid timer parameter."); } return 0; }
/* libcall(const libname[], const funcname[], const typestring[], ...) * * Loads the DLL or shared library if not yet loaded (the name comparison is * case sensitive). * * typestring format: * Whitespace is permitted between the types, but not inside the type * specification. The string "ii[4]&u16s" is equivalent to "i i[4] &u16 s", * but the latter is easier on the eye. * * types: * i = signed integer, 16-bit in Windows 3.x, else 32-bit in Win32 and Linux * u = unsigned integer, 16-bit in Windows 3.x, else 32-bit in Win32 and Linux * f = IEEE floating point, 32-bit * p = packed string * s = unpacked string * The difference between packed and unpacked strings is only relevant when * the parameter is passed by reference (see below). * * pass-by-value and pass-by-reference: * By default, parameters are passed by value. To pass a parameter by * reference, prefix the type letter with an "&": * &i = signed integer passed by reference * i = signed integer passed by value * Same for '&u' versus 'u' and '&f' versus 'f'. * * Arrays are passed by "copy & copy-back". That is, libcall() allocates a * block of dynamic memory to copy the array into. On return from the foreign * function, libcall() copies the array back to the abstract machine. The * net effect is similar to pass by reference, but the foreign function does * not work in the AMX stack directly. During the copy and the copy-back * operations, libcall() may also transform the array elements, for example * between 16-bit and 32-bit elements. This is done because Pawn only * supports a single cell size, which may not fit the required integer size * of the foreign function. * * See "element ranges" for the syntax of passing an array. * * Strings may either be passed by copy, or by "copy & copy-back". When the * string is an output parameter (for the foreign function), the size of the * array that will hold the return string must be indicated between square * brackets behind the type letter (see "element ranges"). When the string * is "input only", this is not needed --libcall() will determine the length * of the input string itself. * * The tokens 'p' and 's' are equivalent, but 'p[10]' and 's[10]' are not * equivalent: the latter syntaxes determine whether the output from the * foreign function will be stored as a packed or an unpacked string. * * element sizes: * Add an integer behind the type letter; for example, 'i16' refers to a * 16-bit signed integer. Note that the value behind the type letter must * be either 8, 16 or 32. * * You should only use element size specifiers on the 'i' and 'u' types. That * is, do not use these specifiers on 'f', 's' and 'p'. * * element ranges: * For passing arrays, the size of the array may be given behind the type * letter and optional element size. The token 'u[4]' indicates an array of * four unsigned integers, which are typically 32-bit. The token 'i16[8]' * is an array of 8 signed 16-bit integers. Arrays are always passed by * "copy & copy-back" * * When compiled as Unicode, this library converts all strings to Unicode * strings. * * The calling convention for the foreign functions is assumed: * - "__stdcall" for Win32, * - "far pascal" for Win16 * - and the GCC default for Unix/Linux (_cdecl) * * C++ name mangling of the called function is not handled (there is no standard * convention for name mangling, so there is no portable way to convert C++ * function names to mangled names). Win32 name mangling (used by default by * Microsoft compilers on functions declared as __stdcall) is also not handled. * * Returns the value of the called function. */ static cell AMX_NATIVE_CALL n_libcall(AMX *amx, const cell *params) { const TCHAR *libname, *funcname, *typestring; MODLIST *item; int paramidx, typeidx, idx; PARAM ps[MAXPARAMS]; cell *cptr,result; LIBFUNC LibFunc; amx_StrParam(amx, params[1], libname); item = findlib(&ModRoot, amx, libname); if (item == NULL) item = addlib(&ModRoot, amx, libname); if (item == NULL) { amx_RaiseError(amx, AMX_ERR_NATIVE); return 0; } /* if */ /* library is loaded, get the function */ amx_StrParam(amx, params[2], funcname); LibFunc=(LIBFUNC)SearchProcAddress(item->inst, funcname); if (LibFunc==NULL) { amx_RaiseError(amx, AMX_ERR_NATIVE); return 0; } /* if */ #if defined HAVE_DYNCALL_H /* (re-)initialize the dyncall library */ if (dcVM==NULL) { dcVM=dcNewCallVM(4096); dcMode(dcVM,DC_CALL_C_X86_WIN32_STD); } /* if */ dcReset(dcVM); #endif /* decode the parameters */ paramidx=typeidx=0; amx_StrParam(amx, params[3], typestring); while (paramidx < MAXPARAMS && typestring[typeidx]!=__T('\0')) { /* skip white space */ while (typestring[typeidx]!=__T('\0') && typestring[typeidx]<=__T(' ')) typeidx++; if (typestring[typeidx]==__T('\0')) break; /* save "pass-by-reference" token */ ps[paramidx].type=0; if (typestring[typeidx]==__T('&')) { ps[paramidx].type=BYREF; typeidx++; } /* if */ /* store type character */ ps[paramidx].type |= (unsigned char)typestring[typeidx]; typeidx++; /* set default size, then check for an explicit size */ #if defined __WIN32__ || defined _WIN32 || defined WIN32 ps[paramidx].size=32; #elif defined _Windows ps[paramidx].size=16; #endif if (_istdigit(typestring[typeidx])) { ps[paramidx].size=(unsigned char)_tcstol(&typestring[typeidx],NULL,10); while (_istdigit(typestring[typeidx])) typeidx++; } /* if */ /* set default range, then check for an explicit range */ ps[paramidx].range=1; if (typestring[typeidx]=='[') { ps[paramidx].range=_tcstol(&typestring[typeidx+1],NULL,10); while (typestring[typeidx]!=']' && typestring[typeidx]!='\0') typeidx++; ps[paramidx].type |= BYREF; /* arrays are always passed by reference */ typeidx++; /* skip closing ']' too */ } /* if */ /* get pointer to parameter */ amx_GetAddr(amx,params[paramidx+4],&cptr); switch (ps[paramidx].type) { case 'i': /* signed integer */ case 'u': /* unsigned integer */ case 'f': /* floating point */ assert(ps[paramidx].range==1); ps[paramidx].v.val=(int)*cptr; break; case 'i' | BYREF: case 'u' | BYREF: case 'f' | BYREF: ps[paramidx].v.ptr=cptr; if (ps[paramidx].range>1) { /* convert array and pass by address */ ps[paramidx].v.ptr = fillarray(amx, &ps[paramidx], cptr); } /* if */ break; case 'p': case 's': case 'p' | BYREF: case 's' | BYREF: if (ps[paramidx].type=='s' || ps[paramidx].type=='p') { int len; /* get length of input string */ amx_StrLen(cptr,&len); len++; /* include '\0' */ /* check max. size */ if (len<ps[paramidx].range) len=ps[paramidx].range; ps[paramidx].range=len; } /* if */ ps[paramidx].v.ptr=malloc(ps[paramidx].range*sizeof(TCHAR)); if (ps[paramidx].v.ptr==NULL) return amx_RaiseError(amx, AMX_ERR_NATIVE); amx_GetString((char *)ps[paramidx].v.ptr,cptr,sizeof(TCHAR)>1,UNLIMITED); break; default: /* invalid parameter type */ return amx_RaiseError(amx, AMX_ERR_NATIVE); } /* switch */ paramidx++; } /* while */ if ((params[0]/sizeof(cell)) - 3 != (size_t)paramidx) return amx_RaiseError(amx, AMX_ERR_NATIVE); /* format string does not match number of parameters */ #if defined HAVE_DYNCALL_H for (idx = 0; idx < paramidx; idx++) { if ((ps[idx].type=='i' || ps[idx].type=='u' || ps[idx].type=='f') && ps[idx].range==1) { switch (ps[idx].size) { case 8: dcArgChar(dcVM,(unsigned char)(ps[idx].v.val & 0xff)); break; case 16: dcArgShort(dcVM,(unsigned short)(ps[idx].v.val & 0xffff)); break; default: dcArgLong(dcVM,ps[idx].v.val); } /* switch */ } else { dcArgPointer(dcVM,ps[idx].v.ptr); } /* if */ } /* for */ result=(cell)dcCallPointer(dcVM,(void*)LibFunc); #else /* HAVE_DYNCALL_H */ /* push the parameters to the stack (left-to-right in 16-bit; right-to-left * in 32-bit) */ #if defined __WIN32__ || defined _WIN32 || defined WIN32 for (idx=paramidx-1; idx>=0; idx--) { #else for (idx=0; idx<paramidx; idx++) { #endif if ((ps[idx].type=='i' || ps[idx].type=='u' || ps[idx].type=='f') && ps[idx].range==1) { switch (ps[idx].size) { case 8: push((unsigned char)(ps[idx].v.val & 0xff)); break; case 16: push((unsigned short)(ps[idx].v.val & 0xffff)); break; default: push(ps[idx].v.val); } /* switch */ } else { push(ps[idx].v.ptr); } /* if */ } /* for */ /* call the function; all parameters are already pushed to the stack (the * function should remove the parameters from the stack) */ result=LibFunc(); #endif /* HAVE_DYNCALL_H */ /* store return values and free allocated memory */ for (idx=0; idx<paramidx; idx++) { switch (ps[idx].type) { case 'p': case 's': free(ps[idx].v.ptr); break; case 'p' | BYREF: case 's' | BYREF: amx_GetAddr(amx,params[idx+4],&cptr); amx_SetString(cptr,(char *)ps[idx].v.ptr,ps[idx].type==('p'|BYREF),sizeof(TCHAR)>1,UNLIMITED); free(ps[idx].v.ptr); break; case 'i': case 'u': case 'f': assert(ps[idx].range==1); break; case 'i' | BYREF: case 'u' | BYREF: case 'f' | BYREF: amx_GetAddr(amx,params[idx+4],&cptr); if (ps[idx].range==1) { /* modify directly in the AMX (no memory block was allocated */ switch (ps[idx].size) { case 8: *cptr= (ps[idx].type==('i' | BYREF)) ? (long)((signed char)*cptr) : (*cptr & 0xff); break; case 16: *cptr= (ps[idx].type==('i' | BYREF)) ? (long)((short)*cptr) : (*cptr & 0xffff); break; } /* switch */ } else { int i; for (i=0; i<ps[idx].range; i++) { switch (ps[idx].size) { case 8: *cptr= (ps[idx].type==('i' | BYREF)) ? ((signed char*)ps[idx].v.ptr)[i] : ((unsigned char*)ps[idx].v.ptr)[i]; break; case 16: *cptr= (ps[idx].type==('i' | BYREF)) ? ((short*)ps[idx].v.ptr)[i] : ((unsigned short*)ps[idx].v.ptr)[i]; break; default: *cptr= (ps[idx].type==('i' | BYREF)) ? ((long*)ps[idx].v.ptr)[i] : ((unsigned long*)ps[idx].v.ptr)[i]; } /* switch */ } /* for */ free((char *)ps[idx].v.ptr); } /* if */ break; default: assert(0); } /* switch */ } /* for */ return result; } /* bool: libfree(const libname[]="") * When the name is an empty string, this function frees all libraries (for this * abstract machine). The name comparison is case sensitive. * Returns true if one or more libraries were freed. */ static cell AMX_NATIVE_CALL n_libfree(AMX *amx, const cell *params) { const TCHAR *libname; amx_StrParam(amx,params[1],libname); return freelib(&ModRoot,amx,libname) > 0; } #else /* HAVE_DYNCALL_H || WIN32_FFI */ static cell AMX_NATIVE_CALL n_libcall(AMX *amx, const cell *params) { (void)amx; (void)params; return 0; }
static cell AMX_NATIVE_CALL n_unformat(AMX * amx, cell * params) { // FAIL(g_iTrueMax != 0, ERROR_NOT_INITIALISED); FAIL(params[0] >= 8, ERROR_MISSING_PARAMETERS); CellMemory storage(amx, params); // Get the specifier string. cell * formatAddr; amx_GetAddr(amx, params[2], &formatAddr); Specifier * parent = nullptr; error_t error = OK; char const * cptr = nullptr; bool del = true; if (*formatAddr == -1) { // Special case, the passed string is actually a 2 element arrays, the // first is -1 as a marker, the second is the address of a pre-compiled // specifier. parent = (Specifier *)*(formatAddr + 1); del = false; } else { FAIL(*formatAddr != '\0' && !(*formatAddr == '\1' && *(formatAddr + 1) == '\0'), ERROR_NO_SPECIFIER); char * format; amx_StrParam(amx, params[2], format); cptr = format; // Try complie the format line input to a specifier. error = gParser.Compile(cptr, &parent); if (error != OK) { delete parent; return (cell)error; } FAIL(parent, ERROR_NO_COMPILE); } // Get the string to split up. char * input; //logprintf("GET "); STR_PARAM(amx, params[1], input); cptr = input; //logprintf("input = \"%s\"", input); // Do the main code with the default delimiters to begin with. This is the // only line in this function not concerned with marshalling data from PAWN // and in to C++, i.e. this is the main core of the operation now that we // have everything set up. This is a VASTLY better design than v2.x, where // almost everything was controlled by the main "n_sscanf" function (making // it HUGE). Environment env(&storage); Utils::SkipWhitespace(cptr); error = parent->Run(cptr, env); if (del) delete parent; // Don't delete pre-compiled specifiers. return (cell)error; }
// native sscanf(const data[], const format[], (Float,_}:...); static cell AMX_NATIVE_CALL n_sscanf(AMX * amx, cell * params) { if (g_iTrueMax == 0) { logprintf("sscanf error: System not initialised."); return SSCANF_FAIL_RETURN; } // Friendly note, the most complex set of specifier additions is: // // A<i>(10, 11)[5] // // In that exact order - type, default, size. It's very opposite to how // it's done in code, where you would do the eqivalent to: // // <i>[5] = {10, 11} // // But this method is vastly simpler to parse in this context! Technically // you can, due to legacy support for 'p', do: // // Ai(10, 11)[5] // // But you will get an sscanf warning, and I may remove that ability from // the start - that will mean a new function, but an easy to write one. // In fact the most complex will probably be something like: // // E<ifs[32]s[8]d>(10, 12.3, Hello there, Hi, 42) // // Get the number of parameters passed. We add one as the indexes are out // by one (OBOE - Out By One Error) due to params[0] being the parameter // count, not an actual parameter. const int paramCount = ((int)params[0] / 4) + 1; // Could add a check for only 3 parameters here - I can't think of a time // when you would not want any return values at all, but that doesn't mean // they don't exist - you could just want to check but not save the format. // Update - that is now a possibility with the '{...}' specifiers. if (paramCount < (2 + 1)) { logprintf("sscanf error: Missing required parameters."); return SSCANF_FAIL_RETURN; } //else if (paramCount == (2 + 1)) //{ // Only have an input and a specifier - better hope the whole specifier // is quite (i.e. enclosed in '{...}'). //} // Set up function wide values. // Get and check the main data. // Pointer to the current input data. char * string; STR_PARAM(amx, params[1], string); // Pointer to the current format specifier. char * format; STR_PARAM(amx, params[2], format); // Check for CallRemoteFunction style null strings and correct. if (string[0] == '\1' && string[1] == '\0') { string[0] = '\0'; } // Current parameter to save data to. int paramPos = 3; cell * cptr; InitialiseDelimiter(); // Skip leading space. SkipWhitespace(&string); bool doSave; // Code for the rare cases where the WHOLE format is quiet. if (*format == '{') { ++format; doSave = false; } else { doSave = true; } // Now do the main loop as long as there are variables to store the data in // and input string remaining to get the data from. while (*string && (paramPos < paramCount || !doSave)) { if (!*format) { // End of the format string - if we're here we've got all the // parameters but there is extra string or variables, which may // indicate their code needs fixing, for example: // sscanf(data, "ii", var0, var1, var3, var4); // There is only two format specifiers, but four returns. This may // also be reached if there is too much input data, but that is // considered OK as that is likely a user's fault. if (paramPos < paramCount) { logprintf("sscanf warning: Format specifier does not match parameter count."); } if (!doSave) { // Started a quiet section but never explicitly ended it. logprintf("sscanf warning: Unclosed quiet section."); } return SSCANF_TRUE_RETURN; } else if (IsWhitespace(*format)) { ++format; } else { switch (*format++) { case 'L': DX(bool, L) // FALLTHROUGH case 'l': DOV(bool, L) break; case 'B': DX(int, B) // FALLTHROUGH case 'b': DO(int, B) case 'N': DX(int, N) // FALLTHROUGH case 'n': DO(int, N) case 'C': DX(char, C) // FALLTHROUGH case 'c': DO(char, C) case 'I': case 'D': DX(int, I) // FALLTHROUGH case 'i': case 'd': DO(int, I) case 'H': case 'X': DX(int, H) // FALLTHROUGH case 'h': case 'x': DO(int, H) case 'O': DX(int, O) // FALLTHROUGH case 'o': DO(int, O) case 'F': DXF(double, F) // FALLTHROUGH case 'f': DOF(double, F) case 'G': DXF(double, G) // FALLTHROUGH case 'g': DOF(double, G) case '{': if (doSave) { doSave = false; } else { // Already in a quiet section. logprintf("sscanf warning: Can't have nestled quiet sections."); } continue; case '}': if (doSave) { logprintf("sscanf warning: Not in a quiet section."); } else { doSave = true; } continue; case 'P': logprintf("sscanf warning: You can't have an optional delimiter."); // FALLTHROUGH case 'p': // 'P' doesn't exist. // Theoretically, for compatibility, this should be: // p<delimiter>, but that will break backwards // compatibility with anyone doing "p<" to use '<' as a // delimiter (doesn't matter how rare that may be). Also, // writing deprecation code and both the new and old code // is more trouble than it's worth, and it's slow. // UPDATE: I wrote the "GetSingleType" code for 'a' and // figured out a way to support legacy and new code, while // still maintaining support for the legacy "p<" separator, // so here it is: ResetDelimiter(); AddDelimiter(GetSingleType(&format)); continue; case 'Z': logprintf("sscanf warning: 'Z' doesn't exist - that would be an optional, deprecated optional string!."); // FALLTHROUGH case 'z': logprintf("sscanf warning: 'z' is deprecated, consider using 'S' instead."); // FALLTHROUGH case 'S': if (IsDelimiter(*string)) { char * dest; int length; if (DoSD(&format, &dest, &length)) { // Send the string to PAWN. if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); amx_SetString(cptr, dest, 0, 0, length); } } break; } // Implicit "else". SkipDefaultEx(&format); // FALLTHROUGH case 's': { // Get the length. int length = GetLength(&format, false); char * dest; DoS(&string, &dest, length, IsEnd(*format)); // Send the string to PAWN. if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); amx_SetString(cptr, dest, 0, 0, length); } } break; case 'U': DX(int, U) // FALLTHROUGH case 'u': DOV(int, U) break; case 'Q': DX(int, Q) // FALLTHROUGH case 'q': DOV(int, Q) break; case 'R': DX(int, R) // FALLTHROUGH case 'r': DOV(int, R) break; case 'A': // We need the default values here. if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoA(&format, &string, cptr, true)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. if (DoA(&format, &string, NULL, true)) { break; } } return SSCANF_FAIL_RETURN; case 'a': if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoA(&format, &string, cptr, false)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. if (DoA(&format, &string, NULL, false)) { break; } } return SSCANF_FAIL_RETURN; case 'E': // We need the default values here. if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoE(&format, &string, cptr, true)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. if (DoE(&format, &string, NULL, true)) { break; } } return SSCANF_FAIL_RETURN; case 'e': if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoE(&format, &string, cptr, false)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. if (DoE(&format, &string, NULL, false)) { break; } } return SSCANF_FAIL_RETURN; case 'K': // We need the default values here. if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoK(amx, &format, &string, cptr, true)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. if (DoK(amx, &format, &string, NULL, true)) { break; } } return SSCANF_FAIL_RETURN; case 'k': if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoK(amx, &format, &string, cptr, false)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. if (DoK(amx, &format, &string, NULL, false)) { break; } } return SSCANF_FAIL_RETURN; case '\'': // Find the end of the literal. { char * str = format, * write = format; bool escape = false; while (!IsEnd(*str) && (escape || *str != '\'')) { if (*str == '\\') { if (escape) { // "\\" - Go back a step to write this // character over the last character (which // just happens to be the same character). --write; } escape = !escape; } else { if (*str == '\'') { // Overwrite the escape character with the // quote character. Must have been // preceeded by a slash or it wouldn't have // got to here in the loop. --write; } escape = false; } // Copy the string over itself to get rid of excess // escape characters. // Not sure if it's faster in the average case to // always do the copy or check if it's needed. // This write is always safe as it makes the string // shorter, so we'll never run out of space. It // will also not overwrite the original string. *write++ = *str++; } if (*str == '\'') { // Correct end. Make a shorter string to search // for. *write = '\0'; // Find the current section of format in string. char * find = strstr(string, format); if (!find) { // Didn't find the string return SSCANF_FAIL_RETURN; } // Found the string. Update the current string // position to the length of the search term // further along from the start of the term. Use // "write" here as we want the escaped string // length. string = find + (write - format); // Move to after the end of the search string. Use // "str" here as we want the unescaped string // length. format = str + 1; } else { logprintf("sscanf warning: Unclosed string literal."); char * find = strstr(string, format); if (!find) { return SSCANF_FAIL_RETURN; } string = find + (write - format); format = str; } } break; case '%': logprintf("sscanf warning: sscanf specifiers do not require '%' before them."); continue; default: logprintf("sscanf warning: Unknown format specifier '%c', skipping.", *(format - 1)); continue; } // Loop cleanup - only skip one spacer so that we can detect // multiple explicit delimiters in a row, for example: // // hi there // // is NOT multiple explicit delimiters in a row (they're // whitespace). This however is: // // hi , , , there // SkipOneSpacer(&string); } } // Temporary to the end of the code. ResetDelimiter(); AddDelimiter(')'); // We don't need code here to handle the case where paramPos was reached, // but the end of the string wasn't - if that's the case there's no // problem as we just ignore excess string data. while (paramPos < paramCount || !doSave) { // Loop through if there's still parameters remaining. if (!*format) { logprintf("sscanf warning: Format specifier does not match parameter count."); if (!doSave) { // Started a quiet section but never explicitly ended it. logprintf("sscanf warning: Unclosed quiet section."); } return SSCANF_TRUE_RETURN; } else if (IsWhitespace(*format)) { ++format; } else { // Do the main switch again. switch (*format++) { case 'L': DE(bool, L) case 'B': DE(int, B) case 'N': DE(int, N) case 'C': DE(char, C) case 'I': case 'D': DE(int, I) case 'H': case 'X': DE(int, H) case 'O': DE(int, O) case 'F': DEF(double, F) case 'G': DEF(double, G) case 'U': DE(int, U) case 'Q': DE(int, Q) case 'R': DE(int, R) case 'A': if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoA(&format, NULL, cptr, true)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. // Also pass NULL data so it knows to only collect the // default values. if (DoA(&format, NULL, NULL, true)) { break; } } return SSCANF_FAIL_RETURN; case 'E': if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoE(&format, NULL, cptr, true)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. // Also pass NULL data so it knows to only collect the // default values. if (DoE(&format, NULL, NULL, true)) { break; } } return SSCANF_FAIL_RETURN; case 'K': if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); if (DoK(amx, &format, NULL, cptr, true)) { break; } } else { // Pass a NULL pointer so data isn't saved anywhere. // Also pass NULL data so it knows to only collect the // default values. if (DoK(amx, &format, NULL, NULL, true)) { break; } } return SSCANF_FAIL_RETURN; case '{': if (doSave) { doSave = false; } else { // Already in a quiet section. logprintf("sscanf warning: Can't have nestled quiet sections."); } break; case '}': if (doSave) { logprintf("sscanf warning: Not in a quiet section."); } else { doSave = true; } break; case 'Z': logprintf("sscanf warning: 'Z' doesn't exist - that would be an optional, deprecated optional string!."); // FALLTHROUGH case 'z': logprintf("sscanf warning: 'z' is deprecated, consider using 'S' instead."); // FALLTHROUGH case 'S': { char * dest; int length; if (DoSD(&format, &dest, &length)) { // Send the string to PAWN. if (doSave) { amx_GetAddr(amx, params[paramPos++], &cptr); amx_SetString(cptr, dest, 0, 0, length); } } } break; case 'P': logprintf("sscanf warning: You can't have an optional delimiter."); // FALLTHROUGH case 'p': // Discard delimiter. This only matters when they have // real inputs, not the default ones used here. GetSingleType(&format); continue; case '\'': // Implicitly optional if the specifiers after it are // optional. { bool escape = false; while (!IsEnd(*format) && (escape || *format != '\'')) { if (*format == '\\') { escape = !escape; } else { escape = false; } ++format; } if (*format == '\'') { ++format; } else { logprintf("sscanf warning: Unclosed string literal."); } } break; // Large block of specifiers all together. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'k': case 'l': case 'n': case 'o': case 'q': case 'r': case 's': case 'u': case 'x': // These are non optional items, but the input string // didn't include them, so we fail - this is in fact the // most basic definition of a fail (the original)! We // don't need any text warnings here - admittedly we don't // know if the format specifier is well formed (there may // not be enough return variables for example), but it // doesn't matter - the coder should have tested for those // things, and the more important thing is that the user // didn't enter the correct data. return SSCANF_FAIL_RETURN; case '%': logprintf("sscanf warning: sscanf specifiers do not require '%' before them."); break; default: logprintf("sscanf warning: Unknown format specifier '%c', skipping.", *(format - 1)); break; } // Don't need any cleanup here. } } if (*format) { do { if (!IsWhitespace(*format)) { // Only print this warning if the remaining characters are not // spaces - spaces are allowed, and sometimes required, on the // ends of formats (e.g. to stop the final 's' specifier // collecting all remaining characters and only get one word). // We could check that the remaining specifier is a valid one, // but this is only a guide - they shouldn't even have other // characters IN the specifier so it doesn't matter - it will // point to a bug, which is the important thing. if (doSave) { if (*format == '}') { logprintf("sscanf warning: Not in a quiet section."); } else if (*format != '{') { // Fix the bad display bug. logprintf("sscanf warning: Format specifier does not match parameter count."); } // Only display it once. break; } else { if (*format == '}') { doSave = true; } else { logprintf("sscanf warning: Format specifier does not match parameter count."); break; } } } ++format; } while (*format); } if (!doSave) { // Started a quiet section but never explicitly ended it. logprintf("sscanf warning: Unclosed quiet section."); } // No more parameters and no more format specifiers which could be read // from - this is a valid return! return SSCANF_TRUE_RETURN; }
cell AMX_NATIVE_CALL ColAndreasNatives::CA_RayCastLineAngleEx(AMX *amx, cell *params) { cell* addr[12]; // Adding a small value prevents a potential crash if all values are the same btVector3 Start = btVector3(btScalar(amx_ctof(params[1]) + 0.00001), btScalar(amx_ctof(params[2]) + 0.00001), btScalar(amx_ctof(params[3]) + 0.00001)); btVector3 End = btVector3(btScalar(amx_ctof(params[4])), btScalar(amx_ctof(params[5])), btScalar(amx_ctof(params[6]))); btVector3 Result; btVector3 Rotation; btQuaternion ObjectRotation; btVector3 ObjectPosition; btScalar RX; btScalar RY; btScalar RZ; uint16_t Model = 0; if (collisionWorld->performRayTestAngleEx(Start, End, Result, RX, RY, RZ, ObjectRotation, ObjectPosition, Model)) { //Get our adderesses for the last 5 amx_GetAddr(amx, params[7], &addr[0]); amx_GetAddr(amx, params[8], &addr[1]); amx_GetAddr(amx, params[9], &addr[2]); amx_GetAddr(amx, params[10], &addr[3]); amx_GetAddr(amx, params[11], &addr[4]); amx_GetAddr(amx, params[12], &addr[5]); amx_GetAddr(amx, params[13], &addr[6]); amx_GetAddr(amx, params[14], &addr[7]); amx_GetAddr(amx, params[15], &addr[8]); amx_GetAddr(amx, params[16], &addr[9]); amx_GetAddr(amx, params[17], &addr[10]); amx_GetAddr(amx, params[18], &addr[11]); *addr[0] = amx_ftoc(Result.getX()); *addr[1] = amx_ftoc(Result.getY()); *addr[2] = amx_ftoc(Result.getZ()); *addr[3] = amx_ftoc(RX); *addr[4] = amx_ftoc(RY); *addr[5] = amx_ftoc(RZ); *addr[6] = amx_ftoc(ObjectPosition.getX()); *addr[7] = amx_ftoc(ObjectPosition.getY()); *addr[8] = amx_ftoc(ObjectPosition.getZ()); collisionWorld->QuatToEuler(ObjectRotation, Result); *addr[9] = amx_ftoc(Result.getX()); *addr[10] = amx_ftoc(Result.getY()); *addr[11] = amx_ftoc(Result.getZ()); return Model; } return 0; }
cell AMX_NATIVE_CALL amx_DC_CMD(AMX* amx, cell* params) { cell *addr; int len; amx_GetAddr(amx, params[2], &addr); amx_StrLen(addr, &len); if(len>127) len=127; ++len; char cmdtext[128]; amx_GetString(cmdtext, addr, 0, len); cmdtext[0] = '_'; // converting string to lower case int pos=0, cmd_end; do{ ++pos; if(('A' <= cmdtext[pos]) && (cmdtext[pos] <= 'Z')) cmdtext[pos] += ('a'-'A'); else if(cmdtext[pos] == '\0') break; else if(cmdtext[pos] == ' ') { cmd_end = pos; cmdtext[pos++] = '\0'; goto loop1_exit; } }while(1); cmd_end = 0; loop1_exit: // search for command index in all AMX instances int pubidx; cell retval, params_addr; int i; for(i=0; i<=lastAMX; ++i) { if((amx_List[i].amx != NULL) && (amx_FindPublic(amx_List[i].amx, cmdtext, &pubidx) == AMX_ERR_NONE)) { // if current AMX instance has OnPlayerCommandReceived callback - invoke it if(amx_List[i].OPCR != 0x7FFFFFFF) { // restore some symbols in cmdtext cmdtext[0] = '/'; if(cmd_end>0) cmdtext[cmd_end] = ' '; amx_PushString(amx_List[i].amx, ¶ms_addr, 0, cmdtext, 0, 0); amx_Push(amx_List[i].amx, params[1]); amx_Exec(amx_List[i].amx, &retval, amx_List[i].OPCR); amx_Release(amx_List[i].amx, params_addr); // if OPCR returned 0 - command execution rejected if(retval == 0) return 1; cmdtext[0] = '_'; // restore AMX-styled command name if(cmd_end>0) // and separate it from parameters (again =/) cmdtext[cmd_end] = ' '; } // remove extra space characters between command name and parameters while(cmdtext[pos] == ' ') pos++; amx_PushString(amx_List[i].amx, ¶ms_addr, 0, cmdtext+pos, 0, 0); amx_Push(amx_List[i].amx, params[1]); amx_Exec(amx_List[i].amx, &retval, pubidx); amx_Release(amx_List[i].amx, params_addr); // if current AMX instance has OnPlayerCommandPerformed callback - invoke it if(amx_List[i].OPCP != 0x7FFFFFFF) { cmdtext[0] = '/'; if(cmd_end>0) cmdtext[cmd_end] = ' '; amx_Push(amx_List[i].amx, retval); amx_PushString(amx_List[i].amx, ¶ms_addr, 0, cmdtext, 0, 0); amx_Push(amx_List[i].amx, params[1]); amx_Exec(amx_List[i].amx, &retval, amx_List[i].OPCP); amx_Release(amx_List[i].amx, params_addr); } return 1; } } // if command wasn't found - perhaps this is an alternative command if(Alts_n != 0) { int hash; // remove extra space characters between command name and parameters //logprintf("attempting to find alt %s, len = %d", cmdtext, (cmdtext[pos])?(pos-1):(pos)); Murmur3(cmdtext, (cmdtext[pos])?(pos-1):(pos), &hash); if(cmdtext[pos]) { pos--; while(cmdtext[++pos] == ' '){} } //logprintf((char*)"Murmur3(%s) = 0x%X", cmdtext, hash); boost::unordered_map<int,int>::const_iterator alt; for(i=0; i<=lastAMX; ++i) { if((amx_List[i].amx != NULL) && ((alt = Alts[i].find(hash)) != Alts[i].end())) { pubidx = alt->second; //logprintf("found alt: %s, amx = %d, idx = %d", cmdtext, (int)amx, pubidx); if(amx_List[i].OPCR != 0x7FFFFFFF) { // restore some symbols in cmdtext cmdtext[0] = '/'; if(cmd_end>0) cmdtext[cmd_end] = ' '; amx_PushString(amx_List[i].amx, ¶ms_addr, 0, cmdtext, 0, 0); amx_Push(amx_List[i].amx, params[1]); amx_Exec(amx_List[i].amx, &retval, amx_List[i].OPCR); amx_Release(amx_List[i].amx, params_addr); // if OPCR returned 0 - command execution rejected if(retval == 0) return 1; cmdtext[0] = '_'; // restore AMX-styled command name if(cmd_end>0) // and separate it from parameters (again =/) cmdtext[cmd_end] = ' '; } // remove extra space characters between command name and parameters while(cmdtext[pos] == ' ') pos++; amx_PushString(amx_List[i].amx, ¶ms_addr, 0, cmdtext+pos, 0, 0); amx_Push(amx_List[i].amx, params[1]); amx_Exec(amx_List[i].amx, &retval, pubidx); amx_Release(amx_List[i].amx, params_addr); // if current AMX instance has OnPlayerCommandPerformed callback - invoke it if(amx_List[i].OPCP != 0x7FFFFFFF) { cmdtext[0] = '/'; if(cmd_end>0) cmdtext[cmd_end] = ' '; amx_Push(amx_List[i].amx, retval); amx_PushString(amx_List[i].amx, ¶ms_addr, 0, cmdtext, 0, 0); amx_Push(amx_List[i].amx, params[1]); amx_Exec(amx_List[i].amx, &retval, amx_List[i].OPCP); amx_Release(amx_List[i].amx, params_addr); } return 1; } } } // if command not found - call OnPlayerCommandPerformed callback in gamemode AMX (success = -1) if(amx_List[0].OPCP != 0x7FFFFFFF) { cmdtext[0] = '/'; if(cmd_end>0) cmdtext[cmd_end] = ' '; amx_Push(amx_List[0].amx, -1); amx_PushString(amx_List[0].amx, ¶ms_addr, 0, cmdtext, 0, 0); amx_Push(amx_List[0].amx, params[1]); amx_Exec(amx_List[0].amx, &retval, amx_List[0].OPCP); amx_Release(amx_List[0].amx, params_addr); } return 1; }
cell AMX_NATIVE_CALL amx_RegisterAlt(AMX* amx, cell* params) { int amx_n; for(amx_n=0; amx_n<=lastAMX; ++amx_n) if(amx == amx_List[amx_n].amx) break; if(amx_n>lastAMX) // if amx wasn't found in list return 0; cell *addr; int len; amx_GetAddr(amx, params[1], &addr); amx_StrLen(addr, &len); if(len>31) len=31; ++len; char cmd[32]; amx_GetString(cmd, addr, 0, len); cmd[0] = '_'; // converting string to lower case int pos=0; do{ ++pos; if(('A' <= cmd[pos]) && (cmd[pos] <= 'Z')) cmd[pos] += ('a'-'A'); else if(cmd[pos] == '\0') break; else if((cmd[pos] == ' ') || (cmd[pos] == '\t')) { cmd[pos] = '\0'; break; } }while(1); int pubidx; if(amx_FindPublic(amx, cmd, &pubidx) != AMX_ERR_NONE) { //logprintf((char*)"RegisterAlt: Couldn't find function %s", cmd); return 1; } int alt_n = (params[0]/4), hash; //logprintf("RegisterAlt: alts = %d", alt_n-1); do{ if(amx_GetAddr(amx, params[alt_n], &addr) != AMX_ERR_NONE) continue; amx_StrLen(addr, &len); if(len>31) len=31; // command length must be up to 31 chars ++len; amx_GetString(cmd, addr, 0, len); cmd[0] = '_'; pos = 0; do{ ++pos; if(('A' <= cmd[pos]) && (cmd[pos] <= 'Z')) cmd[pos] += ('a'-'A'); else if(cmd[pos] == '\0') break; else if((cmd[pos] == ' ') || (cmd[pos] == '\t')) { cmd[pos] = '\0'; break; } }while(1); //logprintf((char*)"%s, len = %d", cmd, pos); Murmur3(cmd, pos, &hash); //logprintf("RegisterAlt: Murmur3(%s) = 0x%X", cmd, hash); Alts[amx_n].insert(std::make_pair(hash, pubidx)); Alts_n++; //logprintf((char*)"RegisterAlt: new alt - %s, amx = %d, pubidx = %d", cmd, amx, pubidx); }while(--alt_n > 1); return 1; }
// native mysql_statement_execute(connectionHandle, statementId, callback[], dataId, {Float,_}:...); static cell AMX_NATIVE_CALL n_mysql_statement_execute(AMX* amx, cell* params) { if (params[0] < 4 * sizeof(cell)) { logprintf("SCRIPT: Bad parameter count (%d < 4): ", params[0]); return 0; } ConnectionHost* connection = connectionController->connection(params[1]); const Statement* statement = statementRegistry->At(params[2]); if (connection == nullptr || statement == nullptr) return 0; char* callback; amx_StrParam(amx, params[3], callback); unsigned int dataId = params[4]; const int parameterOffset = 4; if ((statement->Parameters().length() + parameterOffset) * sizeof(cell) != params[0]) { logprintf("[lvp_MySQL] The statement call expected %d parameters, received %d.", statement->Parameters().length() + parameterOffset, params[0] / sizeof(cell)); logprintf("[lvp_MySQL] Statement: [%s].", statement->Query().c_str()); return 0; } std::vector<std::string> parameters; const std::string& parameterTypes = statement->Parameters(); char buffer[256]; cell* address; int length = 0; for (unsigned int index = 0; index < parameterTypes.length(); ++index) { if (amx_GetAddr(amx, params[parameterOffset + 1 + index], &address) != AMX_ERR_NONE) return 0; // this case shouldn't happen. switch (parameterTypes[index]) { case 'i': // integers. snprintf(buffer, sizeof(buffer), "%d", *address); parameters.push_back(buffer); break; case 'f': // floats. snprintf(buffer, sizeof(buffer), "%.4f", amx_ctof(*address)); parameters.push_back(buffer); break; case 's': // strings. amx_StrLen(address, &length); amx_GetString(buffer, address, 0, std::min(static_cast<unsigned int>(length + 1), sizeof(buffer))); buffer[sizeof(buffer)-1] = 0; parameters.push_back(escape_string_parameter(buffer)); break; default: // other (unhandled) types. logprintf("[lvp_MySQL] Unknown parameter type in statement: '%c'. Cannot execute.", parameterTypes[index]); logprintf("[lvp_MySQL] Statement: [%s].", statement->Query().c_str()); return 0; } } std::string query; if (QueryBuilder::Build(statement, parameters, query) == false) { logprintf("[lvp_MySQL] Unable to build the query, cannot execute this statement."); logprintf("[lvp_MySQL] Statement: [%s].", statement->Query().c_str()); return 0; } connection->query(query.c_str(), callback, dataId); return 1; }