Path: blob/main/sys/contrib/openzfs/module/lua/lauxlib.c
48383 views
// SPDX-License-Identifier: MIT1/*2** $Id: lauxlib.c,v 1.248.1.1 2013/04/12 18:48:47 roberto Exp $3** Auxiliary functions for building Lua libraries4** See Copyright Notice in lua.h5*/678/* This file uses only the official API of Lua.9** Any function declared here could be written as an application function.10*/1112#define lauxlib_c13#define LUA_LIB1415#include <sys/lua/lua.h>1617#include <sys/lua/lauxlib.h>181920/*21** {======================================================22** Traceback23** =======================================================24*/252627#define LEVELS1 12 /* size of the first part of the stack */28#define LEVELS2 10 /* size of the second part of the stack */29303132/*33** search for 'objidx' in table at index -1.34** return 1 + string at top if find a good name.35*/36static int findfield (lua_State *L, int objidx, int level) {37if (level == 0 || !lua_istable(L, -1))38return 0; /* not found */39lua_pushnil(L); /* start 'next' loop */40while (lua_next(L, -2)) { /* for each pair in table */41if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */42if (lua_rawequal(L, objidx, -1)) { /* found object? */43lua_pop(L, 1); /* remove value (but keep name) */44return 1;45}46else if (findfield(L, objidx, level - 1)) { /* try recursively */47lua_remove(L, -2); /* remove table (but keep name) */48lua_pushliteral(L, ".");49lua_insert(L, -2); /* place '.' between the two names */50lua_concat(L, 3);51return 1;52}53}54lua_pop(L, 1); /* remove value */55}56return 0; /* not found */57}585960static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {61int top = lua_gettop(L);62lua_getinfo(L, "f", ar); /* push function */63lua_pushglobaltable(L);64if (findfield(L, top + 1, 2)) {65lua_copy(L, -1, top + 1); /* move name to proper place */66lua_pop(L, 2); /* remove pushed values */67return 1;68}69else {70lua_settop(L, top); /* remove function and global table */71return 0;72}73}747576static void pushfuncname (lua_State *L, lua_Debug *ar) {77if (*ar->namewhat != '\0') /* is there a name? */78lua_pushfstring(L, "function " LUA_QS, ar->name);79else if (*ar->what == 'm') /* main? */80lua_pushliteral(L, "main chunk");81else if (*ar->what == 'C') {82if (pushglobalfuncname(L, ar)) {83lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));84lua_remove(L, -2); /* remove name */85}86else87lua_pushliteral(L, "?");88}89else90lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);91}929394static int countlevels (lua_State *L) {95lua_Debug ar;96int li = 1, le = 1;97/* find an upper bound */98while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }99/* do a binary search */100while (li < le) {101int m = (li + le)/2;102if (lua_getstack(L, m, &ar)) li = m + 1;103else le = m;104}105return le - 1;106}107108109LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,110const char *msg, int level) {111lua_Debug ar;112int top = lua_gettop(L);113int numlevels = countlevels(L1);114int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;115if (msg) lua_pushfstring(L, "%s\n", msg);116lua_pushliteral(L, "stack traceback:");117while (lua_getstack(L1, level++, &ar)) {118if (level == mark) { /* too many levels? */119lua_pushliteral(L, "\n\t..."); /* add a '...' */120level = numlevels - LEVELS2; /* and skip to last ones */121}122else {123lua_getinfo(L1, "Slnt", &ar);124lua_pushfstring(L, "\n\t%s:", ar.short_src);125if (ar.currentline > 0)126lua_pushfstring(L, "%d:", ar.currentline);127lua_pushliteral(L, " in ");128pushfuncname(L, &ar);129if (ar.istailcall)130lua_pushliteral(L, "\n\t(...tail calls...)");131lua_concat(L, lua_gettop(L) - top);132}133}134lua_concat(L, lua_gettop(L) - top);135}136137/* }====================================================== */138139140/*141** {======================================================142** Error-report functions143** =======================================================144*/145146LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {147lua_Debug ar;148if (!lua_getstack(L, 0, &ar)) /* no stack frame? */149return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);150lua_getinfo(L, "n", &ar);151if (strcmp(ar.namewhat, "method") == 0) {152narg--; /* do not count `self' */153if (narg == 0) /* error is in the self argument itself? */154return luaL_error(L, "calling " LUA_QS " on bad self (%s)",155ar.name, extramsg);156}157if (ar.name == NULL)158ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";159return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",160narg, ar.name, extramsg);161}162163164static int typeerror (lua_State *L, int narg, const char *tname) {165const char *msg = lua_pushfstring(L, "%s expected, got %s",166tname, luaL_typename(L, narg));167return luaL_argerror(L, narg, msg);168}169170171static void tag_error (lua_State *L, int narg, int tag) {172typeerror(L, narg, lua_typename(L, tag));173}174175176LUALIB_API void luaL_where (lua_State *L, int level) {177lua_Debug ar;178if (lua_getstack(L, level, &ar)) { /* check function at level */179lua_getinfo(L, "Sl", &ar); /* get info about it */180if (ar.currentline > 0) { /* is there info? */181lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);182return;183}184}185lua_pushliteral(L, ""); /* else, no information available... */186}187188189LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {190va_list argp;191va_start(argp, fmt);192luaL_where(L, 1);193lua_pushvfstring(L, fmt, argp);194va_end(argp);195lua_concat(L, 2);196return lua_error(L);197}198199200#if !defined(inspectstat) /* { */201202#if defined(LUA_USE_POSIX)203204#include <sys/wait.h>205206/*207** use appropriate macros to interpret 'pclose' return status208*/209#define inspectstat(stat,what) \210if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \211else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }212213#else214215#define inspectstat(stat,what) /* no op */216217#endif218219#endif /* } */220221222/* }====================================================== */223224225/*226** {======================================================227** Userdata's metatable manipulation228** =======================================================229*/230231LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {232luaL_getmetatable(L, tname); /* try to get metatable */233if (!lua_isnil(L, -1)) /* name already in use? */234return 0; /* leave previous value on top, but return 0 */235lua_pop(L, 1);236lua_newtable(L); /* create metatable */237lua_pushvalue(L, -1);238lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */239return 1;240}241242243LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {244luaL_getmetatable(L, tname);245lua_setmetatable(L, -2);246}247248249LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {250void *p = lua_touserdata(L, ud);251if (p != NULL) { /* value is a userdata? */252if (lua_getmetatable(L, ud)) { /* does it have a metatable? */253luaL_getmetatable(L, tname); /* get correct metatable */254if (!lua_rawequal(L, -1, -2)) /* not the same? */255p = NULL; /* value is a userdata with wrong metatable */256lua_pop(L, 2); /* remove both metatables */257return p;258}259}260return NULL; /* value is not a userdata with a metatable */261}262263264LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {265void *p = luaL_testudata(L, ud, tname);266if (p == NULL) typeerror(L, ud, tname);267return p;268}269270/* }====================================================== */271272273/*274** {======================================================275** Argument check functions276** =======================================================277*/278279LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,280const char *const lst[]) {281const char *name = (def) ? luaL_optstring(L, narg, def) :282luaL_checkstring(L, narg);283int i;284for (i=0; lst[i]; i++)285if (strcmp(lst[i], name) == 0)286return i;287return luaL_argerror(L, narg,288lua_pushfstring(L, "invalid option " LUA_QS, name));289}290291292LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {293/* keep some extra space to run error routines, if needed */294const int extra = LUA_MINSTACK;295if (!lua_checkstack(L, space + extra)) {296if (msg)297luaL_error(L, "stack overflow (%s)", msg);298else299luaL_error(L, "stack overflow");300}301}302303304LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {305if (lua_type(L, narg) != t)306tag_error(L, narg, t);307}308309310LUALIB_API void luaL_checkany (lua_State *L, int narg) {311if (lua_type(L, narg) == LUA_TNONE)312luaL_argerror(L, narg, "value expected");313}314315316LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {317const char *s = lua_tolstring(L, narg, len);318if (!s) tag_error(L, narg, LUA_TSTRING);319return s;320}321322323LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,324const char *def, size_t *len) {325if (lua_isnoneornil(L, narg)) {326if (len)327*len = (def ? strlen(def) : 0);328return def;329}330else return luaL_checklstring(L, narg, len);331}332333334LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {335int isnum;336lua_Number d = lua_tonumberx(L, narg, &isnum);337if (!isnum)338tag_error(L, narg, LUA_TNUMBER);339return d;340}341342343LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {344return luaL_opt(L, luaL_checknumber, narg, def);345}346347348LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {349int isnum;350lua_Integer d = lua_tointegerx(L, narg, &isnum);351if (!isnum)352tag_error(L, narg, LUA_TNUMBER);353return d;354}355356357LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {358int isnum;359lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);360if (!isnum)361tag_error(L, narg, LUA_TNUMBER);362return d;363}364365366LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,367lua_Integer def) {368return luaL_opt(L, luaL_checkinteger, narg, def);369}370371372LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,373lua_Unsigned def) {374return luaL_opt(L, luaL_checkunsigned, narg, def);375}376377/* }====================================================== */378379380/*381** {======================================================382** Generic Buffer manipulation383** =======================================================384*/385386/*387** check whether buffer is using a userdata on the stack as a temporary388** buffer389*/390#define buffonstack(B) ((B)->b != (B)->initb)391392393/*394** returns a pointer to a free area with at least 'sz' bytes395*/396LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {397lua_State *L = B->L;398if (B->size - B->n < sz) { /* not enough space? */399char *newbuff;400size_t newsize = B->size * 2; /* double buffer size */401if (newsize - B->n < sz) /* not big enough? */402newsize = B->n + sz;403if (newsize < B->n || newsize - B->n < sz)404luaL_error(L, "buffer too large");405/* create larger buffer */406newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));407/* move content to new buffer */408memcpy(newbuff, B->b, B->n * sizeof(char));409if (buffonstack(B))410lua_remove(L, -2); /* remove old buffer */411B->b = newbuff;412B->size = newsize;413}414return &B->b[B->n];415}416417418LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {419char *b = luaL_prepbuffsize(B, l);420memcpy(b, s, l * sizeof(char));421luaL_addsize(B, l);422}423424425LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {426luaL_addlstring(B, s, strlen(s));427}428429430LUALIB_API void luaL_pushresult (luaL_Buffer *B) {431lua_State *L = B->L;432lua_pushlstring(L, B->b, B->n);433if (buffonstack(B))434lua_remove(L, -2); /* remove old buffer */435}436437438LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {439luaL_addsize(B, sz);440luaL_pushresult(B);441}442443444LUALIB_API void luaL_addvalue (luaL_Buffer *B) {445lua_State *L = B->L;446size_t l;447const char *s = lua_tolstring(L, -1, &l);448if (buffonstack(B))449lua_insert(L, -2); /* put value below buffer */450luaL_addlstring(B, s, l);451lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */452}453454455LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {456B->L = L;457B->b = B->initb;458B->n = 0;459B->size = LUAL_BUFFERSIZE;460}461462463LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {464luaL_buffinit(L, B);465return luaL_prepbuffsize(B, sz);466}467468/* }====================================================== */469470471/*472** {======================================================473** Reference system474** =======================================================475*/476477/* index of free-list header */478#define freelist 0479480481LUALIB_API int luaL_ref (lua_State *L, int t) {482int ref;483if (lua_isnil(L, -1)) {484lua_pop(L, 1); /* remove from stack */485return LUA_REFNIL; /* `nil' has a unique fixed reference */486}487t = lua_absindex(L, t);488lua_rawgeti(L, t, freelist); /* get first free element */489ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */490lua_pop(L, 1); /* remove it from stack */491if (ref != 0) { /* any free element? */492lua_rawgeti(L, t, ref); /* remove it from list */493lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */494}495else /* no free elements */496ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */497lua_rawseti(L, t, ref);498return ref;499}500501502LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {503if (ref >= 0) {504t = lua_absindex(L, t);505lua_rawgeti(L, t, freelist);506lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */507lua_pushinteger(L, ref);508lua_rawseti(L, t, freelist); /* t[freelist] = ref */509}510}511512/* }====================================================== */513514515/*516** {======================================================517** Load functions518** =======================================================519*/520521typedef struct LoadS {522const char *s;523size_t size;524} LoadS;525526527static const char *getS (lua_State *L, void *ud, size_t *size) {528LoadS *ls = (LoadS *)ud;529(void)L; /* not used */530if (ls->size == 0) return NULL;531*size = ls->size;532ls->size = 0;533return ls->s;534}535536537LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,538const char *name, const char *mode) {539LoadS ls;540ls.s = buff;541ls.size = size;542return lua_load(L, getS, &ls, name, mode);543}544545546LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {547return luaL_loadbuffer(L, s, strlen(s), s);548}549550/* }====================================================== */551552553554LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {555if (!lua_getmetatable(L, obj)) /* no metatable? */556return 0;557lua_pushstring(L, event);558lua_rawget(L, -2);559if (lua_isnil(L, -1)) {560lua_pop(L, 2); /* remove metatable and metafield */561return 0;562}563else {564lua_remove(L, -2); /* remove only metatable */565return 1;566}567}568569570LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {571obj = lua_absindex(L, obj);572if (!luaL_getmetafield(L, obj, event)) /* no metafield? */573return 0;574lua_pushvalue(L, obj);575lua_call(L, 1, 1);576return 1;577}578579580LUALIB_API int luaL_len (lua_State *L, int idx) {581int l;582int isnum;583lua_len(L, idx);584l = (int)lua_tointegerx(L, -1, &isnum);585if (!isnum)586luaL_error(L, "object length is not a number");587lua_pop(L, 1); /* remove object */588return l;589}590591592LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {593if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */594switch (lua_type(L, idx)) {595case LUA_TNUMBER:596case LUA_TSTRING:597lua_pushvalue(L, idx);598break;599case LUA_TBOOLEAN:600lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));601break;602case LUA_TNIL:603lua_pushliteral(L, "nil");604break;605default:606lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),607lua_topointer(L, idx));608break;609}610}611return lua_tolstring(L, -1, len);612}613614615/*616** {======================================================617** Compatibility with 5.1 module functions618** =======================================================619*/620#if defined(LUA_COMPAT_MODULE)621622static const char *luaL_findtable (lua_State *L, int idx,623const char *fname, int szhint) {624const char *e;625if (idx) lua_pushvalue(L, idx);626do {627e = strchr(fname, '.');628if (e == NULL) e = fname + strlen(fname);629lua_pushlstring(L, fname, e - fname);630lua_rawget(L, -2);631if (lua_isnil(L, -1)) { /* no such field? */632lua_pop(L, 1); /* remove this nil */633lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */634lua_pushlstring(L, fname, e - fname);635lua_pushvalue(L, -2);636lua_settable(L, -4); /* set new table into field */637}638else if (!lua_istable(L, -1)) { /* field has a non-table value? */639lua_pop(L, 2); /* remove table and value */640return fname; /* return problematic part of the name */641}642lua_remove(L, -2); /* remove previous table */643fname = e + 1;644} while (*e == '.');645return NULL;646}647648649/*650** Count number of elements in a luaL_Reg list.651*/652static int libsize (const luaL_Reg *l) {653int size = 0;654for (; l && l->name; l++) size++;655return size;656}657658659/*660** Find or create a module table with a given name. The function661** first looks at the _LOADED table and, if that fails, try a662** global variable with that name. In any case, leaves on the stack663** the module table.664*/665LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,666int sizehint) {667luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */668lua_getfield(L, -1, modname); /* get _LOADED[modname] */669if (!lua_istable(L, -1)) { /* not found? */670lua_pop(L, 1); /* remove previous result */671/* try global variable (and create one if it does not exist) */672lua_pushglobaltable(L);673if (luaL_findtable(L, 0, modname, sizehint) != NULL)674luaL_error(L, "name conflict for module " LUA_QS, modname);675lua_pushvalue(L, -1);676lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */677}678lua_remove(L, -2); /* remove _LOADED table */679}680681682LUALIB_API void luaL_openlib (lua_State *L, const char *libname,683const luaL_Reg *l, int nup) {684luaL_checkversion(L);685if (libname) {686luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */687lua_insert(L, -(nup + 1)); /* move library table to below upvalues */688}689if (l)690luaL_setfuncs(L, l, nup);691else692lua_pop(L, nup); /* remove upvalues */693}694695#endif696/* }====================================================== */697698/*699** set functions from list 'l' into table at top - 'nup'; each700** function gets the 'nup' elements at the top as upvalues.701** Returns with only the table at the stack.702*/703LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {704luaL_checkversion(L);705luaL_checkstack(L, nup, "too many upvalues");706for (; l->name != NULL; l++) { /* fill the table with given functions */707int i;708for (i = 0; i < nup; i++) /* copy upvalues to the top */709lua_pushvalue(L, -nup);710lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */711lua_setfield(L, -(nup + 2), l->name);712}713lua_pop(L, nup); /* remove upvalues */714}715716717/*718** ensure that stack[idx][fname] has a table and push that table719** into the stack720*/721LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {722lua_getfield(L, idx, fname);723if (lua_istable(L, -1)) return 1; /* table already there */724else {725lua_pop(L, 1); /* remove previous result */726idx = lua_absindex(L, idx);727lua_newtable(L);728lua_pushvalue(L, -1); /* copy to be left at top */729lua_setfield(L, idx, fname); /* assign new table to field */730return 0; /* false, because did not find table there */731}732}733734735/*736** stripped-down 'require'. Calls 'openf' to open a module,737** registers the result in 'package.loaded' table and, if 'glb'738** is true, also registers the result in the global table.739** Leaves resulting module on the top.740*/741LUALIB_API void luaL_requiref (lua_State *L, const char *modname,742lua_CFunction openf, int glb) {743lua_pushcfunction(L, openf);744lua_pushstring(L, modname); /* argument to open function */745lua_call(L, 1, 1); /* open module */746luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");747lua_pushvalue(L, -2); /* make copy of module (call result) */748lua_setfield(L, -2, modname); /* _LOADED[modname] = module */749lua_pop(L, 1); /* remove _LOADED table */750if (glb) {751lua_pushvalue(L, -1); /* copy of 'mod' */752lua_setglobal(L, modname); /* _G[modname] = module */753}754}755756757LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,758const char *r) {759const char *wild;760size_t l = strlen(p);761luaL_Buffer b;762luaL_buffinit(L, &b);763while ((wild = strstr(s, p)) != NULL) {764luaL_addlstring(&b, s, wild - s); /* push prefix */765luaL_addstring(&b, r); /* push replacement in place of pattern */766s = wild + l; /* continue after `p' */767}768luaL_addstring(&b, s); /* push last suffix */769luaL_pushresult(&b);770return lua_tostring(L, -1);771}772773774LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {775const lua_Number *v = lua_version(L);776if (v != lua_version(NULL))777luaL_error(L, "multiple Lua VMs detected");778else if (*v != ver)779luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",780ver, *v);781/* check conversions number -> integer types */782lua_pushnumber(L, -(lua_Number)0x1234);783if (lua_tointeger(L, -1) != -0x1234 ||784lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234)785luaL_error(L, "bad conversion number->int;"786" must recompile Lua with proper settings");787lua_pop(L, 1);788}789790#if defined(_KERNEL)791792EXPORT_SYMBOL(luaL_argerror);793EXPORT_SYMBOL(luaL_error);794EXPORT_SYMBOL(luaL_loadbufferx);795EXPORT_SYMBOL(luaL_newmetatable);796EXPORT_SYMBOL(luaL_traceback);797798#endif799800801