Skip to content

Commit 81c9894

Browse files
authored
Merge pull request libgit2#4645 from pks-t/pks/racy-init-deinit
global: adjust init count under lock
2 parents 6c2939d + 0933fdc commit 81c9894

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

src/global.c

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -276,10 +276,10 @@ int git_libgit2_init(void)
276276
{
277277
int ret, err;
278278

279-
ret = git_atomic_inc(&git__n_inits);
280-
281279
if ((err = pthread_mutex_lock(&_init_mutex)) != 0)
282280
return err;
281+
282+
ret = git_atomic_inc(&git__n_inits);
283283
err = pthread_once(&_once_init, init_once);
284284
err |= pthread_mutex_unlock(&_init_mutex);
285285

@@ -293,13 +293,13 @@ int git_libgit2_shutdown(void)
293293
{
294294
void *ptr = NULL;
295295
pthread_once_t new_once = PTHREAD_ONCE_INIT;
296-
int ret;
296+
int error, ret;
297297

298-
if ((ret = git_atomic_dec(&git__n_inits)) != 0)
299-
return ret;
298+
if ((error = pthread_mutex_lock(&_init_mutex)) != 0)
299+
return error;
300300

301-
if ((ret = pthread_mutex_lock(&_init_mutex)) != 0)
302-
return ret;
301+
if ((ret = git_atomic_dec(&git__n_inits)) != 0)
302+
goto out;
303303

304304
/* Shut down any subsystems that have global state */
305305
shutdown_common();
@@ -314,10 +314,11 @@ int git_libgit2_shutdown(void)
314314
git_mutex_free(&git__mwindow_mutex);
315315
_once_init = new_once;
316316

317-
if ((ret = pthread_mutex_unlock(&_init_mutex)) != 0)
318-
return ret;
317+
out:
318+
if ((error = pthread_mutex_unlock(&_init_mutex)) != 0)
319+
return error;
319320

320-
return 0;
321+
return ret;
321322
}
322323

323324
git_global_st *git__global_state(void)

0 commit comments

Comments
 (0)