ThreadImpl.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #include "il2cpp-config.h"
  2. #if !IL2CPP_THREADS_STD && IL2CPP_THREADS_PTHREAD && !RUNTIME_TINY
  3. #include <limits>
  4. #include <unistd.h>
  5. #include <map>
  6. #include <pthread.h>
  7. #include <errno.h>
  8. #include <string.h>
  9. #if IL2CPP_TARGET_LINUX
  10. #include <sys/prctl.h>
  11. #include <sys/resource.h>
  12. #endif
  13. #include "ThreadImpl.h"
  14. #include "PosixHelpers.h"
  15. namespace il2cpp
  16. {
  17. namespace os
  18. {
  19. /// An Event that we never signal. This is used for sleeping threads in an alertable state. They
  20. /// simply wait on this object with the sleep timer as the timeout. This way we don't need a separate
  21. /// codepath for implementing sleep logic.
  22. static Event s_ThreadSleepObject;
  23. #define ASSERT_CALLED_ON_CURRENT_THREAD \
  24. IL2CPP_ASSERT(pthread_equal (pthread_self (), m_Handle) && "Must be called on current thread!");
  25. ThreadImpl::ThreadImpl()
  26. : m_Handle(0)
  27. , m_StartFunc(NULL)
  28. , m_StartArg(NULL)
  29. , m_CurrentWaitObject(NULL)
  30. , m_StackSize(IL2CPP_DEFAULT_STACK_SIZE)
  31. , m_ConditionSemaphore(1)
  32. {
  33. }
  34. ThreadImpl::~ThreadImpl()
  35. {
  36. }
  37. ErrorCode ThreadImpl::Run(Thread::StartFunc func, void* arg, int64_t affinityMask)
  38. {
  39. // Store state for run wrapper.
  40. m_StartFunc = func;
  41. m_StartArg = arg;
  42. // Initialize thread attributes.
  43. pthread_attr_t attr;
  44. int s = pthread_attr_init(&attr);
  45. if (s)
  46. return kErrorCodeGenFailure;
  47. #if defined(IL2CPP_ENABLE_PLATFORM_THREAD_AFFINTY)
  48. #if IL2CPP_THREAD_HAS_CPU_SET
  49. if (affinityMask != Thread::kThreadAffinityAll)
  50. {
  51. cpu_set_t cpuset;
  52. CPU_ZERO(&cpuset);
  53. for (int i = 0; i < 64; ++i)
  54. {
  55. if (affinityMask & (1 << i))
  56. CPU_SET(i, &cpuset);
  57. }
  58. pthread_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);
  59. }
  60. else
  61. {
  62. // set create default core affinity
  63. pthread_attr_setaffinity_np(&attr, 0, NULL);
  64. }
  65. #else
  66. pthread_attr_setaffinity_np(&attr, 0, NULL);
  67. #endif // IL2CPP_THREAD_HAS_CPU_SET
  68. #endif // defined(IL2CPP_ENABLE_PLATFORM_THREAD_AFFINTY)
  69. #if defined(IL2CPP_ENABLE_PLATFORM_THREAD_STACKSIZE)
  70. pthread_attr_setstacksize(&attr, m_StackSize);
  71. #endif
  72. // Create thread.
  73. pthread_t threadId;
  74. s = pthread_create(&threadId, &attr, &ThreadStartWrapper, this);
  75. if (s)
  76. return kErrorCodeGenFailure;
  77. // Destroy thread attributes.
  78. s = pthread_attr_destroy(&attr);
  79. if (s)
  80. return kErrorCodeGenFailure;
  81. // We're up and running.
  82. m_Handle = threadId;
  83. return kErrorCodeSuccess;
  84. }
  85. void* ThreadImpl::ThreadStartWrapper(void* arg)
  86. {
  87. ThreadImpl* thread = reinterpret_cast<ThreadImpl*>(arg);
  88. // Also set handle here. No matter which thread proceeds first,
  89. // we need to make sure the handle is set.
  90. thread->m_Handle = pthread_self();
  91. // Detach this thread since we will manage calling Join at the VM level
  92. // if necessary. Detaching it also prevents use from running out of thread
  93. // handles for background threads that are never joined.
  94. int returnValue = pthread_detach(thread->m_Handle);
  95. IL2CPP_ASSERT(returnValue == 0);
  96. (void)returnValue;
  97. // Run user code.
  98. thread->m_StartFunc(thread->m_StartArg);
  99. return 0;
  100. }
  101. uint64_t ThreadImpl::Id()
  102. {
  103. return posix::PosixThreadIdToThreadId(m_Handle);
  104. }
  105. void ThreadImpl::SetName(const char* name)
  106. {
  107. // Can only be set on current thread on OSX and Linux.
  108. if (pthread_self() != m_Handle)
  109. return;
  110. #if IL2CPP_TARGET_DARWIN
  111. pthread_setname_np(name);
  112. #elif IL2CPP_TARGET_LINUX || IL2CPP_TARGET_ANDROID || IL2CPP_ENABLE_PLATFORM_THREAD_RENAME
  113. if (pthread_setname_np(m_Handle, name) == ERANGE)
  114. {
  115. char buf[16]; // TASK_COMM_LEN=16
  116. strncpy(buf, name, sizeof(buf));
  117. buf[sizeof(buf) - 1] = '\0';
  118. pthread_setname_np(m_Handle, buf);
  119. }
  120. #endif
  121. }
  122. void ThreadImpl::SetStackSize(size_t newsize)
  123. {
  124. // if newsize is zero we use the per-platform default value for size of stack
  125. if (newsize == 0)
  126. {
  127. newsize = IL2CPP_DEFAULT_STACK_SIZE;
  128. }
  129. m_StackSize = newsize;
  130. }
  131. int ThreadImpl::GetMaxStackSize()
  132. {
  133. #if IL2CPP_TARGET_DARWIN || IL2CPP_TARGET_LINUX
  134. struct rlimit lim;
  135. /* If getrlimit fails, we don't enforce any limits. */
  136. if (getrlimit(RLIMIT_STACK, &lim))
  137. return INT_MAX;
  138. /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
  139. if (lim.rlim_max > (rlim_t)INT_MAX)
  140. return INT_MAX;
  141. return (int)lim.rlim_max;
  142. #else
  143. return INT_MAX;
  144. #endif
  145. }
  146. void ThreadImpl::SetPriority(ThreadPriority priority)
  147. {
  148. ////TODO
  149. }
  150. ThreadPriority ThreadImpl::GetPriority()
  151. {
  152. /// TODO
  153. return kThreadPriorityNormal;
  154. }
  155. void ThreadImpl::QueueUserAPC(Thread::APCFunc function, void* context)
  156. {
  157. IL2CPP_ASSERT(function != NULL);
  158. // Put on queue.
  159. {
  160. m_PendingAPCsMutex.Acquire();
  161. m_PendingAPCs.push_back(APCRequest(function, context));
  162. m_PendingAPCsMutex.Release();
  163. }
  164. // Interrupt an ongoing wait, only interrupt if we have an object waiting
  165. if (m_CurrentWaitObject.load())
  166. {
  167. m_ConditionSemaphore.Release(1);
  168. }
  169. }
  170. void ThreadImpl::CheckForUserAPCAndHandle()
  171. {
  172. ASSERT_CALLED_ON_CURRENT_THREAD;
  173. m_PendingAPCsMutex.Acquire();
  174. while (!m_PendingAPCs.empty())
  175. {
  176. APCRequest apcRequest = m_PendingAPCs.front();
  177. // Remove from list. Do before calling the function to make sure the list
  178. // is up to date in case the function throws.
  179. m_PendingAPCs.erase(m_PendingAPCs.begin());
  180. // Release mutex while we call the function so that we don't deadlock
  181. // if the function starts waiting on a thread that tries queuing an APC
  182. // on us.
  183. m_PendingAPCsMutex.Release();
  184. // Call function.
  185. apcRequest.callback(apcRequest.context);
  186. // Re-acquire mutex.
  187. m_PendingAPCsMutex.Acquire();
  188. }
  189. m_PendingAPCsMutex.Release();
  190. }
  191. void ThreadImpl::SetWaitObject(WaitObject* waitObject)
  192. {
  193. // Cannot set wait objects on threads other than the current thread.
  194. ASSERT_CALLED_ON_CURRENT_THREAD;
  195. // This is an unprotected write as write acccess is restricted to the
  196. // current thread.
  197. m_CurrentWaitObject = waitObject;
  198. }
  199. void ThreadImpl::Sleep(uint32_t milliseconds, bool interruptible)
  200. {
  201. s_ThreadSleepObject.Wait(milliseconds, interruptible);
  202. }
  203. uint64_t ThreadImpl::CurrentThreadId()
  204. {
  205. return posix::PosixThreadIdToThreadId(pthread_self());
  206. }
  207. ThreadImpl* ThreadImpl::GetCurrentThread()
  208. {
  209. return Thread::GetCurrentThread()->m_Thread;
  210. }
  211. ThreadImpl* ThreadImpl::CreateForCurrentThread()
  212. {
  213. ThreadImpl* thread = new ThreadImpl();
  214. thread->m_Handle = pthread_self();
  215. return thread;
  216. }
  217. bool ThreadImpl::YieldInternal()
  218. {
  219. return sched_yield() == 0;
  220. }
  221. #if IL2CPP_HAS_NATIVE_THREAD_CLEANUP
  222. static pthread_key_t s_CleanupKey;
  223. static Thread::ThreadCleanupFunc s_CleanupFunc;
  224. static void CleanupThreadIfCanceled(void* arg)
  225. {
  226. Thread::ThreadCleanupFunc cleanupFunc = s_CleanupFunc;
  227. if (cleanupFunc)
  228. cleanupFunc(arg);
  229. }
  230. void ThreadImpl::SetNativeThreadCleanup(Thread::ThreadCleanupFunc cleanupFunction)
  231. {
  232. if (cleanupFunction)
  233. {
  234. IL2CPP_ASSERT(!s_CleanupFunc);
  235. s_CleanupFunc = cleanupFunction;
  236. int result = pthread_key_create(&s_CleanupKey, &CleanupThreadIfCanceled);
  237. IL2CPP_ASSERT(!result);
  238. NO_UNUSED_WARNING(result);
  239. }
  240. else
  241. {
  242. IL2CPP_ASSERT(s_CleanupFunc);
  243. int result = pthread_key_delete(s_CleanupKey);
  244. IL2CPP_ASSERT(!result);
  245. NO_UNUSED_WARNING(result);
  246. s_CleanupFunc = NULL;
  247. }
  248. }
  249. void ThreadImpl::RegisterCurrentThreadForCleanup(void* arg)
  250. {
  251. IL2CPP_ASSERT(s_CleanupFunc);
  252. pthread_setspecific(s_CleanupKey, arg);
  253. }
  254. void ThreadImpl::UnregisterCurrentThreadForCleanup()
  255. {
  256. IL2CPP_ASSERT(s_CleanupFunc);
  257. void* data = pthread_getspecific(s_CleanupKey);
  258. if (data != NULL)
  259. pthread_setspecific(s_CleanupKey, NULL);
  260. }
  261. #endif
  262. }
  263. }
  264. #endif