summaryrefslogtreecommitdiffhomepage
path: root/src/CompilerKit/utils/DylibHelpers.h
blob: ab58fc7250df7015b7f660146e8132c793ee07c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* ========================================

  Copyright (C) 2025 Amlal El Mahrouss, Licensed under the Apache 2.0 license

======================================== */

#pragma once

#include <CompilerKit/Defines.h>
#include <dlfcn.h>
#include <mutex>

struct CompilerKitDylibTraits;

typedef Int32 (*CompilerKitEntrypoint)(Int32 argc, Char const* argv[]);
typedef VoidPtr CompilerKitDylib;

struct CompilerKitDylibTraits final {
  CompilerKitDylib      fDylib{nullptr};
  CompilerKitEntrypoint fEntrypoint{nullptr};
  std::mutex            fMutex;

  CompilerKitDylibTraits& operator()(const Char* path, const Char* fEntrypoint) {
    std::lock_guard<std::mutex> lock(this->fMutex);

    if (!path || !fEntrypoint) return *this;

    if (this->fDylib) {
      dlclose(this->fDylib);
      this->fDylib = nullptr;
    }

    this->fDylib = dlopen(path, RTLD_LAZY);

    if (!this->fDylib) {
      return *this;
    }

    this->fEntrypoint = (CompilerKitEntrypoint) dlsym(this->fDylib, fEntrypoint);

    if (!this->fEntrypoint) {
      dlclose(this->fDylib);
      this->fDylib = nullptr;

      return *this;
    }

    return *this;
  }

  NECTI_COPY_DELETE(CompilerKitDylibTraits);

  CompilerKitDylibTraits() = default;

  ~CompilerKitDylibTraits() {
    if (this->fDylib) {
      dlclose(this->fDylib);
      this->fDylib = nullptr;
    }

    this->fEntrypoint = nullptr;
  }
};