Can luaL_loadfile() be replaced by luaL_loadbuffer()? - c

I have have a working project like with the following code , running on Visual Studio 2013, windows 7 N.
I tried to replace luaL_loadfile() with luaL_loadbuffer(L,s,strlen(s),name), so that I could put the script as a string together in the main instead, because in my other project with IAR, I have problem with opening file in the project, but I managed to call a lua script directly with putting the script as a string in the main(). My question would be: how does this luaL_loadbuffer() work? I mean, if I understand this function correctly, luaL_loadbuffer(L,s,strlen(s),name), the "s" means a string. I tried to debug with luaL_loadbuffer(), but could not passing the debug, always got error status= 2. Besides I also see somebody else used luaL_loadbuffer() to load the script file, so I am confused now. Can anyone help me?
-- last.lua
function f ()
print("Hello from Lua")
end
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
double z;
int error;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if (luaL_loadfile(L, "last.lua") || lua_pcall(L, 0, 0, 0))
{
printf("error: %s", lua_tostring(L, -1));
return -1;
}
lua_getglobal(L, "f");
if (!lua_isfunction(L, -1))
{
lua_pop(L, 1);
return -1;
}
if (lua_pcall(L, 0, 0, 0) != 0)
{
printf("error running function `f': %s\n", lua_tostring(L, -1));
return -1;
}
lua_close(L);
return 0;
}

Yes, you should be able to do this, assuming you load the file as one chunk (and not try to process it by line or by some other chunk as this will probably make those parts invalid Lua code). There is an example in "Programming Lua" that shows how loadbuffer can be used.
Two additional suggestions: (1) don't remove new lines from the file you read and pass it exactly as is to loadbuffer (otherwise --comment\ncode will turn code into comment), (2) make name look like #name as it will make name to be recognized as the file name (for example, in errors thrown from that code). See description under "source" in 4.9.

Related

Printing/writing wchar_t?

First off: I know there are similar topics for C++, but I am curious about standard C, and I don't believe my problem is related to previous problems.
I am trying to implement Unicode support for a simple program which just asks the user to select a directory through a folder browser and then passes it to another program (only got to the first part). But when attempting to write the received path to a file, it results in a 0-byte file. And when printing it out using wprintf_s, non-ASCII characters come out as question marks. I don't believe there is any undefined behavior or anything as I've double checked documentation. So what am I doing wrong?
The code currently looks like this (just the bare minimum for strict test conditions):
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <shlobj.h>
#include <stdio.h>
int main()
{
BROWSEINFOW bi = { 0 };
LPITEMIDLIST pidl;
wchar_t path[MAX_PATH];
pidl = SHBrowseForFolderW(&bi);
SHGetPathFromIDListW(pidl, path);
wprintf_s(L"%s\n", path);
return 0;
}
The above code prints it regularly. When attempting to write to a file instead, I replace the wprintf_s call with this (having declared FILE *f first of course):
if(_wfopen_s(&f, L"C:\\test.txt", L"w"))
{
fwprintf_s(f, L"%s\n", path)
fclose(f);
}
However, I have also tried using fwrite with both w and wb mode, but all methods results in an empty file.
You need _O_U16TEXT for console output, and "UTF-16LE" for file output.
Also, _wfopen_s returns zero when successful according to MS documentation:
Return Value Zero if successful; an error code on failure. See errno,
_doserrno, _sys_errlist, and _sys_nerr for more information about these error codes.
You should make sure return value is zero
if (0 == _wfopen_s(&f, filename, L"w, ccs=UTF-16LE")){
//isokay ...
}
or check if f is non-NULL. For example:
#include <stdio.h>
#include <io.h> //for _setmode
#include <fcntl.h> //for _O_U16TEXT
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
const wchar_t *buf = L"ελληνική";
wprintf(L"%s\n", buf);
FILE *f = NULL;
_wfopen_s(&f, L"C:\\test\\test.txt", L"w, ccs=UTF-16LE");
if (f)
{
fwprintf_s(f, L"%s\n", buf);
fclose(f);
}
return 0;
}

sh: 1: Syntax error: "(" unexpected with a C file

