summaryrefslogtreecommitdiffstats
path: root/xbmc/utils/CryptThreading.cpp
blob: 3484635b49274ac53df0b99ed79ebe5621a5d36f (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "CryptThreading.h"
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)

#include "threads/Thread.h"
#include "utils/log.h"

#include <atomic>

namespace
{

CCriticalSection* getlock(int index)
{
  return g_cryptThreadingInitializer.GetLock(index);
}

void lock_callback(int mode, int type, const char* file, int line)
{
  if (mode & CRYPTO_LOCK)
    getlock(type)->lock();
  else
    getlock(type)->unlock();
}

unsigned long GetCryptThreadId()
{
  static std::atomic<unsigned long> tidSequence{0};
  static thread_local unsigned long tidTl{0};

  if (tidTl == 0)
    tidTl = ++tidSequence;
  return tidTl;
}

void thread_id(CRYPTO_THREADID* tid)
{
  // C-style cast required due to vastly differing native ID return types
  CRYPTO_THREADID_set_numeric(tid, GetCryptThreadId());
}

}

CryptThreadingInitializer::CryptThreadingInitializer()
{
  // OpenSSL < 1.1 needs integration code to support multi-threading
  // This is absolutely required for libcurl if it uses the OpenSSL backend
  m_locks.resize(CRYPTO_num_locks());
  CRYPTO_THREADID_set_callback(thread_id);
  CRYPTO_set_locking_callback(lock_callback);
}

CryptThreadingInitializer::~CryptThreadingInitializer()
{
  CSingleLock l(m_locksLock);
  CRYPTO_set_locking_callback(nullptr);
  m_locks.clear();
}

CCriticalSection* CryptThreadingInitializer::GetLock(int index)
{
  CSingleLock l(m_locksLock);
  auto& curlock = m_locks[index];
  if (!curlock)
  {
    curlock.reset(new CCriticalSection());
  }

  return curlock.get();
}

unsigned long CryptThreadingInitializer::GetCurrentCryptThreadId()
{
  return GetCryptThreadId();
}

#endif