Coverage Report

Created: 2024-04-26 06:25

/src/adhd/cras/server/cras_thread.c
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2024 The ChromiumOS Authors
2
// Use of this source code is governed by a BSD-style license that can be
3
// found in the LICENSE file.
4
5
#include "cras/server/cras_thread.h"
6
7
#include <pthread.h>
8
#include <stdbool.h>
9
#include <stdlib.h>
10
#include <threads.h>
11
12
#include "cras/common/check.h"
13
14
static thread_local bool main_ctx_allowed = false;
15
static thread_local bool audio_ctx_allowed = false;
16
17
0
struct cras_main_ctx* checked_main_ctx() {
18
0
  CRAS_CHECK(main_ctx_allowed);
19
20
0
  static struct cras_main_ctx mctx = {};
21
0
  return &mctx;
22
0
}
23
24
0
struct cras_audio_ctx* checked_audio_ctx() {
25
0
  CRAS_CHECK(audio_ctx_allowed);
26
27
0
  static struct cras_audio_ctx actx = {};
28
0
  return &actx;
29
0
}
30
31
0
__attribute__((constructor)) static void init() {
32
0
  main_ctx_allowed = audio_ctx_allowed = true;
33
0
}
34
35
struct start_routine_wrapper_data {
36
  void* (*start_routine)(void*);
37
  void* arg;
38
};
39
40
6
static void* start_routine_wrapper(void* arg) {
41
6
  main_ctx_allowed = false;
42
6
  audio_ctx_allowed = true;
43
6
  struct start_routine_wrapper_data data =
44
6
      *(struct start_routine_wrapper_data*)arg;
45
6
  free(arg);
46
6
  return data.start_routine(data.arg);
47
6
}
48
49
int cras_thread_create_audio(pthread_t* thread,
50
                             const pthread_attr_t* attr,
51
                             void* (*start_routine)(void*),
52
6
                             void* arg) {
53
6
  struct start_routine_wrapper_data* data =
54
6
      calloc(sizeof(struct start_routine_wrapper_data), 1);
55
6
  data->start_routine = start_routine;
56
6
  data->arg = arg;
57
6
  int rc = pthread_create(thread, attr, start_routine_wrapper, data);
58
59
6
  if (rc != 0) {
60
0
    free(data);
61
0
    return rc;
62
0
  }
63
64
  // Block accessing audio_ctx on the main thread if the audio thread was
65
  // created successfully.
66
6
  audio_ctx_allowed = false;
67
6
  return 0;
68
6
}
69
70
0
void cras_thread_disarm_checks() {
71
0
  main_ctx_allowed = audio_ctx_allowed = true;
72
0
}