Exercises: Add interceptor library

This commit is contained in:
Alex Hirsch 2021-01-07 23:27:52 +01:00
parent 4f48e9bf7a
commit 4d822fd15d
5 changed files with 84 additions and 0 deletions

View File

@ -329,3 +329,31 @@ Explain all parts like it's done in the lecture.
Take a look at [Boost Operators](https://www.boost.org/doc/libs/1_74_0/libs/utility/operators.htm). Take a look at [Boost Operators](https://www.boost.org/doc/libs/1_74_0/libs/utility/operators.htm).
Try to understand *why* the *curiously recurring template pattern (CRTP)* is used. Try to understand *why* the *curiously recurring template pattern (CRTP)* is used.
## Task 22
You are given the code and build instructions for a shared library and an executable which uses the shared library.
The shared library features two functions `random_number` and `just_a_print` inside the `foo` namespace.
Your task is to create an *interceptor* library:
- `random_number` should be replaced with a function that always returns `4` for improved determinism
- `just_a_print` should be wrapped so that some text is printed before and after the original function is executed
Running the executable with and without the interceptor library could look like this:
```
$ ./executable
Random Number: 880806932
Just a print to stdout, nothing else
$ LD_PRELOAD=$PWD/interceptor.so ./executable
Random Number: 4
some text before
Just a print to stdout, nothing else
some text after
```
**Hint:** For Linux, have a look at the related man-pages, like *ld-linux(8)*.

View File

@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.8)
project(example LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_library(foo SHARED libFoo/foo.cpp)
target_include_directories(foo PUBLIC libFoo)
add_executable(executable executable.cpp)
target_link_libraries(executable foo)

View File

@ -0,0 +1,9 @@
#include <iostream>
#include "foo.hpp"
int main()
{
std::cout << "Random Number: " << foo::random_number() << "\n\n";
foo::just_a_print();
}

View File

@ -0,0 +1,23 @@
#include "foo.hpp"
#include <iostream>
#include <limits>
#include <random>
namespace foo {
int random_number()
{
static std::random_device device;
static std::mt19937 rng(device());
static std::uniform_int_distribution<int> dist(0, std::numeric_limits<int>::max());
return dist(rng);
}
void just_a_print()
{
std::cout << "Just a print to stdout, nothing else\n";
}
} // end namespace foo

View File

@ -0,0 +1,12 @@
#ifndef FOO_HPP
#define FOO_HPP
namespace foo {
int random_number();
void just_a_print();
} // end namespace foo
#endif // FOO_HPP