1// RUN: %clangxx -O0 -g %s -lutil -o %t && %run %t
2// This test depends on the glibc layout of struct sem_t and checks that we
3// don't leave sem_t::private uninitialized.
4// UNSUPPORTED: android, lsan-x86, ubsan
5#include <features.h>
6#include <assert.h>
7#include <semaphore.h>
8#include <string.h>
9#include <stdint.h>
10
11// musl and glibc's __HAVE_64B_ATOMICS==0 ports (e.g. arm, i386) use 32-bit sem
12// values. 64-bit glibc ports defining sem_init@GLIBC_2.0 (mips64) use 32-bit as
13// well, if the sem_init interceptor picks the oldest versioned symbol
14// (glibc<2.36, see https://sourceware.org/PR14932).
15#if !defined(__GLIBC__) || defined(__ILP32__) || \
16 !__GLIBC_PREREQ(2, 36) && defined(__mips64__)
17typedef unsigned semval_t;
18#else
19typedef uint64_t semval_t;
20#endif
21
22// glibc __HAVE_64B_ATOMICS==0 ports define a sem_init which shifts the value by
23// 1 (https://sourceware.org/PR12674 glibc 2.21). The version is picked if
24// either glibc>=2.36 or sem_init@GLIBC_2.0 is absent (arm and newer ports).
25//
26// The __GLIBC_PREREQ check is brittle in that it requires matched
27// __GLIBC_PREREQ values for build time and run time.
28#if defined(__GLIBC__) && defined(__ILP32__) && \
29 (__GLIBC_PREREQ(2, 36) || (__GLIBC_PREREQ(2, 21) && !defined(__i386__) && \
30 !defined(__mips__) && !defined(__powerpc__)))
31# define GET_SEM_VALUE(V) ((V) >> 1)
32#else
33# define GET_SEM_VALUE(V) (V)
34#endif
35
36void my_sem_init(bool priv, int value, semval_t *a, unsigned char *b) {
37 sem_t sem;
38 memset(s: &sem, c: 0xAB, n: sizeof(sem));
39 sem_init(sem: &sem, pshared: priv, value: value);
40
41 char *p = (char *)&sem;
42 memcpy(dest: a, src: p, n: sizeof(semval_t));
43 memcpy(dest: b, src: p + sizeof(semval_t), n: sizeof(char));
44
45 sem_destroy(sem: &sem);
46}
47
48int main() {
49 semval_t a;
50 unsigned char b;
51
52 my_sem_init(priv: false, value: 42, a: &a, b: &b);
53 assert(GET_SEM_VALUE(a) == 42);
54 assert(b != 0xAB);
55
56 my_sem_init(priv: true, value: 43, a: &a, b: &b);
57 assert(GET_SEM_VALUE(a) == 43);
58 assert(b != 0xAB);
59}
60

source code of compiler-rt/test/sanitizer_common/TestCases/Linux/sem_init_glibc.cpp