I'm getting a confusing error message. I'm running MinGW on Windows XP 32-bit. When I attempt to compile the following code, I get an error message "./hello.c: line 4: Syntax error near unexpected token '('". Line 4 is at int main(...), I can't figure out what unexpected token is "near '('". I've tried using int main(void), but I get the same message. However, if I compile it without the "char string..." and "data = fputs(...)" and have it read from a given text file, it compiles without issue.
What I'm trying to accomplish is to read from a file where the filename is given by an external source, i.e. php. Eventually I'm going to be working this into an Apache module with a parser that I've made, hence the call from php, but I wanted to fool around and build some template code to work with before I got to that part.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE *fp;
//char string = "JD"; commented out
char data;
//printf("Type in your filename: "); also commented out
//scanf("%s", &argv); also commented out
if(argc >= 2)
{
fp = fopen("sample.txt", "r"); //switched to reading a given file
}
while((data = getchar()) != EOF)
{
fgets(data, sizeof(data), fp);
// data = fputs(string, fp);
}
if (fp==NULL) /* error opening file returns NULL */
{
printf("Could not open player file!\n"); /* error message */
return 1; /* exit with failure */
}
/* while we're not at end of file */
while (fgets(data, sizeof(string), fp) != NULL)
{
printf(data); /* print the string */
}
fclose(fp); /* close the file */
return 0; /* success */
}
Okay, I tried writing a simple "Hello World" program, but I'm still getting the same error message with it which makes me think the error message isn't being caused by my code at all.
#include <stdio.h>
int main(void) //still getting a syntax error before unexpected token '('
{
printf("Hello, world!");
return 0;
}
There is problem with your logic . the "exploit" array would contain "./myotherAAAAAAAAAAAAAAAAAAAA:" which you are passing to system ..so problem are bound to happen
strncpy(command, "./myotherfile ", 9);
only copies the first 9 chars. Replace that with
strcpy(command, "./myotherfile ");
which should do what you want.
P.S. I suspect that you originally had
strncpy(command, "./myfile ", 9);
which would have worked, and you didn't change the 9 when you changed the length of the file name. There are entire books written on why couplings like this are a bad idea and what to do instead. In this case the simplest solution is to use strcpy so you don't need to mention the length.
I think you are trying to run ./motherfile...Then when you concatenate it with "exploit" name becomes "./myotherAAAAAAAAAAAAAAAAAAA " and not "./myotherfile AAAAAAAAAAAAAAAAAAAA", to give space concatenate it with a space first.

C code runs in Eclipse-Kepler but fails to run in Codeblocks IDE

I am a newbie at C programming and new on Stackoverflow as well.
I have some c code that compiles and runs in Eclipse Kepler (Java EE IDE); I installed the C/C++ plugin and Cygwin Gcc compiler for c.
Everything runs ok in Eclipse IDE; however, when my friend tries to run the same code on his Codeblocks IDE, he doesn't get any output. At some point, he got some segmentation error, which we later learned was due to our program accessing memory space that didn't belong to our program.
Codeblocks IDE is using Gcc compiler not cygwin gcc, but I don't think they're that different to cause this sort of problem.
I am aware that C is extremely primitive and non-standardized, but why would my code run in eclipse with cygwin-gcc compiler but not run in Codeblocks IDE with gcc compiler?
Please help, it's important for our class project.
Thanks to all.
[EDIT] Our code is a little large to paste in here but here's a sample code of what would RUN SUCCESSFULLY in eclipse but FAIL in codeblocks, try it yourself if you have codeblocks please:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(void) {
char *traceEntry1;
FILE *ifp;
traceEntry1 = malloc(200*sizeof(char));
ifp = fopen("./program.txt", "r");
while (fgets(traceEntry1, 75, ifp))
printf("String input is %s \n", traceEntry1);
fclose(ifp);
}
It simply doesn't give any outputs in codeblocks, sometimes just results in a segmentation fault error.
I have no idea what the problem is.
We need your help please, thanks in advance.
Always and ever test the results of all (revelant) calls. "relevant" at least are those call which return results which are unusable if the call failed.
In the case of the OP's code they are:
malloc()
fopen()
fclose()
A save version of the OP's code could look like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
char * traceEntry1 = NULL; /* Always initialise your variables, you might remove this during the optimisation phase later (if ever) */
FILE * ifp = NULL; /* Always initialise your variables, you might remove this during the optimisation phase later (if ever) */
traceEntry1 = malloc(200 * sizeof(*traceEntry1)); /* sizeof(char) is always 1.
Using the dereferenced target (traceEntry1) on the other hand makes this
line of code robust against modifications of the target's type declaration. */
if (NULL == traceEntry1)
{
perror("malloc() failed"); /* Log error. Never ignore useful and even free informaton. */
result = EXIT_FAILURE; /* Flag error and ... */
goto lblExit; /* ... leave via the one and only exit point. */
}
ifp = fopen("./program.txt", "r");
if (NULL == ifp)
{
perror("fopen() failed"); /* Log error. Never ignore useful and even free informaton. */
result = EXIT_FAILURE; /* Flag error ... */
goto lblExit; /* ... and leave via the one and only exit point. */
}
while (fgets(traceEntry1, 75, ifp)) /* Why 75? Why not 200 * sizeof(*traceEntry1)
as that's what was allocated to traceEntr1? */
{
printf("String input is %s \n", traceEntry1);
}
if (EOF == fclose(ifp))
{
perror("fclose() failed");
/* Be tolerant as no poisened results are returned. So do not flag error. It's logged however. */
}
lblExit: /* Only have one exit point. So there is no need to code the clean-up twice. */
free(traceEntry1); /* Always clean up, free what you allocated. */
return result; /* Return the outcome of this exercise. */
}

