C - LuaJit Assign custom module name to a compiled string - c

I have a small C program that has a string which must represent a Lua module and it looks like this:
const char *lua_str = " local mymodule = {} \
function mymodule.foo() \
print(\"Hello World!\") \
end
return mymodule";
Or maybe using the old way (if required):
const char *lua_str = "module(\"mymodule\", package.seeall \
function foo() \
print(\"Hello World!\") \
end";
And let's assume that this is my small host application:
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main(int argc, char** argv)
{
lua_State *L = lua_open();
luaL_openlibs(L);
luaL_dostring(L, lua_str);
luaL_dofile(L, "test.lua");
return 0;
}
Now in test.lua to be able to use that module with a static name that isn't decided by the file name:
local mymodule = require "mymodule"
mymodule.foo()
Basically, I need to execute that string and give it a custom name which represents the actual module name. Currently the name is decided by the file name and I don't want that.

If you look at the documentation for require:
Loads the given module. The function starts by looking into the
package.loaded table to determine whether modname is already loaded.
If it is, then require returns the value stored at
package.loaded[modname]. Otherwise, it tries to find a loader for the
module.
To find a loader, require is guided by the package.loaders array. By
changing this array, we can change how require looks for a module. The
following explanation is based on the default configuration for
package.loaders.
First require queries package.preload[modname]. If it has a value,
this value (which should be a function) is the loader. Otherwise
require searches for a Lua loader using the path stored in
package.path. If that also fails, it searches for a C loader using the
path stored in package.cpath. If that also fails, it tries an
all-in-one loader (see package.loaders).
Once a loader is found, require calls the loader with a single
argument, modname. If the loader returns any value, require assigns
the returned value to package.loaded[modname]. If the loader returns
no value and has not assigned any value to package.loaded[modname],
then require assigns true to this entry. In any case, require returns
the final value of package.loaded[modname].
If there is any error loading or running the module, or if it cannot
find any loader for the module, then require signals an error.
You will see that it explains, in some detail, what methods require uses to find the code for the given module name. Implicit in that explanation is an indication as to how you can assign arbitrary chunks of loaded (or loadable) code to any given name you would like.
Specifically, if you set a value in package.loaded[modname] that value will be returned immediately. Failing that, package.preload[modname] is used as a loader (which is a function that takes the module name).

Related

Mocking C functions in MSVC (Visual Studio)

I am reading several articles on mocking C functions (like CMock, or CMocka), but I am not sure how the actual functions are replaced with mocked functions in this process. For example, CMocka relies on automatic wrapping using a GNU compiler, which supports parameters like --wrap to append the __wrap prefix to function calls, or weak symbols which allow you to override any symbol you like.
But how do you do this in Visual Studio, for pretty much all other frameworks?
For example, CMock has an example similar to this (simplified a lot here):
// myfunc.c
#include <parsestuff.h>
// this is the function we would like to test
int MyFunc(char* Command)
{
// this is the call to the function we will mock
return ParseStuff(Command);
}
There is also the actual implementation, which contains the actual function the linker should find in the actual application:
// parsestuff.c
int ParseStuff(char* cmd)
{
// do some actual work
return 42;
}
Now, during testing the Ruby script creates mock functions like:
// MockParseStuff.c (auto created by cmock)
int ParseStuff(char* Cmd);
void ParseStuff_ExpectAndReturn(char* Cmd, int toReturn);
But if the VS project already includes parsestuff.c, how will it be possible that the call from myfunc.c ends up in MockParseStuff.c?
Does this mean I cannot have parsestuff.c included in the unit testing project? But if this is the case, then it's also impossible to mock, for example, MyFunc from myfunc.c in any tests, since I already had to include the file it in order to test it?
(Update) I am also aware that I can include the .c file instead of the .h file, and then do some preprocessor stuff to replace the original call, like:
// replace ParseStuff with ParseStuff_wrap
#define ParseStuff ParseStuff_wrap
// include the source instead of the header
#include <myfunc.c>
#undef ParseStuff
int ParseStuff_wrap(char* cmd)
{
// this will get called from MyFunc,
// which is now statically included
}
but this seems like a lot of plumbing, and I don't even see it mentioned anywhere.
Here's a simple and short solution with hippomocks:
I created an empty Win32 console application with
main.cpp
myfunc.c + myfunc.h
parsestuff.c, parsestuff.h
and added the code from your example.
With help of hippomocks, you can mock every C-Function. Here's how my main.cpp looks like:
#include "stdafx.h"
#include "myfunc.h"
#include "hippomocks.h"
extern "C" int ParseStuff(char* cmd);
int _tmain(int argc, _TCHAR* argv[])
{
MockRepository mocks;
mocks.ExpectCallFunc(ParseStuff).Return(4711);
char buf[10] = "";
int result = MyFunc(buf);
return result; //assert result is 4711
}
HippoMocks is a free, simple and very powerful one-header framework and can be downloaded on GitHub.
Hope I've earned the bounty :)
UPDATE, How it works:
HippoMocks gets the func pointer to ParseStuff
HippoMocks builds a replacement func pointer to a template function with same signature and own implementation.
Hippomocks patches the jmp opcode from the function call prologue in memory, so that it points to the replaced function.
Replacement and memory patch are released after call or in destructor.
Here's how it looks like on my machine:
#ILT+3080(_ParseStuff):
00D21C0D jmp HippoMocks::mockFuncs<char,int>::static_expectation1<0,char *> (0D21DB1h)
If you watch the memory address 00D21C0D (may differ from run to run) in memory window, you will see, that it gets patched after the call of ExpectCallFunc.
I have not dealt with the C mocking libraries or Visual Studio, but I have thought about this in my own project. The Feathers book suggests the preprocessor seam or the link seam as a tool for dealing with this. You already mentioned the preprocessor seam, so I'll focus on the link seam.
The link seam requires the mocked function to be in a library, and the mock function to be in a library. The test can link against the mock function library while the target application can link against the original library.
Of course, as you mention, to mock MyFunc() you will have to create another library and a separate test application to link against it (or dynamically load and unload libraries in the test application).
It sounds quite laborious which is why I am procrastinating adding tests in my own application!
Hope this helps!

