summaryrefslogtreecommitdiff
path: root/libavutil/cpu.c
diff options
context:
space:
mode:
authorWan-Teh Chang <wtc@google.com>2016-12-07 16:16:02 -0800
committerVittorio Giovara <vittorio.giovara@gmail.com>2016-12-08 15:53:58 -0500
commit2170017a1cd033b6f28e16476921022712a522d8 (patch)
treecfcbe102ef4c0fcddd52e2b51b9fca5a850db146 /libavutil/cpu.c
parentd5759701a82926059ae3e2530805e900041a5419 (diff)
downloadffmpeg-2170017a1cd033b6f28e16476921022712a522d8.tar.gz
avutil: fix data race in av_get_cpu_flags()
Make the one-time initialization in av_get_cpu_flags() thread-safe. The static variables |flags|, |cpuflags_mask|, and |checked| in libavutil/cpu.c are read and written using normal load and store operations. These are considered as data races. The fix is to use atomic load and store operations. Remove the |checked| variable because the invalid value of -1 for |flags| can be used to indicate the same condition. Rename |flags| to |cpu_flags| and move it to file scope. The fix can be verified by running the libavutil/tests/cpu_init.c test program under ThreadSanitizer: ./configure --toolchain=clang-tsan make libavutil/tests/cpu_init libavutil/tests/cpu_init There should be no warnings from ThreadSanitizer. Co-author: Dmitry Vyukov of Google, who suggested the data race fix. Signed-off-by: Wan-Teh Chang <wtc@google.com>
Diffstat (limited to 'libavutil/cpu.c')
-rw-r--r--libavutil/cpu.c34
1 files changed, 18 insertions, 16 deletions
diff --git a/libavutil/cpu.c b/libavutil/cpu.c
index 7d7390a756..0109c9e8d1 100644
--- a/libavutil/cpu.c
+++ b/libavutil/cpu.c
@@ -17,6 +17,7 @@
*/
#include <stdint.h>
+#include <stdatomic.h>
#include "cpu.h"
#include "cpu_internal.h"
@@ -42,34 +43,35 @@
#include <unistd.h>
#endif
-static int cpuflags_mask = -1, checked;
+static atomic_int cpu_flags = ATOMIC_VAR_INIT(-1);
-int av_get_cpu_flags(void)
+static int get_cpu_flags(void)
{
- static int flags;
-
- if (checked)
- return flags;
-
if (ARCH_AARCH64)
- flags = ff_get_cpu_flags_aarch64();
+ return ff_get_cpu_flags_aarch64();
if (ARCH_ARM)
- flags = ff_get_cpu_flags_arm();
+ return ff_get_cpu_flags_arm();
if (ARCH_PPC)
- flags = ff_get_cpu_flags_ppc();
+ return ff_get_cpu_flags_ppc();
if (ARCH_X86)
- flags = ff_get_cpu_flags_x86();
-
- flags &= cpuflags_mask;
- checked = 1;
+ return ff_get_cpu_flags_x86();
+ return 0;
+}
+int av_get_cpu_flags(void)
+{
+ int flags = atomic_load_explicit(&cpu_flags, memory_order_relaxed);
+ if (flags == -1) {
+ flags = get_cpu_flags();
+ atomic_store_explicit(&cpu_flags, flags, memory_order_relaxed);
+ }
return flags;
}
void av_set_cpu_flags_mask(int mask)
{
- cpuflags_mask = mask;
- checked = 0;
+ atomic_store_explicit(&cpu_flags, get_cpu_flags() & mask,
+ memory_order_relaxed);
}
int av_parse_cpu_flags(const char *s)