Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a refcount to library init/cleanup #1691

Merged
merged 1 commit into from May 20, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
add a refcount to library init/cleanup
Add a refcount around mosquitto_lib_init and mosquitto_lib_cleanup so
that multiple calls to init/cleanup don't trigger memory leaks or
double-frees.

Signed-off-by: Martin Kelly <[email protected]>
  • Loading branch information
Martin Kelly committed May 16, 2020
commit 6a4c90e04534b8ac8fbab2c1cdac33f166495c4b
41 changes: 29 additions & 12 deletions lib/mosquitto.c
Expand Up @@ -34,6 +34,7 @@ and the Eclipse Distribution License is available at
#include "packet_mosq.h"
#include "will_mosq.h"

static unsigned int init_refcount = 0;

void mosquitto__destroy(struct mosquitto *mosq);

Expand All @@ -47,31 +48,47 @@ int mosquitto_lib_version(int *major, int *minor, int *revision)

int mosquitto_lib_init(void)
{
int rc;

if (init_refcount == 0) {
#ifdef WIN32
srand(GetTickCount64());
srand(GetTickCount64());
#elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK)
struct timespec tp;
struct timespec tp;

clock_gettime(CLOCK_MONOTONIC, &tp);
srand(tp.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &tp);
srand(tp.tv_nsec);
#elif defined(__APPLE__)
uint64_t ticks;
uint64_t ticks;

ticks = mach_absolute_time();
srand((unsigned int)ticks);
ticks = mach_absolute_time();
srand((unsigned int)ticks);
#else
struct timeval tv;
struct timeval tv;

gettimeofday(&tv, NULL);
srand(tv.tv_sec*1000 + tv.tv_usec/1000);
gettimeofday(&tv, NULL);
srand(tv.tv_sec*1000 + tv.tv_usec/1000);
#endif

return net__init();
rc = net__init();
if (rc != MOSQ_ERR_SUCCESS) {
return rc;
}
}

init_refcount++;
return MOSQ_ERR_SUCCESS;
}

int mosquitto_lib_cleanup(void)
{
net__cleanup();
if (init_refcount == 1) {
net__cleanup();
}

if (init_refcount > 0) {
--init_refcount;
}

return MOSQ_ERR_SUCCESS;
}
Expand Down