Error compiling Linux kernel module using custom system calls

I'll walk you through step by step
First I edit 3 files in my Linux kernel directory
Open LINUX_DIRECTORY/arch/x86/syscalls/syscall_64.tbl and add the custom calls i'm implementing – using the appropriate format
Declare them here: LINUX_DIRECTORY/include/linux/syscalls.h – using the appropriate format:
Open LINUX_DIRECTORY/Makefile and add the directory I'm storing my new system calls to the core-y line:
core-y := usr/ my_system_call_directory/
Here's where I'm having issues. Inside LINUX_DIRECTORY/my_system_call_directory I add a C file with my custom system call definitions and its corresponding Makefile. I leave the definitions empty because inside the C file for my kernel module I declare an extern function (my custom system call) and define a separate function which is set to my extern function:
extern long (*start_shuttle)(void);
long my_start_shuttle(void) {
// stuff here
}
int init_module(void) {
// stuff here
start_shuttle = my_start_shuttle;
// more stuff
}
After recompiling the kernel I try to make the kernel module and get a no definition for start_shuttle error.
Is this because I left the definition for start_shuttle blank in my_system_call_directory? Should it match exactly the my_start_shuttle I defined in the kernel module or is there something special I'm supposed to add? I'm asking dumb questions in advance because it takes so long for my machine to recompile Linux and I'm not sure what to change. Thanks
Figured it out. For anyone as slow as me, you have to use a wrapper and a stub.
So for this example, in the my_system_call_directory, in the c file for your new system call definitions, you need something like this:
#include <linux/linkage.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/export.h>
// initialize the stub function to be NULL
long (*start_shuttle)(void) = NULL;
EXPORT_SYMBOL(start_shuttle);
// wrapper
asmlinkage long sys_start_shuttle(void)
{
if (start_shuttle)
return start_shuttle();
else
return -ENOSYS;
}

How to call same file as different name for different method?

