Line number where SWIG_RuntimeError occurs - lua

I am running Lua with a C++ library via swig. When a swig runtime error occurs I would like to know the line which caused the problem. The error message I receive does not have this information.
How can I find which line in the Lua code triggered the error?
For example suppose I have a swig function "swigstringcount" and it takes a string:
local n=4
local m=swigstringcount(n)
print (m,n)
This (obviously wrong) code produces an error on line two. Currently all I get is
error:SWIG_RuntimeError: swigstringcount requires a string
I want it to tell me that line 2 produced the error, like standard Lua error messages.

Based on this method for getting debug info from the Lua C API I've put together a (slightly messy) example of how you can integrate that into a SWIG interface:
%module test
%{
#undef SWIG_fail_arg
#define SWIG_fail_arg(func_name,argnum,type) \
{lua_Debug ar;\
lua_getstack(L, 1, &ar);\
lua_getinfo(L, "nSl", &ar);\
lua_pushfstring(L,"Error (%s:%d) in %s (arg %d), expected '%s' got '%s'",\
ar.source,ar.currentline,func_name,argnum,type,SWIG_Lua_typename(L,argnum));\
goto fail;}
%}
%include <std_string.i>
%inline %{
void func(const std::string& str) {}
%}
This basically replaces the default SWIG_fail_arg macro with a modified one that gets and prints some debug info.
I tested it with the latest SWIG trunk (I think you might be using an older version since the text I see didn't quite match), but I was able to do:
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> require('test')
> local n=4
> test.func(n)
Error (=stdin:1) in func (arg 1), expected 'std::string const &' got 'nil'
stack traceback:
[C]: in function 'func'
stdin:1: in main chunk
[C]: ?
I seem to have more debug info (i.e. a full stack trace) there already though.

Related

VS2019 and _NO_CRT_STDIO_INLINE, how to explain this weirdo?

Please check my short code below.
pwrapper.h
#include <stdio.h>
#include <stdarg.h>
extern"C" int mm_printfA(const char *fmt, ...);
extern"C" int mm_printfW(const wchar_t *fmt, ...);
pwrapper.cpp
#include "pwrapper.h"
int mm_printfA(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
int ret = vprintf(fmt, args);
va_end(args);
return ret;
}
int mm_printfW(const wchar_t *fmt, ...)
{
va_list args;
va_start(args, fmt);
int ret = vwprintf(fmt, args);
va_end(args);
return ret;
}
main.cpp
#include "pwrapper.h"
// cl /MT /D _NO_CRT_STDIO_INLINE main.cpp pwrapper.cpp
void main()
{
mm_printfA("What is %d?\n", 123);
}
#if 0
void usedull()
{
vprintf(NULL, NULL);
vwprintf(NULL, NULL);
}
#endif
For some reason, I need to compile it with _NO_CRT_STDIO_INLINE, like this:
cl /MT /D _NO_CRT_STDIO_INLINE main.cpp pwrapper.cpp
But link stage fails saying unresolved external symbol vwprintf and vprintf .
A very weird workaround I find out is: Enable the usedull() function body -- although never be called, and, link through pwrapper.lib, using bb.bat below:
#setlocal EnableDelayedExpansion
#set CFLAGS=/D _NO_CRT_STDIO_INLINE
cl /nologo /c /MT %CFLAGS% pwrapper.cpp
#if errorlevel 1 exit /b 4
lib /nologo /out:pwrapper.lib pwrapper.obj
#if errorlevel 1 exit /b 4
cl /nologo /c /MT main.cpp
#if errorlevel 1 exit /b 4
link /nologo main.obj pwrapper.lib
#if errorlevel 1 exit /b 4
Well, this really works, but why?
This is not a pleasant workaround, because each exe project needs to include a "useless" usedull() function. So, is there any better way?
I really can't tell why this workaround works, an explanation of it is very welcome.
==== Some Clarification ====
There were two main.cpp in my original post. Let me name them separately for later reference in case someone would bother to answer this weird question.
main.0.cpp refers to the one without usedull().
main.1.cpp refers to the one with usedull().
In this question, I use VC++ headers and libs for application(not for kernel), and
I compile main.0.cpp and main.1.cpp without _NO_CRT_STDIO_INLINE.
I always compile pwrapper.cpp with _NO_CRT_STDIO_INLINE.
Whether having pwrapper.obj go through pwrapper.lib produce the same result in this issue.
In short:
compiling pwrapper.cpp with -D _NO_CRT_STDIO_INLINE tells the compiler you are going to provide your own implementation of vprintf and vwprintf at link time, and
compiling main.cpp without -D _NO_CRT_STDIO_INLINE tells the compiler to include implementations of vprintf and vwprintf which are used at link time to satisfy both the references from usedull and mm_printfA/mm_printfW
so, this particular combination works to resolve all undefined symbols at link time. See below for more discussion however.
Discussion
In stdio.h, vprintf (which I'll focus on, but vwprintf is configured in the same way) is defined like so:
_Check_return_opt_
_CRT_STDIO_INLINE int __CRTDECL vprintf(
_In_z_ _Printf_format_string_ char const* const _Format,
va_list _ArgList
)
#if defined _NO_CRT_STDIO_INLINE
;
#else
{
return _vfprintf_l(stdout, _Format, NULL, _ArgList);
}
#endif
Note that
if _NO_CRT_STDIO_INLINE is defined, this becomes a forward declaration
whereas if it is not defined, the full body is included in the compilation of the including translation unit.
Additionally, in corecrt_stdio_config.h whether _NO_CRT_STDIO_INLINE is defined determines the value of _CRT_STDIO_INLINE; if it is defined, _CRT_STDIO_INLINE is defined as empty, otherwise it is defined as __inline.
Putting these together,
if _NO_CRT_STDIO_INLINE is not defined, these functions will be candidates for inline expansion,
otherwise a separate implementation of that function will need to be provided at link time.
Default Compilation (no /O1, /O2, no _NO_CRT_STDIO_INLINE)
The above works with the specific compile and link invocations you are using, as without optimization the compiler will simply include the function body in the compilation of main.1.obj. You can see this using dumpbin; running dumpbin -symbols main.1.obj | find "| vprintf" prints:
01D 00000000 SECT8 notype () External | vprintf
showing that main.1.obj provides vprintf as an externally available symbol.
Checking pwrapper.obj, we get:
00A 00000000 UNDEF notype () External | vprintf
showing that vprintf is undefined in this object file, and will need to be provided at link time.
Optimisation for Inline Expansion
However, if we change the optimisation option for inline expansion, we get different results. Using even the first level of optimisation (-Ob1, included in -O1 and -O2) like so:
cl -c -Ob1 main.1.cpp
causes the compiler to incorporate the body of vprintf directly into usedull, and remove the separate implementation of vprintf, which can be confirmed using dumpbin. So, as you would now expect, attempting to link main.1.obj and pwrapper.obj together will once again give your original error:
pwrapper.obj : error LNK2019: unresolved external symbol vwprintf referenced in function mm_printfW
pwrapper.obj : error LNK2019: unresolved external symbol vprintf referenced in function mm_printfA
main.exe : fatal error LNK1120: 2 unresolved externals
Multiple Implementations?
So, following on from that it is apparent that compiling both files with -D _NO_CRT_STDIO_INLINE will fail as there will be no implementations of the relevant methods. What about if both are compiled without this definition?
If we check the object files, both have defined symbols for vprintf:
01D 00000000 SECT8 notype () External | vprintf
and:
01A 00000000 SECT7 notype () External | vprintf
which under normal circumstances would result in errors due both to multiple definitions of a symbol and violations of the One Definition Rule. However, when performing inline expansion, the compiler and linker have your back. As per 2:
Rather than expand an inline function defined in a header file, the compiler may create it as a callable function in more than one translation unit. The compiler marks the generated function for the linker to prevent one-definition-rule (ODR) violations.

Mediawiki scribunto lua module do not know builtin functions

I am having a problem with calling Lua built-in functions using Scribunto.
I created basic module Module:Item
local p = {};
function p.test(frame)
print("Hello World!")
end
return p
Which I call in different page as {{#invoke: Item | test}}
and I receive a following error:
Lua error in Module:Item at line 3: attempt to call global 'print' (a nil value).
Backtrace:
1. (tail call): ?
2. Module:Item:3: in function "chunk"
3. mw.lua:511: ?
4. (tail call): ?
5. [C]: in function "xpcall"
6. MWServer.lua:99: in function "handleCall"
7. MWServer.lua:313: in function "dispatch"
8. MWServer.lua:52: in function "execute"
9. mw_main.lua:7: in main chunk
10. [C]: ?
Since print is Lua built-in function I have the feeling the problem will be somewhere in setting on the pc.
However, when I imported wiki Infoboxes, they are working OK.
Versions:
Linux Mint Tara - Cinnamon based on ubuntu 18
MediaWiki 1.31.7
Scribunto (106fbf4) 17:24, 15 May 2018
Lua 5.1.5
Any help pointing where the problem can be is highly appreciated.
Scribunto intentionally doesn't include print. The "Removed functions and packages" section in its manual says this about it:
This was discussed on wikitech-l and it was decided that it should be omitted in favour of return values, to improve code quality. If necessary, mw.log() may be used to output information to the debug console.

Missing functions in Table Library in Lua

When I run table.maxn() or table.getn() in Lua I get the errors below:
> table.maxn(a)
stdin:1: attempt to call a nil value (field 'maxn')
stack traceback:
stdin:1: in main chunk
[C]: in ?
> table.getn(a)
stdin:1: attempt to call a nil value (field 'getn')
stack traceback:
stdin:1: in main chunk
[C]: in ?
When I try to explore the contents of the table object I get the results below. It is almost as though some functions are missing from the library.
> for k,v in pairs(table) do
>> print (k)
>> end
remove
insert
move
sort
concat
unpack
pack
>
I am using Lua5.3 - from downloaded win32 binaries > Lua53.exe
I have confirmed that I did not alter / affect the table object in any way. The results above were obtained after restarting the Interpreter afresh.
What could the issue be?
You are using lua 5.3 but:
table.getn was deprecated in lua 5.1 (ref)
table.maxn was deprecated in lua 5.2 (ref)
You need to write valid code for the version of lua you are targetting.

got SIGSEGV while calling 'require ("lsqlite3")' with lua 5.1.5

I had built lua 5.1.5 and lsqlite3-0.8.1. all of them run well on my RedHat Linux.
and then I ported them to my MIPS development board. lua and other modules (such as luafilesystem, md5, cgilua and wsapi) run well. but lsqlite3 does not work.
when I execute require("lsqlite3") in lua command line, it returns error messages in below:
lua
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
require("lsqlite3")
do_page_fault() #2: sending SIGSEGV to lua for invalid read access from
00000000 (epc == 00000000, ra == 2ac36144)
Segmentation fault
can any one give me any help to fix it? Thanks!
I got few progress in solving this problem, I rebuilt the LUA with gcc compile option '-Wl,-E' and rebuilt lsqlite3 later. I executed require ("lsqlite3") in lua command line, and it didnt print any message. I continued running some other database operation commands and found them all been successfully executed. As it seemed the problem had been solved, I should be very happy about it.
but another more strange problem raised.
If I put sentence require("lsqlite3") into a file, and then execute the file in this way:
lua file
it still printed error messages like this:
do_page_fault() #2: sending SIGSEGV to lua for invalid read access from
2ada054c (epc == 2ada054c, ra == 2abdceac)
If I put more database operation sentences into a file, and then run this file by lua. Lua can give correct result of query operation and insert values to table correctly, but always print error messages showed above.
If I run sentences in the file one by one in lua command line interface, it never print this error message.
It seems to give the error message when executing the 'require' function. But if I put require("lfs") into a file and run this file by lua, it never print error message.
I am confused that whait is the difference between the lua command line execution and lua script.
There are three places in lsqlite3.c where sqlite_int64 is used (never long long directly). When you build sqlite3 some type will be used for 64 bit integers; lsqlite3 will use the same type by including sqlite3.h for the definition of the type.

Cannot link a minimal Lua program

I have the following trivial Lua program which I copied from the book Programming In Lua
#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main (void)
{
char buff[256];
int error;
lua_State *L = luaL_newstate(); /* opens Lua */
luaL_openlibs(L); /* opens the standard libraries */
while (fgets(buff, sizeof(buff), stdin) != NULL)
{
error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
lua_pcall(L, 0, 0, 0);
if (error)
{
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1); /* pop error message from the stack */
}
}
lua_close(L);
return 0;
}
my environment is cywin
my make file looks like this:
CC=gcc
INCLUDE='-I/home/xyz/c_drive/Program Files/Lua/5.1/include'
LINKFLAGS='-L/home/xyz/c_drive/Program Files/Lua/5.1/lib' -llua51
li.o:li.c
$(CC) $(INCLUDE) -c li.c
main:li.o
$(CC) -o main $(LINKFLAGS) li.o
clean:
rm *.o
rm main
My /home/xyz/c_drive/Program Files/Lua/5.1/lib directory contains lua5.1.dll lua5.1.lib lua51.dll and lua51.lib
Trying to build my main target I am getting the following errors:
li.o:li.c:(.text+0x35): undefined reference to `_luaL_newstate'
li.o:li.c:(.text+0x49): undefined reference to `_luaL_openlibs'
li.o:li.c:(.text+0xaf): undefined reference to `_luaL_loadbuffer'
li.o:li.c:(.text+0xd9): undefined reference to `_lua_pcall'
li.o:li.c:(.text+0x120): undefined reference to `_lua_tolstring'
li.o:li.c:(.text+0x154): undefined reference to `_lua_settop'
li.o:li.c:(.text+0x167): undefined reference to `_lua_close'
Any ideas about what I might be doing wrong here?
The problem is that you have named the libraries on the link command line before the object files that require them. The linker loads modules from left to right on the command line. At the point on the line where you name -llua51, no undefined symbols that could be satisfied by that library are known. Then you name li.o, which does have unknown symbols.
Some Unix-like environments don't treat this as an error because part of the link process is deferred to the program load when reference to .so files are satisfied. But Cygwin, MinGW, and Windows in general must treat this as an error because DLLs work quite differently from .so files.
The solution is to put -llua51 after all the .o files on your link line.
Edit: Incidentally, it appears you are linking against the Lua for Windows distribution, but building with GCC under Cygwin. You will want to use Dependency Walker to make sure that your program does not depend on the Cygwin runtime, and that it does depend on the same C runtime as the lua51.dll from Lua for Windows. IIRC, that will be the runtime for the previous version of Visual Studio. It is possible to make GCC link against that, but you will need to be using the MinGW port (which you can use from Cygwin), and link against a couple of specific libraries to get that version. I'm away from my usual PC, or I'd quote an exact link line. (I believe you need -lmoldname -lmsvcr80 or something like that, as the last items on the link line.)
It will cause mysterious and very hard to diagnose problems if more than one C runtime library is in use. The easy answer is to use the same one as your preferred Lua DLL. Another alternative is that the Lua Binaries project has pre-compiled Lua DLLs for a wide array of C toolchains on Windows. If you need a Lua application that understands the Cygwin environment, you will want one that is built by GCC for Cygwin and not the Lua for Windows flavor. Lua Binaries will be your friend, or you can build Lua your self from source.
The names in the Lua API do not have those leading underscores. Try compiling with -fno-leading-underscore.

Resources