VirtualBox

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

Last change on this file since 43437 was 43363, checked in by vboxsync, 13 years ago

Haiku Additions.

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