Skip to content

Commit

Permalink
[dso_demo] Add some non-trivial constructions (e.g. using TLS)
Browse files Browse the repository at this point in the history
The use of TLS from DSOs presents particularly interesting technical
challenges.

The use of TLS in general triggers a certain problem in Bazel on MacOS
at this point, which can be avoided by compiling with
--dynamic_mode=off or by disabling the dynamic mode feature
entirely (see bazelbuild/bazel#4341 (comment)).
  • Loading branch information
tkoeppe committed Oct 29, 2021
1 parent caadd0f commit 88eb952
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
4 changes: 4 additions & 0 deletions sandbox/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,8 @@ cc_binary(
srcs = ["dso_demo.cc"],
linkshared = 1,
linkstatic = 1,
deps = [
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/strings",
],
)
22 changes: 20 additions & 2 deletions sandbox/dso_demo.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
#include <cstdio>
#include <cstdlib>
#include <string>
#include <string_view>

extern "C" void demo_function() {
std::puts("I am a function.");
#include "absl/strings/string_view.h"
#include "absl/container/flat_hash_map.h"

extern "C" void demo_function(std::size_t n, const char* args[]) {
std::puts("I am a function. Here come my arguments.");

absl::flat_hash_map<std::string, std::vector<std::string>> m;

for (std::size_t i = 0; i != n; ++i) {
absl::string_view arg = args[i];
m[arg].emplace_back().assign(arg);
}

for (const auto& [k, v] : m) {
std::printf("Argument '%*s' appears %zu times.\n",
static_cast<int>(k.size()), k.data(), v.size());
}
}
5 changes: 3 additions & 2 deletions sandbox/dso_loader.cc
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#include <dlfcn.h>

#include <cstdio>
#include <cstdlib>
#include <cstring>

extern "C" {
using FunPtr = void();
using FunPtr = void(std::size_t, const char*[]);
} // extern "C"

int main(int argc, char* argv[]) {
Expand All @@ -23,7 +24,7 @@ int main(int argc, char* argv[]) {
} else {
FunPtr* f;
*reinterpret_cast<void**>(&f) = s;
f();
f(argc, const_cast<const char**>(argv));
}

if (dlclose(h) != 0) {
Expand Down

0 comments on commit 88eb952

Please sign in to comment.