Weak alias to mock - c

I'm trying to mock a fn say foo using
#ifdef UT_TEST
void foo(void) __attribute__ ((weak, alias ("foo_impl")));
#else
void foo(void);
#endif
However, is there a way to do this # runtime instead of compile time? I cannot use C++, for historical reasons.

In the past I've mostly seen this problem solved at the build system level instead, which I feel is a cleaner solution. Doing it this way allows to avoid most ifdefs and instead work with full files. In make, it might look something like this:
OBJS += file1.o file2.o
ifeq ($(UNIT_TEST),y)
OBJS += dummy_implementation.o
else
OBJS += real_implementation.o
endif
myprog: $(OBJS)
or in more classic make idiom:
OBJS-y += file1.o file2.o
OBJS-$(UNIT_TEST) += dummy_implementation.o
OBJS-$(REAL_BUILD) += real_implementation.o
OBJS = $(OBJS-y)
myprog: $(OBJS)
dummy_implementation.c and real_implementation.c would share a header file in this case.

Related

GDB Debugger - "malloc" not defined. Trying to assign C array with debugger

I've got some software compiled to run on an embedded NRF24 target, using a gcc-arm-none-eabi toolchain from here (a custom one that provides gdb with support for python3) . I'm trying essentially, malloc an array from the GDB debugger console at runtime, then fill it with elements that I provide.
I have a pointer defined in a .c file like: static float32_t *array;.
I want to then call a cmd like: call (void*) malloc(num_of_elements*sizeof(float32_t)) from inside the GDB console to allocate an array at runtime, and then fill it with elements with something like maybe: call (void*) memcpy(array, {var1, var2... var n}, n)
My issue is the GDB debugger cannot find the malloc stdlib function. If I do something like:
break malloc
Function "malloc" not defined.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal]
It can't find this function, although it is fine with finding <string.h> fns, like memcpy for example and I can't quite work out why this is.
I have a feeling it could be something to do with linking, the program is built with a Makefile, the flags towards the end may be of interest:
LIB_FILES += \
$(SDK_ROOT)/components/toolchain/cmsis/dsp/GCC/libarm_cortexM4lf_math.a \
# Optimization flags
OPT = -O0 -g3
# Uncomment the line below to enable link time optimization
#OPT += -flto
# C flags common to all targets
CFLAGS += $(OPT)
CFLAGS += -DBOARD_PCA10056
CFLAGS += -DARM_MATH_CM4
CFLAGS += -DBSP_DEFINES_ONLY
CFLAGS += -DCONFIG_GPIO_AS_PINRESET
CFLAGS += -DFLOAT_ABI_HARD
CFLAGS += -DNRF52840_XXAA
CFLAGS += -mcpu=cortex-m4
CFLAGS += -mthumb -mabi=aapcs
CFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
# keep every function in a separate section, this allows linker to discard unused ones
CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
CFLAGS += -fno-builtin -fshort-enums
CFLAGS += -DDEV8_PINOUT
CFLAGS += -DNUM_FLASH_BLOCKS=128
CFLAGS += -DDEBUG
CFLAGS += -DNRF_LOG_ENABLED=1
CFLAGS += -DNRF_LOG_BACKEND_UART_ENABLED=1
# C++ flags common to all targets
CXXFLAGS += $(OPT)
# Assembler flags common to all targets
ASMFLAGS += $(OPT)
ASMFLAGS += -mcpu=cortex-m4
ASMFLAGS += -mthumb -mabi=aapcs
ASMFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
ASMFLAGS += -DBOARD_PCA10056
ASMFLAGS += -DBSP_DEFINES_ONLY
ASMFLAGS += -DCONFIG_GPIO_AS_PINRESET
ASMFLAGS += -DFLOAT_ABI_HARD
ASMFLAGS += -DNRF52840_XXAA
ASMFLAGS += -DARM_MATH_CM4
# Linker flags
LDFLAGS += $(OPT)
LDFLAGS += -mthumb -mabi=aapcs -L$(SDK_ROOT)/modules/nrfx/mdk -T$(LINKER_SCRIPT)
LDFLAGS += -mcpu=cortex-m4
LDFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
# let linker dump unused sections
LDFLAGS += -Wl,--gc-sections
# use newlib in nano version
LDFLAGS += --specs=nano.specs
LDFLAGS += -Wl,--print-memory-usage
nrf52840_xxaa: CFLAGS += -D__HEAP_SIZE=8192
nrf52840_xxaa: CFLAGS += -D__STACK_SIZE=8192
nrf52840_xxaa: ASMFLAGS += -D__HEAP_SIZE=8192
nrf52840_xxaa: ASMFLAGS += -D__STACK_SIZE=8192
# Add standard libraries at the very end of the linker input, after all objects
# that may need symbols provided by these libraries.
LIB_FILES += -lc -lnosys -lm
To debug I'm using GDB with a Jlink server type setup.
Your code needs to explicitly reference the symbol to force it to link, and you need to prevent link optimisation from removing unused references. Rather then doing a dummy call with potential unwanted side effects, you can simply refer to the symbol via a function pointer instantiation thus:
void* (*volatile force_malloc_link)(size_t) = &malloc ;
Or more simply since you will not actually invoke the function through the pointer:
volatile void* force_link_malloc = &malloc ;
You could make it generic with a macro for any symbol you wish to link:
#define FORCE_LINK( sym ) volatile void* force_link_ ## sym = &sym
You can also force the entire library to be linked (if you have the space) - How to force gcc to link an unused static library. One of the answers there explains how you can also unpack the static library and link individual object files.
It can't find this function
The function may not be linked into your binary.
Does your binary call malloc elsewhere?
Do you link against libc.so or libc.a?
Does nm a.out | grep ' malloc' find it?
it is fine with finding <string.h> fns, like memcpy
If your binary calls memcpy and you link against libc.a, then memcpy implementation will be linked in. Using the same nm command from above will show that the memcpy symbol is present and malloc is not.
If you want to call malloc at runtime, you need to make sure it's linked in. One way to achieve this is to add:
const char *argv0;
int main(int argc, char *argv[])
{
argv0 = strdup(argv[0]); // This should guarantee that malloc is linked in.
// rest of the program
}

