File: fiber_cleanup.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (71 lines) | stat: -rw-r--r-- 1,766 bytes parent folder | download | duplicates (26)
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
60
61
62
63
64
65
66
67
68
69
70
71
// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
// REQUIRES: linux
#include "test.h"

#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

long count_memory_mappings() {
  pid_t my_pid = getpid();
  char proc_file_name[128];
  snprintf(proc_file_name, sizeof(proc_file_name), "/proc/%d/maps", my_pid);

  FILE *proc_file = fopen(proc_file_name, "r");
  long line_count = 0;
  int c;
  do {
    c = fgetc(proc_file);
    if (c == '\n') {
      line_count++;
    }
  } while (c != EOF);
  fclose(proc_file);

  return line_count;
}

void fiber_iteration() {
  void *orig_fiber = __tsan_get_current_fiber();
  void *fiber = __tsan_create_fiber(0);

  pthread_mutex_t mutex;
  pthread_mutex_init(&mutex, NULL);

  // Running some code on the fiber that triggers handling of pending signals.
  __tsan_switch_to_fiber(fiber, 0);
  pthread_mutex_lock(&mutex);
  pthread_mutex_unlock(&mutex);
  __tsan_switch_to_fiber(orig_fiber, 0);

  // We expect the fiber to clean up all resources (here the sigcontext) when destroyed.
  __tsan_destroy_fiber(fiber);
}

// Magic-Number for some warmup iterations,
// as tsan maps some memory for the first runs.
const size_t num_warmup = 100;

int main() {
  for (size_t i = 0; i < num_warmup; i++) {
    fiber_iteration();
  }

  long memory_mappings_before = count_memory_mappings();
  fiber_iteration();
  fiber_iteration();
  long memory_mappings_after = count_memory_mappings();

  // Is there a better way to detect a resource  leak in the
  // ThreadState object? (i.e. a mmap not being freed)
  if (memory_mappings_before == memory_mappings_after) {
    fprintf(stderr, "PASS\n");
  } else {
    fprintf(stderr, "FAILED\n");
  }

  return 0;
}

// CHECK-NOT: WARNING: ThreadSanitizer:
// CHECK: PASS