1/*
2   Copyright 2021 Northern.tech AS
3
4   This file is part of CFEngine 3 - written and maintained by Northern.tech AS.
5
6   This program is free software; you can redistribute it and/or modify it
7   under the terms of the GNU General Public License as published by the
8   Free Software Foundation; version 3.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15  You should have received a copy of the GNU General Public License
16  along with this program; if not, write to the Free Software
17  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
18
19  To the extent this program is licensed as part of the Enterprise
20  versions of CFEngine, the applicable Commercial Open Source License
21  (COSL) may apply to this file if you as a licensee so wish it. See
22  included file COSL.txt.
23*/
24
25BEGIN_MARKER // Do not include this file directly! Build process should replace XextensionX occurrences.
26
27#include <XextensionX_extension.h>
28
29#include <logging.h>
30
31#include <pthread.h>
32
33#ifndef BUILTIN_EXTENSIONS
34
35static pthread_once_t XextensionX_library_once = PTHREAD_ONCE_INIT;
36static void *XextensionX_library_handle = NULL;
37
38static void XextensionX_library_assign();
39
40void *XextensionX_library_open()
41{
42    if (getenv("CFENGINE_TEST_OVERRIDE_EXTENSION_LIBRARY_DO_CLOSE") != NULL)
43    {
44        return extension_library_open(xEXTENSIONx_LIBRARY_NAME);
45    }
46
47    int ret = pthread_once(&XextensionX_library_once, &XextensionX_library_assign);
48    if (ret != 0)
49    {
50        Log(LOG_LEVEL_ERR, "Could not initialize Extension Library: %s: %s", xEXTENSIONx_LIBRARY_NAME, strerror(ret));
51        return NULL;
52    }
53    return XextensionX_library_handle;
54}
55
56static void XextensionX_library_assign()
57{
58    XextensionX_library_handle = extension_library_open(xEXTENSIONx_LIBRARY_NAME);
59}
60
61void XextensionX_library_close(void *handle)
62{
63    if (getenv("CFENGINE_TEST_OVERRIDE_EXTENSION_LIBRARY_DO_CLOSE") != NULL)
64    {
65        return extension_library_close(handle);
66    }
67
68    // Normally we don't ever close the extension library, because we may have
69    // pointer references to it.
70}
71
72#endif // BUILTIN_EXTENSIONS
73