From 1fdab16d96de488e57c83ba7656e87c21fc6c86b Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 16 Apr 2016 15:35:47 -0400 Subject: [PATCH] ex29 --- lcthw-remnants-2/Makefile | 10 ++++++--- lcthw-remnants-2/ex29.c | 33 ++++++++++++++++++++++++++++ lcthw-remnants-2/libex29.c | 45 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 lcthw-remnants-2/ex29.c create mode 100644 lcthw-remnants-2/libex29.c diff --git a/lcthw-remnants-2/Makefile b/lcthw-remnants-2/Makefile index b959778..c6e5992 100644 --- a/lcthw-remnants-2/Makefile +++ b/lcthw-remnants-2/Makefile @@ -1,14 +1,18 @@ -SHELL=/bin/bash -CFLAGS=-Wall -g -DNDEBUG +SHELL = /bin/bash +CFLAGS = -Wall -g -DNDEBUG -fPIC +LDLIBS = -ldl EXERCISES := $(shell ./list-exercises) -all: $(EXERCISES) +all: $(EXERCISES) libex29.so ex19: object.o ex22_main: ex22.o +libex29.so: libex29.o + $(CC) -shared -o $@ $< + clean: shopt -s nullglob ; \ $(RM) $(EXERCISES) *.o *.a diff --git a/lcthw-remnants-2/ex29.c b/lcthw-remnants-2/ex29.c new file mode 100644 index 0000000..ff115c5 --- /dev/null +++ b/lcthw-remnants-2/ex29.c @@ -0,0 +1,33 @@ +#include +#include "dbg.h" +#include + +typedef int (*lib_function)(const char *data); + + +int main(int argc, char *argv[]) +{ + int rc = 0; + check(argc == 4, "USAGE: ex29 libex29.so function data"); + + char *lib_file = argv[1]; + char *func_to_run = argv[2]; + char *data = argv[3]; + + void *lib = dlopen(lib_file, RTLD_NOW); + check(lib != NULL, "Failed to open the library %s: %s", lib_file, dlerror()); + + lib_function func = dlsym(lib, func_to_run); + check(func != NULL, "Did not find %s function in the library %s: %s", func_to_run, lib_file, dlerror()); + + rc = func(data); + check(rc == 0, "Function %s return %d for data: %s", func_to_run, rc, data); + + rc = dlclose(lib); + check(rc == 0, "Failed to close %s", lib_file); + + return 0; + +error: + return 1; +} diff --git a/lcthw-remnants-2/libex29.c b/lcthw-remnants-2/libex29.c new file mode 100644 index 0000000..1aafd4f --- /dev/null +++ b/lcthw-remnants-2/libex29.c @@ -0,0 +1,45 @@ +#include +#include +#include "dbg.h" + + +int print_a_message(const char *msg) +{ + printf("A STRING: %s\n", msg); + + return 0; +} + + +int uppercase(const char *msg) +{ + int i = 0; + + // BUG: \0 termination problems + for(i = 0; msg[i] != '\0'; i++) { + printf("%c", toupper(msg[i])); + } + + printf("\n"); + + return 0; +} + +int lowercase(const char *msg) +{ + int i = 0; + + // BUG: \0 termination problems + for(i = 0; msg[i] != '\0'; i++) { + printf("%c", tolower(msg[i])); + } + + printf("\n"); + + return 0; +} + +int fail_on_purpose(const char *msg) +{ + return 1; +}