I have a function in which one of the function arguments is an integer. During function invocation I am passing an enumerated datatype to this function. After building using gcc, any access to the INTEGER variable inside the function causes a segmentation fault.
Sample code:
void somefun (unsigned int nState)
{
switch (nState) // <-- Crashes on this line
{
//
// functionality here ...
//
}
}
enum {
UNDEFINED = -1,
STATE_NICE,
STATE_GREEDY
} E_STATE;
int main (int argc, char *argv [])
{
somefun (STATE_NICE);
}
First off, The enum is defined in main() and does not exist for somefun(). You should define the enum outside of main, although I cannot see how this is causing a crash.
After defining the enum outside of the main you should define somefun to be somefun( E_STATE nState ) and test again.
I compiled and ran that code exactly (cut & paste) on my computer, using gcc version 4.2.4, with no errors or segmentation fault. I believe the problem might be somewhere else.
Actually runs for me:
bash $ cat bar.c
#include <stdio.h>
void somefun (unsigned int nState)
{
switch (nState) // <-- Crashes on this line
{
//
// functionality here ...
//
default:
printf("Hello?\n");
}
}
int main (int argc, char *argv [])
{
enum {
UNDEFINED = -1,
STATE_NICE,
STATE_GREEDY
} E_STATE;
somefun (STATE_NICE);
return 0;
}
bash $ gcc -Wall bar.c -o bar
bar.c: In function 'main':
bar.c:22: warning: unused variable 'E_STATE'
bash $ ./bar
Hello?
bash $
Made a couple of changes, but it ran without them. (1) added a tag in the switch just so it had something; (2) added the #include <stdio.h> and printf so I could tell that it had run; (3) added the return 0; to eliminate an uninteresting warning.
It did run successfully with none of the changes, it just didn't do anything visible.
So, what's the OS, what's the hardware architecture?
Update
The code changed while I was trying it, so here's a test of the updated version:
bash $ cat bar-prime.c
#include <stdio.h>
void somefun (unsigned int nState)
{
switch (nState) // <-- Crashes on this line
{
//
// functionality here ...
//
default:
printf("Hello?\n");
}
}
enum {
UNDEFINED = -1,
STATE_NICE,
STATE_GREEDY
} E_STATE;
int main (int argc, char *argv [])
{
somefun (STATE_NICE);
return 0;
}
bash $ gcc -Wall bar-prime.c -o bar-prime && ./bar-prime
Hello?
bash $
Still works. Are you getting a core file in your version? Have you tried getting a stack trace?
Your situation is like specific to sun sparc hardware or similar. Please post uname -a and output of dmesg
From all your answers it seems that the code is logically correct, and I need to investigate the real reason for the crash. I will investigate it and post it soon.
Related
I know this is a weird question, but I want to get the "initscr" function error mentioned by the doc (getting invalid pointer and an error message on stderr) to test if a wrapper works properly.
But I don't find any information about that. I'm currently working with ncurses 6.2.
After few research, I have found that the invalid pointer is really a NULL, not just an empty one pointing on anywhere.
But I'm not able to break the function...
If someone know how to help me to break down this, feel free to leave a comment.
The following program:
#include <curses.h>
#include <malloc.h>
#include <stdlib.h>
bool my_malloc_disabled;
void *malloc(size_t size) {
if (my_malloc_disabled) {
return NULL;
}
void *__libc_malloc(size_t);
return __libc_malloc(size);
}
int main() {
my_malloc_disabled = 1;
initscr();
}
does:
$ gcc file.c -lcurses
$ ./a.out
Error opening allocating $TERM.
I'm writing a dynamic array for a personal project and am trying to unit test all the functions. I'm trying to write a unit test for util_dyn_array_check_index() but am having problems doing so because I made the design decision to call exit(-1) if there is an index out of bounds. I want to check in my unit test that it calls exit() when provided with an invalid index. But if I ever give it an invalid index, it just exits my testing program. Is it possible to somehow catch that a call to exit() was thrown, or redefine exit() in my testing program to prevent it from ending the tests?
From this answer I've looked into atexit(), but it looks like that doesn't stop an exit, just performs one or more user-defined functions before exiting. This doesn't work for me because I have other tests to run after this one. My last thought is I could make util_dyn_array_check_index() a macro instead of a function, and redefine exit() to be a different function in my testing program, but I'd rather not make it a macro if I can avoid it.
Here's my code:
The details of this struct don't really matter, just provided for completeness
//basically a Vec<T>
typedef struct {
//a pointer to the data stored
void * data;
//the width of the elements to be stored in bytes
size_t stride;
//the number of elements stored
size_t len;
//the number of elements able to be stored without reallocating
size_t capacity;
} util_dyn_array;
Here is the function I want to test.
//exits with -1 if index is out of bounds
inline void util_dyn_array_check_index(util_dyn_array * self, size_t index) {
if (index >= self->len) {
exit(-1);
}
return;
}
Here is a skeleton of what I would like the test to be (omitted some macro magic I'm using to make writing tests nicer, for clarity).
bool test_dyn_array_check_index() {
util_dyn_array vector = util_dyn_array_new(sizeof(int), 16);
for(int i = 0; i < 16; i++) {
util_dyn_array_push(&vector, (void*)&i);
}
for(int i = 0; i < 16; i++) {
//if nothing happens, its successful
util_dyn_array_check_index(&vector, i);
}
//somehow check that it calls exit without letting it crash my program
{
util_dyn_array_check_index(&vector, 16);
}
return true;
}
Obviously I could change my code to return a bool or write to errno, but I'd prefer it to exit as its usually an unrecoverable bug.
It is UB to define another exit() in standard C (both as a function and as a macro if the header is included). In many environments, you are likely to be able to get away with it, though.
With that said, doing such a thing makes no sense here, because we are talking about exit(). The function is not expecting to continue execution after that, so that pretty much forces you to replace it with a longjmp() or go with textual replacement to convert it to a return (assuming a void return type). In both cases, it means you need to assume the function is not leaving things in a broken state (like holding some resource). That is a lot to assume, but it may be a reasonable way out if your unit testing framework is meant to be tied to this particular project.
Instead of trying to modify the behavior of the tested function, I suggest you add support for running tests in their own process to your test framework. There are many advantages apart from being able to test things like these. For instance, you get the ability of running tests in parallel for free and isolates many side-effects between them.
Another solution: use an #ifdef macro to call a different function in your debug build.
#ifdef DEBUG
#define exit_badindex(...) my_debug_function(__VA_ARGS__)
#else
#define exit_badindex(...) exit(__VA_ARGS__)
#ifndef NDEBUG
#warning NDEBUG undefined in non-DEBUG build: my_debug_function will not be called
#endif
#endif
Run the code in a fork and check the exit value of the fork.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <sys/wait.h>
void util_dyn_array_check_index() {
exit(-1);
}
int main(void) {
pid_t pid = fork();
assert(pid >= 0);
if( pid == 0 ) {
util_dyn_array_check_index();
exit(0);
}
else {
int child_status;
wait(&child_status);
printf("util_dyn_array_check_index exited with %d\n", WEXITSTATUS(child_status));
}
}
Note that the exit status will be 255 because despite accepting an integer POSIX exit statuses are unsigned. Consider using exit(1) instead or define an ARGUMENT_ERROR_EXIT_STATUS macro.
Note that I used an assert to check if my fork failed. This might be a better way to implement your checks.
inline void util_dyn_array_check_index(util_dyn_array * self, size_t index) {
assert(index < self->len);
}
This will provide more information on error, and it can be switched off in production for performance.
Assertion failed: (index < self->len), function util_dyn_array_check_index, file test.c, line 9.
assert calls abort. In your tests you'd close stderr to avoid the assert message from cluttering up the output, and check that WTERMSIG(status) == SIGABRT.
void util_dyn_array_check_index() {
assert(43 < 42);
}
int main(void) {
pid_t pid = fork();
assert(pid >= 0);
if( pid == 0 ) {
// Suppress the assert output
fclose(stderr);
util_dyn_array_check_index();
exit(0);
}
else {
int status;
wait(&status);
if( WTERMSIG(status) == SIGABRT ) {
puts("Pass");
}
else {
puts("Fail");
}
}
}
If it's for unit testing, you don't need to physically catch the call to exit().
Before the solution, I would like to suggest redesigning your library. You have a few alternatives:
Having util_dyn_array include a callback that is called if out-of-bound mode is encountered, and default it to exit(1) (not exit(-1), that doesn't work well when the program is called from a shell).
Having a global out-of-bound handler (which again defaults to exit(1)), and allow the program to change the handler at runtime by calling something like set_oob_handler(new_handler).
Doing integration tests instead of unit tests. As suggested by multiple people here, if the library can exit or crash, this goes to the realm of integration (with the calling process/OS).
My solution:
main.c:
#include <stdio.h>
void func(void);
int main(int argc, char **argv)
{
printf("starting\n");
func();
printf("ending\n");
}
something.c:
void my_exit(int status)
{
printf("my_exit(%d)\n", status);
#ifdef UNIT_TEST
printf("captured exit(%d)\n", status); // you can even choose to call a global callback here, only in unit tests.
#else
exit(status);
#endif
}
void func(void) {
my_exit(1);
}
makefile:
# these targets are MUTUALLY EXCLUSIVE!!
release:
cc -g -c -fpic something.c
cc -shared -o libsomething.so something.o
cc -g -o main main.c -L. -lsomething
fortest:
cc -DUNIT_TEST=1 -g -c -fpic something.c
cc -shared -o libsomething.so something.o
cc -g -o main main.c -L. -lsomething
$ make release
cc -g -c -fpic something.c
[...]
$ LD_LIBRARY_PATH=. ./main
starting
my_exit(1)
$ make fortest
cc -DUNIT_TEST=1 -g -c -fpic something.c
[...]
$ LD_LIBRARY_PATH=. ./main
starting
my_exit(1)
captured exit(1)
ending
(note that this was tested on Linux, I don't have a Mac to test on, so minor makefile modifications might be required).
The exit function is a weak symbol, so you can create your own copy of the function to catch the case where it gets called. Additionally, you can make use of setjmp and longjmp in your test code to detect a proper call to exit:
For example:
#include "file_to_test.c"
static int expected_code; // the expected value a tested function passes to exit
static int should_exit; // 1 if exit should have been called
static int done; // set to 1 to prevent stubbing behavior and actually exit
static jmp_buf jump_env;
static int rslt;
#define test_assert(x) (rslt = rslt && (x))
// stub function
void exit(int code)
{
if (!done)
{
test_assert(should_exit==1);
test_assert(expected_code==code);
longjmp(jump_env, 1);
}
else
{
_exit(code);
}
}
bool test_dyn_array_check_index() {
int jmp_rval;
done = 0;
rslt = 1;
util_dyn_array vector = util_dyn_array_new(sizeof(int), 16);
for(int i = 0; i < 16; i++) {
util_dyn_array_push(&vector, (void*)&i);
}
for(int i = 0; i < 16; i++) {
//if nothing happens, its successful
should_exit = 0;
if (!(jmp_rval=setjmp(jump_env)))
{
util_dyn_array_check_index(&vector, i);
}
test_assert(jmp_rval==0);
}
// should call exit(-1)
{
should_exit = 1;
expected_code = 2;
if (!(jmp_rval=setjmp(jump_env)))
{
util_dyn_array_check_index(&vector, 16);
}
test_assert(jmp_rval==1);
}
done = 1
return rslt;
}
Before calling a function that could call exit, call setjmp to set a jump point. The stubbed exit function then checks whether exit should have been called and with which exit code, then calls longjmp to jump back out to the test.
If exit was called then the return value of setjmp is 1, indicating it came from a call to longjmp. If not longjmp is not called and the return value of setjmp will be 0 after the function returns.
I am trying to wrap existing function.
below code is perfectly worked.
#include<stdio.h>
int __real_main();
int __wrap_main()
{
printf("Wrapped main\n");
return __real_main();
}
int main()
{
printf("main\n");
return 0;
}
command:
gcc main.c -Wl,-wrap,main
output:
Wrapped main
main
So i have changed main function with temp. my goal is to wrap temp() function.
Below is the code
temp.c
#include<stdio.h>
int temp();
int __real_temp();
int __wrap_temp()
{
printf("Wrapped temp\n");
return __real_temp();
}
int temp()
{
printf("temp\n");
return 0;
}
int main()
{
temp();
return 0;
}
command:
gcc temp.c -Wl,-wrap,temp
output:
temp
Wrapped temp is not printing. please guide me to wrap funciton temp.
The manpage for ld says:
--wrap=symbol
Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to "__wrap_symbol". Any
undefined reference to "__real_symbol" will be resolved to symbol.
The keyword here is undefined.
If you put the definition temp in the same translation unit as the code that uses it, it will not be undefined in the code that uses it.
You need to split the code definition and the code that uses it:
#!/bin/sh
cat > user.c <<'EOF'
#include<stdio.h>
int temp(void);
int __real_temp(void);
int __wrap_temp()
{
printf("Wrapped temp\n");
return __real_temp();
}
int main()
{
temp();
return 0;
}
EOF
cat > temp.c <<'EOF'
#include<stdio.h>
int temp()
{
printf("temp\n");
return 0;
}
EOF
gcc user.c -Wl,-wrap,temp temp.c # OK
./a.out
Splitting the build into two separate compiles perhaps makes it clearer:
$ gcc -c user.c
$ gcc -c temp.c
$ nm user.o temp.o
temp.o:
U puts
0000000000000000 T temp
user.o:
0000000000000015 T main
U puts
U __real_temp
U temp
0000000000000000 T __wrap_temp
Now since temp is undefined in user.c, the linker can do its __real_/__wrap_magic on it.
$ gcc user.o temp.o -Wl,-wrap=temp
$ ./a.out
Wrapped temp
temp
The answer proposed by PSCocik works great if you can split the function you want to override from the function that will call it. However if you want to keep the callee and the caller in the same source file the --wrap option will not work.
Instead you can use __attribute__((weak)) before the implementation of the callee in order to let someone reimplement it without GCC yelling about multiple definitons.
For example suppose you want to mock the world function in the following hello.c code unit. You can prepend the attribute in order to be able to override it.
#include "hello.h"
#include <stdio.h>
__attribute__((weak))
void world(void)
{
printf("world from lib\n");
}
void hello(void)
{
printf("hello\n");
world();
}
And you can then override it in another unit file. Very useful for unit testing/mocking:
#include <stdio.h>
#include "hello.h"
/* overrides */
void world(void)
{
printf("world from main.c\n");
}
int main(void)
{
hello();
return 0;
}
Is there a function that returns the FUSE version string?
fuse_common.h has int fuse_version(void), which returns the major version, multiplied by 10, plus the minor version; both of which are derived from #define values. (e.g., This returns 27 on my platform). What I'm looking for, however, is some char* fuse_version(void) that would return something like 2.7.3.
As you said yourself, the version is defined in fuse_common.h. If you don't want to use helper_version, as #Alexguitar said you may just write a small program that does it -- but it seems that only the two first numbers (major and minor) are available:
#include <fuse/fuse.h>
#include <stdlib.h>
#include <stdio.h>
char* str_fuse_version(void) {
static char str[10] = {0,0,0,0,0,0,0,0,0,0};
if (str[0]==0) {
int v = fuse_version();
int a = v/10;
int b = v%10;
snprintf(str,10,"%d.%d",a,b);
}
return str;
}
int main () {
printf("%s\n", str_fuse_version());
exit(EXIT_SUCCESS);
}
Note: you should include fuse/fuse.h and not fuse_common.h; also, you may need to pass -D_FILE_OFFSET_BITS=64 when compiling.
$ gcc -Wall fuseversiontest.c -D_FILE_OFFSET_BITS=64 -lfuse
$ ./a.out
2.9
In the source code of fuse in include/config.h you have:
/* Define to the version of this package. */
#define PACKAGE_VERSION "2.9.4"
Additionally, there's a function in lib/helper.c that prints it.
static void helper_version(void)
{
fprintf(stderr, "FUSE library version: %s\n", PACKAGE_VERSION);
}
Edit:
I do realize that the package versioning strings are only for internal use so you're probably stuck with the major and minor numbers exposed by fuse_common.h . You'll probably have to write a function like #Jay suggests.
Under Linux, I can register a routine that will run before main. For example:
#include <stdio.h>
void myinit(int argc, char **argv, char **envp) {
printf("%s: %s\n", __FILE__, __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof(myinit) *__init = myinit;
By compiling this with GCC and linking it in, the function myinit will be run before main.
Is there way to do this under Mac OSX and MACH-O?
Thanks.
You could place the function in __mod_init_func data section of Mach-O binary.
From Mach-O format reference:
__DATA,__mod_init_func
Module initialization functions. The C++ compiler places static constructors here.
example.c
#include <stdio.h>
void myinit(int argc, char **argv, char **envp) {
printf("%s: %s\n", __FILE__, __FUNCTION__);
}
__attribute__((section("__DATA,__mod_init_func"))) typeof(myinit) *__init = myinit;
int main() {
printf("%s: %s\n", __FILE__, __FUNCTION__);
return 0;
}
I build your example with clang on OS X platform:
$ clang -Wall example.c
$ ./a.out
example.c: myinit
example.c: main
Easiest way is to specify the function to be constructor using constructor attribute. The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() completes or exit() is called. You can also specify optional priority if you have several functions
e.g. __attribute__((constructor(100)))
#include <stdio.h>
__attribute__((constructor)) void myinit() {
printf("my init\n");
}
int main() {
printf("my main\n");
return 0;
}
__attribute__((destructor)) void mydeinit() {
printf("my deinit\n");
}
$ clang -Wall example.c
$ ./a.out
my init
my main
my deinit
Disclaimer: I generally discourage what I'm about to say. Having code running before or after main makes things less predictable. I'm not sure why you wouldn't just let the first line of main invoke your myinit, but I suppose everyone has a reason. Here goes.
I don't know much about Mach-O, but the simplest way to run code before main, is to link in a C++ class that has a corresponding global instance defined. You can do this independently of your "C" code without having to alter anything else. You can also have this C++ code invoke C functions defined elsewhere in your code. In the example below, I show a simple example of how I would invoke your myinit.
In a standalone .cpp (or .cc) file, declare a very simple C++ class with a constructor that calls your "myinit function".
foo.cpp
// forward declare your myinit function and designate "C" linkage
extern "C" myinit(int, char**, char**);
class CodeToRunBeforeMain
{
public:
CodeToRunBeforeMain()
{
// invoke your myinit function here
myinit(0, NULL, NULL);
}
};
// global instance - constructor will run before main.
CodeToRunBeforeMain g_runBeforeMain;
The above approach doesn't recognize argc, argv, or envp. Hopefully, that isn't important.