VirtualBox

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

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

IPRT: Name threads on linux when supported.

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

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