commit 818a9f4254d603e3abd77d7ee9c2575fd34a65d7 Author: qwjyh Date: Sat Aug 17 16:26:07 2024 +0200 init with uname diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..140f8cf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.so diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..713406d --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +cc = gcc +CFLAGS := $(CFLAGS) -Wall -Wextra -D_GNU_SOURCE + +LIBFLAGS = $(pkg-config --libs --cflags lua) + +objs = uname.so + +all : $(objs) + +%.so : %.c %.h + $(cc) -o $@ $(CFLAGS) $(LIBFLAGS) -fPIC -shared $< + +.PHONY : clean +clean : + -rm $(objs) diff --git a/uname.c b/uname.c new file mode 100644 index 0000000..63020dc --- /dev/null +++ b/uname.c @@ -0,0 +1,81 @@ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include "uname.h" +#include +#include +#include + +#define ERRBUF_SIZE 1024 + +static int l_numid(lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + printf("%f\n", x); + + lua_pushnumber(L, x); + + return 1; +} + +/* + * Add one + */ +long long plus_one(int x) { + return x + 1; +} + +static int l_plus_one(lua_State *L) { + // argument number check is not conventional in lua? + int argc = lua_gettop(L); + if (argc != 1) + return luaL_error(L, "Invalid number of argument"); + + // Type check and get + lua_Integer x = luaL_checkinteger(L, 1); + + lua_Integer result = plus_one(x); + + // Push the result + lua_pushinteger(L, result); + // How many elements from the top is return value + return 1; +} + +static int l_uname(lua_State *L) { + struct utsname name; + if (uname(&name)) { + char errbuf[ERRBUF_SIZE]; + if (strerror_r(errno, errbuf, ERRBUF_SIZE)) + perror("Error while making error msg"); + return luaL_error(L, errbuf); + } + lua_newtable(L); + lua_pushstring(L, "sysname"); + lua_pushstring(L, name.sysname); + lua_settable(L, -3); + lua_pushstring(L, "machine"); + lua_pushstring(L, name.machine); + lua_settable(L, -3); + lua_pushstring(L, "release"); + lua_pushstring(L, name.release); + lua_settable(L, -3); + lua_pushstring(L, "version"); + lua_pushstring(L, name.version); + lua_settable(L, -3); + return 1; +} + +static const struct luaL_Reg llib_uname [] = { + {"uname", l_uname}, + {"numid", l_numid}, + {"plusone", l_plus_one}, + {NULL, NULL}, +}; + +// for `require` +int luaopen_uname(lua_State *L) { + luaL_newlib(L, llib_uname); + return 1; +} diff --git a/uname.h b/uname.h new file mode 100644 index 0000000..fa715c6 --- /dev/null +++ b/uname.h @@ -0,0 +1,16 @@ +#ifndef L_UNAME_H +#define L_UNAME_H +#include +#include +#include +#include + +long long plus_one(int x); + +static int l_numid(lua_State *L); +static int l_plus_one(lua_State *L); +static int l_uname(lua_State *L); + +int luaopen_uname(lua_State *L); + +#endif