Fix CVE-2017-6891 in minitasn1 code
[platform/upstream/gnutls.git] / lib / locks.h
1 /*
2  * Copyright (C) 2010-2012 Free Software Foundation, Inc.
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * The GnuTLS is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2.1 of
11  * the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>
20  *
21  */
22
23 #ifndef GNUTLS_LOCKS_H
24 #define GNUTLS_LOCKS_H
25
26 #include <gnutls/gnutls.h>
27 #include <gnutls_int.h>
28 #include <system.h>
29
30 extern mutex_init_func gnutls_mutex_init;
31 extern mutex_deinit_func gnutls_mutex_deinit;
32 extern mutex_lock_func gnutls_mutex_lock;
33 extern mutex_unlock_func gnutls_mutex_unlock;
34
35 #if defined(HAVE_WIN32_LOCKS)
36 # include <windows.h>
37
38 /* Idea based based on comment 2 at:
39  * http://stackoverflow.com/questions/3555859/is-it-possible-to-do-static-initialization-of-mutexes-in-windows
40  */
41 # define GNUTLS_STATIC_MUTEX(mutex) \
42         static CRITICAL_SECTION *mutex = NULL
43
44 # define GNUTLS_STATIC_MUTEX_LOCK(mutex) \
45         if (mutex == NULL) { \
46                 CRITICAL_SECTION *mutex##tmp = malloc(sizeof(CRITICAL_SECTION)); \
47                 InitializeCriticalSection(mutex##tmp); \
48                 if (InterlockedCompareExchangePointer((PVOID*)&mutex, (PVOID)mutex##tmp, NULL) != NULL) { \
49                         DeleteCriticalSection(mutex##tmp); \
50                         free(mutex##tmp); \
51                 } \
52         } \
53         EnterCriticalSection(mutex)
54
55 # define GNUTLS_STATIC_MUTEX_UNLOCK(mutex) \
56         LeaveCriticalSection(mutex)
57
58 #elif defined(HAVE_PTHREAD_LOCKS)
59 # include <pthread.h>
60 # define GNUTLS_STATIC_MUTEX(mutex) \
61         static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER
62
63 # define GNUTLS_STATIC_MUTEX_LOCK(mutex) \
64         pthread_mutex_lock(&mutex)
65
66 # define GNUTLS_STATIC_MUTEX_UNLOCK(mutex) \
67         pthread_mutex_unlock(&mutex)
68
69 #else
70 # define GNUTLS_STATIC_MUTEX(mutex)
71 # define GNUTLS_STATIC_MUTEX_LOCK(mutex)
72 # define GNUTLS_STATIC_MUTEX_UNLOCK(mutex)
73 #endif
74
75 #endif