Can I use a #define representation of a stdlib function?

I kinda liked the idea of having my own sprintf function without the string.h or stdio.h bloatware.
#define sprintf(x) my_sprintf(x)
void my_sprintf(const char * string);
int main(void)
{
sprintf("abc");
}
These are my LD flags:
LDFLAGS += -lgcc
LDFLAGS += --specs=nano.specs
LDFLAGS += -mthumb
LDFLAGS += -mcpu=cortex-m4
# LDFLAGS += --gc-sections
# LDFLAGS += -nostartfiles
# LDFLAGS += -nodefaultlibs
# LDFLAGS += -gc-sections
As you see, I have the nostartfiles and nodefaultlibs options unset. So, even if I had the idea of including string.h or stdio.h, The compiler might find a definition/reference of the sprintf function.
So I'd like to know what if the #define will still refer to the "redefinition" if it is the same than an existing function name.
Any help is warmly welcome.
Yes, but an easier way would be to use a freestanding environment:
gcc -ffreestanding ...
If you want to know if your approach will take effect across files (i.e. #define function(x) y in file1.c and function(z) in file2.c), then no, it won't.

conditional compilation flags in make

How to solve the following problem with make?
SRCS1 = a.c b,c
SRCS2 = d.c e.c
SRCS= $(SRCS1) $(SRCS2)
OBJS1 = $(subst .c,.o,$(SRCS1))
OBJS2 = $(subst .c,.o,$(SRCS2))
OBJS = $(OBJS1) $(OBJS2)
include ../Makeconf
(which contains CPPFLAGS=-Dfoo) (the main Makefile is also in ../)
Now I want to compile SRCS1 with foo defined and SRCS2 with foo not defined.
I tried
ifneq (,$(findstring $(OBJS2),$(OBJS)))
CPPFLAGS += -Ufoo
endif
but that adds -Ufoo to all files when compiled. Any ideas?
You haven't shown us enough of the makefile(s) to give a complete answer, but I think this is what you're looking for:
$(OBJS2): CPPFLAGS += -Ufoo

Compiling multiple files in C

I recently asked this question about compiling multiple files in C so that a file main.c can reference a file modules.c. The answer ended up being to make the modules file into a header file and having main import it.
I have now been told that this is an incorrect way to do it, as C supports modular compilation. My Makefile is below, and this is supposedly supposed to be correct, but I receive errors for each function call in main.c -- warning: implicit declaration of function X.
What do I need to do to compile this correctly, with two .c files rather than a .c and .h file? The main.c file has a main() function that needs to be able to call the functions in modules.c.
Makefile:
#################################################################
# Variables
# -- allows C-source and assembly-source files mix. Again, the
# -- indented lines start with a TAB(^I) and not spaces..
#################################################################
CFLAGS = -g -Wall -Werror
LDFLAGS =
CC = gcc
LD = gcc
TARG = driver
OBJS = modules.o main.o
#################################################################
# Rules for make
#################################################################
$(TARG): $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $(TARG)
%.o: %.c %.s
$(CC) $(CFLAGS) -c $<
clean:
rm -f *.o *˜ $(TARG)
print:
pr -l60 Makefile modules.c main.c | lpr
#################################################################
# Dependencies -- none in this program
#################################################################
You've already gotten feedback about using GCC and Makefiles, and it's been noted that the typical way to accomplish your task would be two .c files and one .h file. But it's not required to have a .h file if you use function declarations (which is arguably simpler, just less maintainable and useful), as demonstrated by the following below example.
main.c:
void moduleFunc1(int); // extern keyword required for vars, not for functions
int main()
{
moduleFunc1(100);
return 0;
}
module.c:
#include <stdio.h>
void moduleFunc1(int value)
{
printf("%d\n", value);
}
To compile:
gcc main.c module.c
Edit: After having looked at the assignment you linked, my best guess is actually still that function declarations are what you are looking for. To quote from the assignment, under "Others", #7:
A function should be declared in the module/function where
it is called and not in global scope. Say A calls B and C does
not call it then B should be declared in A only.
In my example, the function declaration is in the module where it's called and seems to meet the A-B-C example. (The confusing part is the global scope comment, but I wouldn't say that the function declaration's scope is global. Observe that if you move the declaration below main(), for example, it messes things up. I haven't found something strictly authoritative for this point, though.)
Having read the assignment, could your instructor possibly mean the following?
main.c:
#include <stdio.h>
int main() {
int plus(int a, int b); /* declaration */
printf("%d ", plus(4, 5));
exit(0);
}
module.c:
int plus(int a, int b) {
return a + b;
}
gcc -Wall -Wextra main.c module.c
The thing is though, that plus() is available in the global namespace. So I am a bit lost.
Just an aside:
3. int next = 234;
printf("%6d ", next);
will print value of next, right justified in 6 columns
6. Use separate statements for declaration and initialization
of a variable as:
int xval;
xval = 100;
Do as I say, not as I do!
You can do this a few ways, but regardless of which you choose, if main.c calls functions from module.c, then main.c must #include a header which declares prototypes for those functions.
The first and simplest way is to just do this:
gcc -Wall -g main.c module.c -o myprogram
The second and more ornate way is to build module.c first as an object file. The primary purpose of this method is to save time when developing/debugging/compiling large programs with multiple parts -- rather than having to recompile the whole thing, you can just recompile the parts the have changed. It also allows you to easily mix and match parts. This is easiest to do with a makefile:
myprogram: main.c module.o
CC $(CFLAGS) main.c module.o -o myprogram
module.o:
CC $(CFLAGS) -c module.c
Notice the "myprogram" target from the makefile works with (prereq) module.o whereas the plain gcc method works with module.c.
If, as per your assignment, you can't use a header or global declarations, you can declare prototypes inside functions:
void somefunc () {
char *whatever (int x); // prototype
printf("%s\n", whatever(12));
}
Is fine, and presuming whatever() is defined somewhere, will work when you compile and run it.

