File: sem_init_glibc.cpp

package info (click to toggle)
llvm-toolchain-16 1%3A16.0.6-15~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,634,792 kB
  • sloc: cpp: 6,179,261; ansic: 1,216,205; asm: 741,319; python: 196,614; objc: 75,325; f90: 49,640; lisp: 32,396; pascal: 12,286; sh: 9,394; perl: 7,442; ml: 5,494; awk: 3,523; makefile: 2,723; javascript: 1,206; xml: 886; fortran: 581; cs: 573
file content (59 lines) | stat: -rw-r--r-- 1,995 bytes parent folder | download | duplicates (16)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// RUN: %clangxx -O0 -g %s -lutil -o %t && %run %t
// This test depends on the glibc layout of struct sem_t and checks that we
// don't leave sem_t::private uninitialized.
// UNSUPPORTED: android, lsan-x86, ubsan
#include <features.h>
#include <assert.h>
#include <semaphore.h>
#include <string.h>
#include <stdint.h>

// musl and glibc's __HAVE_64B_ATOMICS==0 ports (e.g. arm, i386) use 32-bit sem
// values. 64-bit glibc ports defining sem_init@GLIBC_2.0 (mips64) use 32-bit as
// well, if the sem_init interceptor picks the oldest versioned symbol
// (glibc<2.36, see https://sourceware.org/PR14932).
#if !defined(__GLIBC__) || defined(__ILP32__) ||                               \
    !__GLIBC_PREREQ(2, 36) && defined(__mips64__)
typedef unsigned semval_t;
#else
typedef uint64_t semval_t;
#endif

// glibc __HAVE_64B_ATOMICS==0 ports define a sem_init which shifts the value by
// 1 (https://sourceware.org/PR12674 glibc 2.21). The version is picked if
// either glibc>=2.36 or sem_init@GLIBC_2.0 is absent (arm and newer ports).
//
// The __GLIBC_PREREQ check is brittle in that it requires matched
// __GLIBC_PREREQ values for build time and run time.
#if defined(__GLIBC__) && defined(__ILP32__) &&                                \
    (__GLIBC_PREREQ(2, 36) || (__GLIBC_PREREQ(2, 21) && !defined(__i386__) &&  \
                               !defined(__mips__) && !defined(__powerpc__)))
#  define GET_SEM_VALUE(V) ((V) >> 1)
#else
#  define GET_SEM_VALUE(V) (V)
#endif

void my_sem_init(bool priv, int value, semval_t *a, unsigned char *b) {
  sem_t sem;
  memset(&sem, 0xAB, sizeof(sem));
  sem_init(&sem, priv, value);

  char *p = (char *)&sem;
  memcpy(a, p, sizeof(semval_t));
  memcpy(b, p + sizeof(semval_t), sizeof(char));

  sem_destroy(&sem);
}

int main() {
  semval_t a;
  unsigned char b;

  my_sem_init(false, 42, &a, &b);
  assert(GET_SEM_VALUE(a) == 42);
  assert(b != 0xAB);

  my_sem_init(true, 43, &a, &b);
  assert(GET_SEM_VALUE(a) == 43);
  assert(b != 0xAB);
}