I was recently at a presentation where one of the speakers stated that he'd used a single CGI file, written in C, that is called by the webserver, but the webserver calls the file by using different names, the CGI file would run a different method.
How can I have a single C file execute different functions within when it is called by different names? Also how do I re-direct the calls for differently named files back to this single file?
Is this possible or was he just full of himself?
If you create the executable with different names but with the same code base, you can take a different branch of the code based the name of the executable used to invoke the program.
Simple example file:
#include <stdio.h>
#include <string.h>
int main1(int argc, char** argv)
{
printf("Came to main1.\n");
return 0;
}
int main2(int argc, char** argv)
{
printf("Came to main2.\n");
return 0;
}
int main(int argc, char** argv)
{
// If the program was invoked using main1, go to main1
if (strstr(argv[0], "main1") != NULL )
{
return main1(argc-1, argv+1);
}
// If the program was invoked using main2, go to main2
if (strstr(argv[0], "main2") != NULL )
{
return main2(argc-1, argv+1);
}
// Don't know what to do.
return -1;
}
Create two different executables from the file.
cc test-262.c -o main1
cc test-262.c -o main2
Then, invoke the program by using the two different executables:
./main1
Output:
Came to main1.
and...
./main2
Output:
Came to main2.
Unix filesystems support the concept of hard and soft links. To create them just type:
ln origfile newfile
to create a hard link, or:
ln -s origfile newfile
to create a soft link.
Soft links are just a special kind of file that contains the path of another file. Most operations in the link transparently result in operating on the target file.
Hard links are lower level. In effect, all files are a link from the pathname to the content. In Unix you can link more than one pathname to the same content. In effect, there's no "original" and "links", all are links. When you delete a file, you're just removing a link, and when the link count goes to zero, the content is removed.
Many unix utilities do this trick. Since the running shell includes the name used to invoque the executable, it's handled just like the 0'th argument of the command line.
When a CGI script is being called by a web server, it receives a considerable amount of information in its environment to let it know how it was called, including:
SCRIPT_NAME, the path to the script from the document root
SCRIPT_FILENAME, the filesystem path to the script (usually the same as argv[0])
REQUEST_URI, the path that was requested by the browser (usually similar to SCRIPT_NAME in the absence of URL rewriting)
QUERY_STRING and PATH_INFO, which contain URL parameters following the script's name
HTTP_*, which contain most of the HTTP headers that were passed in the request
Point is, the script gets a lot of information about how it was called. It could be using any of those to make its decision.
It's possible and actually pretty common.
The first element in the argv array passed to the main function is the "name" of the executable. This can be the full path, or it can be just the last component of the path, or -- if the executable is started with an exec* function call, it can be an arbitrary string. (And Posix allows it to be a null string, as well, but in practice that's pretty rare.)
So there is nothing stopping the executable from looking at argv[0] (having first checked to make sure that argc > 0) and parsing it.
The most typical way to introduce a different name for the executable is to insert a filesystem link with the alternate name (which could be either a hard or a soft-link, but for maintainability soft links are more useful.)
For CGIs, it is not even necessary to examine argv[0], since there are various useful environment variables, including (at least): SCRIPT_NAME.

CreateProcess doesn't work with error 2 [duplicate]

I'm trying to use CreateProcess to start a child process, however I keep getting error 2, which, according to the documentation is file not found.
My code looks like this:
if (!(CreateProcess(LPCTSTR("test.exe") ,NULL ,NULL,NULL,FALSE ,0 ,NULL ,NULL ,&producer_si
,&producer)))
{
printf("Create process failed!(%d)\n", GetLastError());
}
Where test.exe is an executable program which I created earlier. The child process is very simple, with the code looking like this:
void _tmain (int argc, TCHAR* argv[])
{
printf("%s\n", "hello!");
}
test.exe is also found in the same folder as the parent process. I'm not understanding why I'm always getting an error code of 2.
Error 2 is ERROR_FILE_NOT_FOUND. As others have told you, you are relying on a relative path when you need to use an absolute path instead.
Also, LPCTSTR("test.exe") is not valid code. If UNICODE is defined, CreateFile() maps to CreateFileW(), and LPCTSTR maps to LPCWSTR ie const wchar_t*. You cannot typecast a char* to a wchar_t* and end up with meaningful data. If you want to use TCHAR-sensitive literals, use the TEXT() macro instead, eg:
if (!CreateProcess(TEXT("full path to\\test.exe"), ...))
Otherwise, forget using TCHAR and just write Ansi-specific or Unicode-specific code instead, depending on your needs:
if (!CreateProcessA("full path to\\test.exe", ...))
if (!CreateProcessW(L"full path to\\test.exe", ...))
test.exe is never being looked up in the directory that the calling exe lives in. It is being looked up in the current directory which is a per-process path variable. Maybe the current directory is not pointed to where test.exe lives. You should also never rely on that because it can change arbitrarily (for example by using the file dialogs, or when the parent process changes it).
The CreateProcess function is very sensitive when it comes to file names, at least in my opinion.
When you specify your exe like that you actually specify it according to the current directory which may not be the same as the directory your main exe is in, which explains the file not found.
One way around is to simply get your current exe's directory with GetModulePath stip away the exe name from that and there you have the same directory, or simply use an absolute path.
According to the CreateProcess documentation the first parameter can be NULL :
The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space–delimited token in the lpCommandLine string.
At least for me it seemed that if you just specify the command line only it works far better than with the application name, and also within the application name you can't handle the commandline.
With QT the MSDN function TEXT() it doesn't work: QTCreator's compiler return:
'Lvar' undeclared (first use in this function)
where var is input of Text(), because of QT whose enable UNICODE and because of that:
#ifdef UNICODE
/*
* NOTE: This tests UNICODE, which is different from the _UNICODE define
* used to differentiate standard C runtime calls.
*/
typedef WCHAR TCHAR;
typedef WCHAR _TCHAR;
/*
* __TEXT is a private macro whose specific use is to force the expansion of a
* macro passed as an argument to the macro TEXT. DO NOT use this
* macro within your programs. It's name and function could change without
* notice.
*/
#define __TEXT(q) L##q
#else
typedef CHAR TCHAR;
typedef CHAR _TCHAR;
#define __TEXT(q) q
#endif
#endif
in particular this passage:
#define __TEXT(q) L##q
in winnt.h included by windows.h
So, to solve this problem, we have to add this:
DEFINES -= UNICODE
in the .pro file of the QTCreator's project and it will work.

How do I get a bundle reference from inside of a plugin with carbon?

I'm writing a C++ plugin in Mac OS X using the Carbon framework (yeah, yeah, I know, Apple is deprecating Carbon, but at the moment I can't migrate this code to Cocoa). My plugin gets loaded by a master application, and I need to get a CFBundleRef reference to my plugin so that I can access it's resources.
The problem is, when I call CFBundleGetMainBundle() during my plugin's initialization routines, that returns a reference to the host's bundle reference, not the plugin's. How can I get a reference to my plugin's bundle instead?
Note: I would rather not use anything determined at compile-time, including calling CFBundleGetBundleWithIdentifier() with a hard-coded string identifier.
See this posting on the carbon-dev mailing list, which seems to be a similar situation.
The method given there is
I recommend using CFBundleGetBundleWithIdentifier.
Your plug-in should have an unique identifier; something like
"com.apple.dts.iTunes_plug-in", etc. Look for the CFBundleIdentifier
property in your plug-in's bundle's info.plist.
Note: I would rather not use anything determined at compile-time, including calling CFBundleGetBundleWithIdentifier() with a hard-coded string identifier.
Because that's WET, right?
Here's how you can make that solution DRY.
First, define some macros for this in a header file, like so:
#define MY_PLUGIN_BUNDLE_IDENTIFIER com.example.wiflamalator.photoshop-plugin
#define MY_PLUGIN_STRINGIFY(x) #x
#define MY_PLUGIN_BUNDLE_IDENTIFIER_STRING MY_PLUGIN_STRINGIFY(MY_PLUGIN_BUNDLE_IDENTIFIER)
Import the header file into the code that calls CFBundleGetBundleWithIdentifier. In that code, use CFSTR(MY_PLUGIN_BUNDLE_IDENTIFIER_STRING).
Then, in Xcode, either set that file as your Info.plist prefix header, or (if you already have one) #include it into that header. Finally, in Info.plist, set the bundle identifier to MY_PLUGIN_BUNDLE_IDENTIFIER (in a string value, of course).
Now you have the bundle identifier written in exactly one place (the header), from which the C preprocessor puts it in all the places where it needs to be, so you can look up your own bundle by it using CFBundleGetBundleWithIdentifier.
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
#ifdef __APPLE__
// This should be actually defined somewhere else
#define MY_PLUGIN_BUNDLE_IDENTIFIER com.yourbundle.name
// Then all the regular stuff
#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define MY_PLUGIN_BUNDLE_IDENTIFIER_STRING EXPAND_AND_QUOTE(MY_PLUGIN_BUNDLE_IDENTIFIER)
CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(CFSTR(MY_PLUGIN_BUNDLE_IDENTIFIER_STRING));
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
StoragePaths::setApplicationResourcesDirectory(STR(path));
#endif
Prints the path to the your bundle
Note: For JUCE users, use JucePlugin_CFBundleIdentifier instead of MY_PLUGIN_BUNDLE_IDENTIFIER and you're all set

Resources