object file missing function symbol

I am currently writing a short test app.
The compilation gives me these errors :
CC main.c
Building ../bin/pmono
./main.o:(.data+0x18): undefined reference to `busy'
./main.o:(.data+0x58): undefined reference to `busy'
./main.o:(.data+0x98): undefined reference to `busy'
./main.o:(.data+0xd8): undefined reference to `busy'
./main.o:(.data+0x118): undefined reference to `busy'
./main.o:(.data+0x158): more undefined references to `busy' follow
collect2: ld a retourné 1 code d'état d'exécution
I will try to narrow the code down to the specific parts.
Here is a structure I use which contain the desired reference :
/*
* Chained list of blocks from a frame of the cyclic executive
*/
typedef struct block {
long c; /* Worst case execution time */
long d; /* Deadline */
long p; /* Period */
void (*action) (long); /* Action performed by this frame */
struct block * next;
} *Frame;
The function pointer is placeholder for a generic function not written yet, declared as such in the same .h file :
/*
* Load the CPU for a determined time expressed in nanosecond
*/
void busy(long t);
The function is currently hollow in the c file :
void busy(long t) {
}
Finally, here is a sample default structure I use in my tests :
struct block D = {8,20,20,busy,0};
struct block C = {2,20,20,busy,&D};
struct block B = {3,10,10,busy,&C};
struct block A = {1,10,10,busy,&B};
Frame sequence0 = &A;
All of these parts are contained in a common source file shared between numerous implementations of periodic tasks. The compilation of the object file seems fine.
When I try to compile a given implementation, I first include the .h file, compile the .o file, then try to link the whole thing, using makefile. Here is one makefile to give you an idea :
BIN = ../bin/pmono
CC = gcc
SUBDIR = .
SRC = $(foreach dir, $(SUBDIR), $(wildcard $(dir)/*.c))
OBJ = $(SRC:.c=.o) $(wildcard ../common/*.o)
INCLUDES =
WARNINGS =
OPTIMISATION =
DEBUG =
XENO_CONFIG = /usr/xenomai/bin/xeno-config
XENO_POSIX_CFLAGS = $(shell $(XENO_CONFIG) --skin=posix --cflags)
XENO_POSIX_LDFLAGS = $(shell $(XENO_CONFIG) --skin=posix --ldflags)
CFLAGS = $(INCLUDES) $(XENO_POSIX_CFLAGS) $(WARNINGS) $(OPTIMISATION)
LDFLAGS = -lm $(XENO_POSIX_LDFLAGS) $(DEBUG)
all:.depend $(BIN)
%.o:%.c
#echo "CC $<"
#$(CC) -c $(CFLAGS) $< -o $#
$(BIN): $(OBJ)
#echo "Building ${BIN}"
#$(CC) $(OBJ) -o $# $(LDFLAGS)
clean:
rm -f $(OBJ)
distclean: clean
rm -f $(BIN)
rm -f ./.depend
.depend: $(SRC)
#echo "Génération des dépendances"
#$(CC) $(CFLAGS) -MM $(SRC) > .depend
-include .depend
So, I'm a beginner in this, and this is my understanding : the symbol of the busy function is missing in the main.o, while it exists in the cyclic_executive.o file. I don't understand how this is possible, as I include the cyclic_executive.h file, thus giving the proper declaration and prototype.
I think I'm doing it wrong, but I'm short on idea.
Also, I really dislike how I declare my "default" sequence. I know there is a proper way to do it, but I can't recall it... Does someone has a name to help search for it ?
Thanks.
You are not linking the file with the busy() function call.
Try this from the command line:
gcc main.c cyclic_executive.c
If it works, or at least doesn't give errors on the busy() function, that will confirm the issue. Then try
make all
This should print all the commands as they are executed. If you are still in the dark, try
make -d
That will give you a ton of diagnostics about what make is actually doing.

Resources