Skip to content

Commit

Permalink
add a refcount to library init/cleanup
Browse files Browse the repository at this point in the history
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 authored and ralight committed May 20, 2020
1 parent eae8c9a commit 61a50c6
Showing 1 changed file with 29 additions and 12 deletions.
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

0 comments on commit 61a50c6

Please sign in to comment.