Error loading module (Lua)

I am having trouble with this error I am receiving whenever I run my application. The error is:
loop or previous error loading module 'socket'.
The code that is causing this error is:
socket = require("socket").
This error occurs during the first lua_pcall. Here is the function that calls that:
void startTerminal(int port, char host[80])
{
lua_State *L = lua_open();
/* Open Lua Library */
luaL_openlibs(L);
/* Choose the lua file that will run */
if(luaL_loadfile(L, "socket.lua")) {
lfatal(L, "luaL_loadfile() failed");
}
/* Start lua file */
if(lua_pcall(L, 0, 0, 0)) {
lfatal(L, "lua_pcall()");
}
/* Get connect function */
lua_getglobal(L, "connect");
if(!lua_isfunction(L, -1)) {
lua_pop(L, 1);
lfatal(L, "lua_isfunction() failed");
}
/* Setup arguments */
lua_pushnumber(L, port);
lua_pushstring(L, host);
/* Call the lua function */
if(lua_pcall(L, 2, 2, 0)) {
lfatal(L, "lua_pcall() failed");
}
/* Print out results */
printf("%s", lua_tostring(L, -1));
printf("%s", lua_tostring(L, -1));
lua_close(L);
}
Here is how I am compiling the code:
gcc -Wall -o terminal attacker.c -I/usr/include/lua5.1 -llua5.1 -lm
Am I missing any switches during compile or am I missing library?
NOTE:
The compiler does not throw any errors and compiles cleanly.
In other Lua applications that does not include C, I don't have any problem with require("socket").
Thanks
luaL_loadfile(L, "socket.lua")
This is suspect. Very suspect.
Using the standard Lua loaders, when you issue require("MODULE_NAME"), the very first thing it will look for (after checking to see if MODULE_NAME was already loaded) will be "MODULE_NAME.lua". In the current directory. Which certainly exists. It's called socket.lua, the very file you've loaded and are trying to execute. Therefore, it's going to try to load socket.lua as a module.
And since socket.lua has require("socket") in it, it will load itself again. And again. And again.
Well, it won't because Lua's package loader system is smart enough to detect loops and issue an error. Which is exactly what it did.
So don't name a file MODULE_NAME.lua if you actually are going to require a module with that name.

Engine functions: Calling MATLAB from a C application

I'm trying to call a user-defined MATLAB function from a C application, but I'm having trouble getting even the simplest engine scenario to work. Below is a program that should simply print a = 1 into the MATLAB command window. But when I run it, nothing happens!
#include "engine.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
Engine *ep;
if (!(ep = engOpen("\0"))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
engOutputBuffer(ep, NULL, 0);
engEvalString(ep, "a = 1");
engClose(ep);
return EXIT_SUCCESS;
}
stdout output is not sent to the MATLAB Engine console. You can specify your own output buffer using
char engOutput[300];
engOutputBuffer(ep, engOutput, 300);
engEvalString(ep, "disp('test')");
You will then have to print engOutput yourself.
If the purpose of the print is just to verify the engine is working, you can go to the engine console and type "a" to see that the variable was created.

Resources