VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/thread-posix.cpp@ 44025

Last change on this file since 44025 was 44025, checked in by vboxsync, 12 years ago

Put IN_RT_STATIC in the VBOXR3STATIC template so everyone have the right expectations regaring import/export declarations. Some := required in Runtime/Makefile.kmk to prevent define 'leaks' between targets during kBuild/footer.kmk.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 12.7 KB
Line 
1/* $Id: thread-posix.cpp 44025 2012-12-04 01:33:34Z vboxsync $ */
2/** @file
3 * IPRT - Threads, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#define LOG_GROUP RTLOGGROUP_THREAD
32#include <errno.h>
33#include <pthread.h>
34#include <signal.h>
35#if defined(RT_OS_LINUX)
36# include <unistd.h>
37# include <sys/syscall.h>
38#endif
39#if defined(RT_OS_SOLARIS)
40# include <sched.h>
41# include <sys/resource.h>
42#endif
43#if defined(RT_OS_DARWIN)
44# include <mach/thread_act.h>
45# include <mach/thread_info.h>
46# include <mach/host_info.h>
47# include <mach/mach_init.h>
48# include <mach/mach_host.h>
49#endif
50#if defined(RT_OS_DARWIN) /*|| defined(RT_OS_FREEBSD) - later */ \
51 || (defined(RT_OS_LINUX) && !defined(IN_RT_STATIC) /* static + dlsym = trouble */) \
52 || defined(IPRT_MAY_HAVE_PTHREAD_SET_NAME_NP)
53# define IPRT_MAY_HAVE_PTHREAD_SET_NAME_NP
54# include <dlfcn.h>
55#endif
56#if defined(RT_OS_HAIKU)
57# include <OS.h>
58#endif
59
60#include <iprt/thread.h>
61#include <iprt/log.h>
62#include <iprt/assert.h>
63#include <iprt/asm.h>
64#include <iprt/err.h>
65#include <iprt/string.h>
66#include "internal/thread.h"
67
68
69/*******************************************************************************
70* Defined Constants And Macros *
71*******************************************************************************/
72#ifndef IN_GUEST
73/** Includes RTThreadPoke. */
74# define RTTHREAD_POSIX_WITH_POKE
75#endif
76
77
78/*******************************************************************************
79* Global Variables *
80*******************************************************************************/
81/** The pthread key in which we store the pointer to our own PRTTHREAD structure. */
82static pthread_key_t g_SelfKey;
83#ifdef RTTHREAD_POSIX_WITH_POKE
84/** The signal we use for poking threads.
85 * This is set to -1 if no available signal was found. */
86static int g_iSigPokeThread = -1;
87#endif
88
89#ifdef IPRT_MAY_HAVE_PTHREAD_SET_NAME_NP
90# if defined(RT_OS_DARWIN)
91/**
92 * The Mac OS X (10.6 and later) variant of pthread_setname_np.
93 *
94 * @returns errno.h
95 * @param pszName The new thread name.
96 */
97typedef int (*PFNPTHREADSETNAME)(const char *pszName);
98# else
99/**
100 * The variant of pthread_setname_np most other unix-like systems implement.
101 *
102 * @returns errno.h
103 * @param hThread The thread.
104 * @param pszName The new thread name.
105 */
106typedef int (*PFNPTHREADSETNAME)(pthread_t hThread, const char *pszName);
107# endif
108
109/** Pointer to pthread_setname_np if found. */
110static PFNPTHREADSETNAME g_pfnThreadSetName = NULL;
111#endif /* IPRT_MAY_HAVE_PTHREAD_SET_NAME_NP */
112
113
114/*******************************************************************************
115* Internal Functions *
116*******************************************************************************/
117static void *rtThreadNativeMain(void *pvArgs);
118static void rtThreadKeyDestruct(void *pvValue);
119static void rtThreadPosixPokeSignal(int iSignal);
120
121
122DECLHIDDEN(int) rtThreadNativeInit(void)
123{
124 /*
125 * Allocate the TLS (key in posix terms) where we store the pointer to
126 * a threads RTTHREADINT structure.
127 */
128 int rc = pthread_key_create(&g_SelfKey, rtThreadKeyDestruct);
129 if (rc)
130 return VERR_NO_TLS_FOR_SELF;
131
132#ifdef RTTHREAD_POSIX_WITH_POKE
133 /*
134 * Try register the dummy signal handler for RTThreadPoke.
135 * Avoid SIGRTMIN thru SIGRTMIN+2 because of LinuxThreads.
136 */
137 static const int s_aiSigCandidates[] =
138 {
139# ifdef SIGRTMAX
140 SIGRTMAX-3,
141 SIGRTMAX-2,
142 SIGRTMAX-1,
143# endif
144# ifndef RT_OS_SOLARIS
145 SIGUSR2,
146# endif
147 SIGWINCH
148 };
149
150 g_iSigPokeThread = -1;
151 for (unsigned iSig = 0; iSig < RT_ELEMENTS(s_aiSigCandidates); iSig++)
152 {
153 struct sigaction SigActOld;
154 if (!sigaction(s_aiSigCandidates[iSig], NULL, &SigActOld))
155 {
156 if ( SigActOld.sa_handler == SIG_DFL
157 || SigActOld.sa_handler == rtThreadPosixPokeSignal)
158 {
159 struct sigaction SigAct;
160 RT_ZERO(SigAct);
161 SigAct.sa_handler = rtThreadPosixPokeSignal;
162 SigAct.sa_flags = 0;
163 sigfillset(&SigAct.sa_mask);
164
165 /* ASSUMES no sigaction race... (lazy bird) */
166 if (!sigaction(s_aiSigCandidates[iSig], &SigAct, NULL))
167 {
168 g_iSigPokeThread = s_aiSigCandidates[iSig];
169 break;
170 }
171 AssertMsgFailed(("rc=%Rrc errno=%d\n", RTErrConvertFromErrno(errno), errno));
172 }
173 }
174 else
175 AssertMsgFailed(("rc=%Rrc errno=%d\n", RTErrConvertFromErrno(errno), errno));
176 }
177#endif /* RTTHREAD_POSIX_WITH_POKE */
178
179#ifdef IPRT_MAY_HAVE_PTHREAD_SET_NAME_NP
180 if (RT_SUCCESS(rc))
181 g_pfnThreadSetName = (PFNPTHREADSETNAME)(uintptr_t)dlsym(RTLD_DEFAULT, "pthread_setname_np");
182#endif
183 return rc;
184}
185
186
187/**
188 * Destructor called when a thread terminates.
189 * @param pvValue The key value. PRTTHREAD in our case.
190 */
191static void rtThreadKeyDestruct(void *pvValue)
192{
193 /*
194 * Deal with alien threads.
195 */
196 PRTTHREADINT pThread = (PRTTHREADINT)pvValue;
197 if (pThread->fIntFlags & RTTHREADINT_FLAGS_ALIEN)
198 {
199 pthread_setspecific(g_SelfKey, pThread);
200 rtThreadTerminate(pThread, 0);
201 pthread_setspecific(g_SelfKey, NULL);
202 }
203}
204
205
206#ifdef RTTHREAD_POSIX_WITH_POKE
207/**
208 * Dummy signal handler for the poke signal.
209 *
210 * @param iSignal The signal number.
211 */
212static void rtThreadPosixPokeSignal(int iSignal)
213{
214 Assert(iSignal == g_iSigPokeThread);
215 NOREF(iSignal);
216}
217#endif
218
219
220/**
221 * Adopts a thread, this is called immediately after allocating the
222 * thread structure.
223 *
224 * @param pThread Pointer to the thread structure.
225 */
226DECLHIDDEN(int) rtThreadNativeAdopt(PRTTHREADINT pThread)
227{
228 /*
229 * Block SIGALRM - required for timer-posix.cpp.
230 * This is done to limit harm done by OSes which doesn't do special SIGALRM scheduling.
231 * It will not help much if someone creates threads directly using pthread_create. :/
232 */
233 sigset_t SigSet;
234 sigemptyset(&SigSet);
235 sigaddset(&SigSet, SIGALRM);
236 sigprocmask(SIG_BLOCK, &SigSet, NULL);
237#ifdef RTTHREAD_POSIX_WITH_POKE
238 if (g_iSigPokeThread != -1)
239 siginterrupt(g_iSigPokeThread, 1);
240#endif
241
242 int rc = pthread_setspecific(g_SelfKey, pThread);
243 if (!rc)
244 return VINF_SUCCESS;
245 return VERR_FAILED_TO_SET_SELF_TLS;
246}
247
248
249DECLHIDDEN(void) rtThreadNativeDestroy(PRTTHREADINT pThread)
250{
251 if (pThread == (PRTTHREADINT)pthread_getspecific(g_SelfKey))
252 pthread_setspecific(g_SelfKey, NULL);
253}
254
255
256/**
257 * Wrapper which unpacks the params and calls thread function.
258 */
259static void *rtThreadNativeMain(void *pvArgs)
260{
261 PRTTHREADINT pThread = (PRTTHREADINT)pvArgs;
262 pthread_t Self = pthread_self();
263 Assert((uintptr_t)Self == (RTNATIVETHREAD)Self && (uintptr_t)Self != NIL_RTNATIVETHREAD);
264
265#if defined(RT_OS_LINUX)
266 /*
267 * Set the TID.
268 */
269 pThread->tid = syscall(__NR_gettid);
270 ASMMemoryFence();
271#endif
272
273 /*
274 * Block SIGALRM - required for timer-posix.cpp.
275 * This is done to limit harm done by OSes which doesn't do special SIGALRM scheduling.
276 * It will not help much if someone creates threads directly using pthread_create. :/
277 */
278 sigset_t SigSet;
279 sigemptyset(&SigSet);
280 sigaddset(&SigSet, SIGALRM);
281 sigprocmask(SIG_BLOCK, &SigSet, NULL);
282#ifdef RTTHREAD_POSIX_WITH_POKE
283 if (g_iSigPokeThread != -1)
284 siginterrupt(g_iSigPokeThread, 1);
285#endif
286
287 /*
288 * Set the TLS entry and, if possible, the thread name.
289 */
290 int rc = pthread_setspecific(g_SelfKey, pThread);
291 AssertReleaseMsg(!rc, ("failed to set self TLS. rc=%d thread '%s'\n", rc, pThread->szName));
292
293#ifdef IPRT_MAY_HAVE_PTHREAD_SET_NAME_NP
294 if (g_pfnThreadSetName)
295# ifdef RT_OS_DARWIN
296 g_pfnThreadSetName(pThread->szName);
297# else
298 g_pfnThreadSetName(Self, pThread->szName);
299# endif
300#endif
301
302 /*
303 * Call common main.
304 */
305 rc = rtThreadMain(pThread, (uintptr_t)Self, &pThread->szName[0]);
306
307 pthread_setspecific(g_SelfKey, NULL);
308 pthread_exit((void *)(intptr_t)rc);
309 return (void *)(intptr_t)rc;
310}
311
312
313DECLHIDDEN(int) rtThreadNativeCreate(PRTTHREADINT pThread, PRTNATIVETHREAD pNativeThread)
314{
315 /*
316 * Set the default stack size.
317 */
318 if (!pThread->cbStack)
319 pThread->cbStack = 512*1024;
320
321#ifdef RT_OS_LINUX
322 pThread->tid = -1;
323#endif
324
325 /*
326 * Setup thread attributes.
327 */
328 pthread_attr_t ThreadAttr;
329 int rc = pthread_attr_init(&ThreadAttr);
330 if (!rc)
331 {
332 rc = pthread_attr_setdetachstate(&ThreadAttr, PTHREAD_CREATE_DETACHED);
333 if (!rc)
334 {
335 rc = pthread_attr_setstacksize(&ThreadAttr, pThread->cbStack);
336 if (!rc)
337 {
338 /*
339 * Create the thread.
340 */
341 pthread_t ThreadId;
342 rc = pthread_create(&ThreadId, &ThreadAttr, rtThreadNativeMain, pThread);
343 if (!rc)
344 {
345 *pNativeThread = (uintptr_t)ThreadId;
346 return VINF_SUCCESS;
347 }
348 }
349 }
350 pthread_attr_destroy(&ThreadAttr);
351 }
352 return RTErrConvertFromErrno(rc);
353}
354
355
356RTDECL(RTTHREAD) RTThreadSelf(void)
357{
358 PRTTHREADINT pThread = (PRTTHREADINT)pthread_getspecific(g_SelfKey);
359 /** @todo import alien threads? */
360 return pThread;
361}
362
363
364#ifdef RTTHREAD_POSIX_WITH_POKE
365RTDECL(int) RTThreadPoke(RTTHREAD hThread)
366{
367 AssertReturn(hThread != RTThreadSelf(), VERR_INVALID_PARAMETER);
368 PRTTHREADINT pThread = rtThreadGet(hThread);
369 AssertReturn(pThread, VERR_INVALID_HANDLE);
370
371 int rc;
372 if (g_iSigPokeThread != -1)
373 {
374 rc = pthread_kill((pthread_t)(uintptr_t)pThread->Core.Key, g_iSigPokeThread);
375 rc = RTErrConvertFromErrno(rc);
376 }
377 else
378 rc = VERR_NOT_SUPPORTED;
379
380 rtThreadRelease(pThread);
381 return rc;
382}
383#endif
384
385/** @todo move this into platform specific files. */
386RTR3DECL(int) RTThreadGetExecutionTimeMilli(uint64_t *pKernelTime, uint64_t *pUserTime)
387{
388#if defined(RT_OS_SOLARIS)
389 struct rusage ts;
390 int rc = getrusage(RUSAGE_LWP, &ts);
391 if (rc)
392 return RTErrConvertFromErrno(rc);
393
394 *pKernelTime = ts.ru_stime.tv_sec * 1000 + ts.ru_stime.tv_usec / 1000;
395 *pUserTime = ts.ru_utime.tv_sec * 1000 + ts.ru_utime.tv_usec / 1000;
396 return VINF_SUCCESS;
397
398#elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
399 /* on Linux, getrusage(RUSAGE_THREAD, ...) is available since 2.6.26 */
400 struct timespec ts;
401 int rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
402 if (rc)
403 return RTErrConvertFromErrno(rc);
404
405 *pKernelTime = 0;
406 *pUserTime = (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
407 return VINF_SUCCESS;
408
409#elif defined(RT_OS_DARWIN)
410 thread_basic_info ThreadInfo;
411 mach_msg_type_number_t Count = THREAD_BASIC_INFO_COUNT;
412 kern_return_t krc = thread_info(mach_thread_self(), THREAD_BASIC_INFO, (thread_info_t)&ThreadInfo, &Count);
413 AssertReturn(krc == KERN_SUCCESS, RTErrConvertFromDarwinKern(krc));
414
415 *pKernelTime = ThreadInfo.system_time.seconds * 1000 + ThreadInfo.system_time.microseconds / 1000;
416 *pUserTime = ThreadInfo.user_time.seconds * 1000 + ThreadInfo.user_time.microseconds / 1000;
417
418 return VINF_SUCCESS;
419#elif defined(RT_OS_HAIKU)
420 thread_info ThreadInfo;
421 status_t status = get_thread_info(find_thread(NULL), &ThreadInfo);
422 AssertReturn(status == B_OK, RTErrConvertFromErrno(status));
423
424 *pKernelTime = ThreadInfo.kernel_time / 1000;
425 *pUserTime = ThreadInfo.user_time / 1000;
426
427 return VINF_SUCCESS;
428#else
429 return VERR_NOT_IMPLEMENTED;
430#endif
431}
432
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette