Debian Codegraph @

Xpjproject/pjlib/src/pj/os_core_unix.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3 * Copyright (C) 2003-2008 Benny Prijono <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 /*
20 * Contributors:
21 * - Thanks for Zetron, Inc. (Phil Torre, [email protected]) for donating
22 * the RTEMS port.
23 */
24 #ifndef _GNU_SOURCE
25 # define _GNU_SOURCE
26 #endif
27 #include <pj/os.h>
28 #include <pj/assert.h>
29 #include <pj/pool.h>
30 #include <pj/log.h>
31 #include <pj/rand.h>
32 #include <pj/string.h>
33 #include <pj/guid.h>
34 #include <pj/except.h>
35 #include <pj/errno.h>
36
37 #if defined(PJ_HAS_SEMAPHORE_H) && PJ_HAS_SEMAPHORE_H != 0
38 # include <semaphore.h>
39 #endif
40
41 #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
42 # include <dispatch/dispatch.h>
43 #endif
44
45 #include <unistd.h> // getpid()
46 #include <errno.h> // errno
47
48 #if PJ_HAS_THREADS
49 # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
50 && !defined(__STDC_NO_ATOMICS__) \
51 && (!defined(__GNUC__) || defined(__clang__) \
52 || __GNUC__ > 4 \
53 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9))
54 # define HAS_STD_ATOMICS 1
55 # include <stdatomic.h>
56 # else
57 # define EMULATE_ATOMICS 1
58 # endif
59 #endif
60
61 #include <pthread.h>
62 #if defined(PJ_HAS_PTHREAD_NP_H) && PJ_HAS_PTHREAD_NP_H != 0
63 # include <pthread_np.h>
64 #endif
65 #include <pj/config.h>
66
67 #if defined(PJ_HAS_FCNTL_H) && PJ_HAS_FCNTL_H != 0
68 # include <fcntl.h>
69 #endif
70
71 #define THIS_FILE "os_core_unix.c"
72
73 #define SIGNATURE1 0xDEAFBEEF
74 #define SIGNATURE2 0xDEADC0DE
75
76 #if defined(PJ_ANDROID) && PJ_ANDROID != 0
77
78 #include <jni.h>
79
80 JavaVM *pj_jni_jvm = NULL;
81
82 #if defined(PJ_JNI_HAS_JNI_ONLOAD) && PJ_JNI_HAS_JNI_ONLOAD != 0
83
84 JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved)
85 {
86 pj_jni_jvm = vm;
87
88 return JNI_VERSION_1_4;
89 }
90
91 #endif /* PJ_JNI_HAS_JNI_ONLOAD */
92
93 #endif /* PJ_ANDROID */
94
95 struct pj_thread_t
96 {
97 char obj_name[PJ_MAX_OBJ_NAME];
98 pthread_t thread;
99 pj_thread_proc *proc;
100 void *arg;
101 pj_uint32_t signature1;
102 pj_uint32_t signature2;
103
104 pj_mutex_t *suspended_mutex;
105
106 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
107 pj_uint32_t stk_size;
108 pj_uint32_t stk_max_usage;
109 char *stk_start;
110 const char *caller_file;
111 int caller_line;
112 #endif
113 };
114
115 struct pj_atomic_t
116 {
117 #if HAS_STD_ATOMICS
118 _Atomic pj_atomic_value_t value;
119 #elif EMULATE_ATOMICS
120 pj_mutex_t *mutex;
121 pj_atomic_value_t value;
122 #else
123 pj_atomic_value_t value;
124 #endif
125 } PJ_ALIGN_DATA_SUFFIX(8);
126
127 struct pj_mutex_t
128 {
129 pthread_mutex_t mutex;
130 char obj_name[PJ_MAX_OBJ_NAME];
131 #if PJ_DEBUG
132 int nesting_level;
133 pj_thread_t *owner;
134 char owner_name[PJ_MAX_OBJ_NAME];
135 #endif
136 };
137
138 #if defined(PJ_HAS_SEMAPHORE) && PJ_HAS_SEMAPHORE != 0
139 struct pj_sem_t
140 {
141 #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
142 dispatch_semaphore_t sem;
143 #else
144 sem_t *sem;
145 #endif
146 char obj_name[PJ_MAX_OBJ_NAME];
147 };
148 #endif /* PJ_HAS_SEMAPHORE */
149
150 #if defined(PJ_HAS_EVENT_OBJ) && PJ_HAS_EVENT_OBJ != 0
151 struct pj_event_t
152 {
153 enum event_state {
154 EV_STATE_OFF,
155 EV_STATE_SET,
156 EV_STATE_PULSED
157 } state;
158
159 pj_mutex_t mutex;
160 pthread_cond_t cond;
161
162 pj_bool_t auto_reset;
163 int threads_waiting;
164 int threads_to_release;
165 };
166 #endif /* PJ_HAS_EVENT_OBJ */
167
168 struct pj_barrier_t {
169 #if defined(_POSIX_BARRIERS) && _POSIX_BARRIERS >= 200112L
170 /* pthread_barrier is supported. */
171 pthread_barrier_t barrier;
172 #else
173 /* pthread_barrier is not supported. */
174 pj_mutex_t mutex;
175 pthread_cond_t cond;
176 unsigned count;
177 unsigned trip_count;
178 #endif
179 };
180
181 /*
182 * Flag and reference counter for PJLIB instance.
183 */
184 static int initialized;
185
186 #if PJ_HAS_THREADS
187 static pj_thread_desc main_thread_desc;
188 static long thread_tls_id;
189 static pj_mutex_t critical_section;
190 #else
191 # define MAX_THREADS 32
192 static int tls_flag[MAX_THREADS];
193 static void *tls[MAX_THREADS];
194 #endif
195
196 static unsigned atexit_count;
197 static void (*atexit_func[32])(void);
198
199 static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name, int type);
200 /*
201 * pj_init(void).
202 * Init PJLIB!
203 */
204 PJ_DEF(pj_status_t) pj_init(void)
205 {
206 char dummy_guid[PJ_GUID_MAX_LENGTH];
207 pj_str_t guid;
208 pj_status_t rc;
209
210 /* Check if PJLIB have been initialized */
211 if (initialized) {
212 ++initialized;
213 return PJ_SUCCESS;
214 }
215
216 /* Init logging */
217 pj_log_init();
218
219 #if PJ_HAS_THREADS
220 /* Init this thread's TLS. */
221 if ((rc=pj_thread_init()) != 0) {
222 return rc;
223 }
224
225 /* Critical section. */
226 if ((rc=init_mutex(&critical_section, "critsec", PJ_MUTEX_RECURSE)) != 0)
227 return rc;
228
229 #endif
230
231 /* Initialize exception ID for the pool.
232 * Must do so after critical section is configured.
233 */
234 rc = pj_exception_id_alloc("PJLIB/No memory", &PJ_NO_MEMORY_EXCEPTION);
235 if (rc != PJ_SUCCESS)
236 return rc;
237
238 /* Init random seed. */
239 /* Or probably not. Let application in charge of this */
240 /* pj_srand( clock() ); */
241
242 /* Startup GUID. */
243 guid.ptr = dummy_guid;
244 pj_generate_unique_string( &guid );
245
246 /* Startup timestamp */
247 #if defined(PJ_HAS_HIGH_RES_TIMER) && PJ_HAS_HIGH_RES_TIMER != 0
248 {
249 pj_timestamp dummy_ts;
250 if ((rc=pj_get_timestamp(&dummy_ts)) != 0) {
251 return rc;
252 }
253 }
254 #endif
255
256 /* Flag PJLIB as initialized */
257 ++initialized;
258 pj_assert(initialized == 1);
259
260 PJ_LOG(4,(THIS_FILE, "pjlib %s for POSIX initialized",
261 PJ_VERSION));
262
263 return PJ_SUCCESS;
264 }
265
266 /*
267 * pj_atexit()
268 */
269 PJ_DEF(pj_status_t) pj_atexit(void (*func)(void))
270 {
271 if (atexit_count >= PJ_ARRAY_SIZE(atexit_func))
272 return PJ_ETOOMANY;
273
274 atexit_func[atexit_count++] = func;
275 return PJ_SUCCESS;
276 }
277
278 /*
279 * pj_shutdown(void)
280 */
281 PJ_DEF(void) pj_shutdown()
282 {
283 int i;
284
285 /* Only perform shutdown operation when 'initialized' reaches zero */
286 pj_assert(initialized > 0);
287 if (--initialized != 0)
288 return;
289
290 /* Call atexit() functions */
291 for (i=atexit_count-1; i>=0; --i) {
292 (*atexit_func[i])();
293 }
294 atexit_count = 0;
295
296 /* Free exception ID */
297 if (PJ_NO_MEMORY_EXCEPTION != -1) {
298 pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION);
299 PJ_NO_MEMORY_EXCEPTION = -1;
300 }
301
302 #if PJ_HAS_THREADS
303 /* Destroy PJLIB critical section */
304 pj_mutex_destroy(&critical_section);
305
306 /* Free PJLIB TLS */
307 if (thread_tls_id != -1) {
308 pj_thread_local_free(thread_tls_id);
309 thread_tls_id = -1;
310 }
311
312 /* Ticket #1132: Assertion when (re)starting PJLIB on different thread */
313 pj_bzero(main_thread_desc, sizeof(pj_thread_desc));
314 #endif
315
316 /* Clear static variables */
317 pj_errno_clear_handlers();
318 }
319
320
321 /*
322 * pj_getpid(void)
323 */
324 PJ_DEF(pj_uint32_t) pj_getpid(void)
325 {
326 PJ_CHECK_STACK();
327 return getpid();
328 }
329
330 /*
331 * Check if this thread has been registered to PJLIB.
332 */
333 PJ_DEF(pj_bool_t) pj_thread_is_registered(void)
334 {
335 #if PJ_HAS_THREADS
336 return pj_thread_local_get(thread_tls_id) != 0;
337 #else
338 pj_assert("pj_thread_is_registered() called in non-threading mode!");
339 return PJ_TRUE;
340 #endif
341 }
342
343
344 /* Thread priority utils for Android (via JNI as NDK does not provide it).
345 * Set priority is probably not enough because it does not change the thread
346 * group in scheduler.
347 * Temporary solution is to call the Java API to set the thread priority.
348 * A cool solution would be to port (if possible) the code from the
349 * android os regarding set_sched groups.
350 */
351 #if defined(PJ_ANDROID) && PJ_ANDROID != 0
352
353 #include <jni.h>
354 #include <sys/resource.h>
355 #include <sys/system_properties.h>
356
357 /* If you disable PJ_JNI_HAS_JNI_ONLOAD, set the JVM using this function. */
358 PJ_DEF(void) pj_jni_set_jvm(void *jvm)
359 {
360 pj_jni_jvm = (JavaVM *)jvm;
361 }
362
363 PJ_DEF(pj_bool_t) pj_jni_attach_jvm(void **jni_env)
364 {
365 if (!pj_jni_jvm)
366 return PJ_FALSE;
367
368 if ((*pj_jni_jvm)->GetEnv(pj_jni_jvm, jni_env, JNI_VERSION_1_4) < 0) {
369 if ((*pj_jni_jvm)->AttachCurrentThread(pj_jni_jvm,
370 (JNIEnv **)jni_env, NULL) < 0)
371 {
372 jni_env = NULL;
373 return PJ_FALSE;
374 }
375 return PJ_TRUE;
376 }
377
378 return PJ_FALSE;
379 }
380
381 PJ_DEF(void) pj_jni_detach_jvm(pj_bool_t attached)
382 {
383 if (!pj_jni_jvm) return;
384
385 if (attached)
386 (*pj_jni_jvm)->DetachCurrentThread(pj_jni_jvm);
387 }
388
389
390 static pj_status_t set_android_thread_priority(int priority)
391 {
392 jclass process_class;
393 jmethodID set_prio_method;
394 jthrowable exc;
395 pj_status_t result = PJ_SUCCESS;
396 JNIEnv *jni_env = 0;
397 pj_bool_t attached = pj_jni_attach_jvm((void **)&jni_env);
398
399 if (!jni_env) return PJ_EINVALIDOP;
400
401 /* Get pointer to the java class */
402 process_class = (jclass)(*jni_env)->NewGlobalRef(jni_env,
403 (*jni_env)->FindClass(jni_env, "android/os/Process"));
404 if (process_class == 0) {
405 PJ_LOG(5, (THIS_FILE, "Unable to find class android.os.Process"));
406 result = PJ_EIGNORED;
407 goto on_return;
408 }
409
410 /* Get the id of set thread priority function */
411 set_prio_method = (*jni_env)->GetStaticMethodID(jni_env, process_class,
412 "setThreadPriority",
413 "(I)V");
414 if (set_prio_method == 0) {
415 PJ_LOG(5, (THIS_FILE, "Unable to find setThreadPriority() method"));
416 result = PJ_EIGNORED;
417 goto on_return;
418 }
419
420 /* Set the thread priority */
421 (*jni_env)->CallStaticVoidMethod(jni_env, process_class, set_prio_method,
422 priority);
423 exc = (*jni_env)->ExceptionOccurred(jni_env);
424 if (exc) {
425 (*jni_env)->ExceptionDescribe(jni_env);
426 (*jni_env)->ExceptionClear(jni_env);
427 PJ_LOG(4, (THIS_FILE, "Failure in setting thread priority using "
428 "Java API, fallback to setpriority()"));
429 setpriority(PRIO_PROCESS, 0, priority);
430 } else {
431 PJ_LOG(5, (THIS_FILE, "Setting thread priority to %d successful",
432 priority));
433 }
434
435 on_return:
436 pj_jni_detach_jvm(attached);
437 return result;
438 }
439
440 #endif
441
442
443 /*
444 * Get thread priority value for the thread.
445 */
446 PJ_DEF(int) pj_thread_get_prio(pj_thread_t *thread)
447 {
448 #if PJ_HAS_THREADS
449 struct sched_param param;
450 int policy;
451 int rc;
452
453 rc = pthread_getschedparam (thread->thread, &policy, &param);
454 if (rc != 0)
455 return -1;
456
457 return param.sched_priority;
458 #else
459 PJ_UNUSED_ARG(thread);
460 return 1;
461 #endif
462 }
463
464 #if !defined(PJ_ANDROID) || PJ_ANDROID == 0
465 static pj_status_t set_prio(pj_thread_t *thread, int prio,
466 pj_bool_t max_policy)
467 {
468 int policy;
469 int rc;
470 struct sched_param param;
471
472 if (max_policy) {
473 policy = SCHED_RR;
474 } else {
475 rc = pthread_getschedparam (thread->thread, &policy, &param);
476 if (rc != 0)
477 return PJ_RETURN_OS_ERROR(rc);
478 }
479 param.sched_priority = prio;
480 rc = pthread_setschedparam(thread->thread, policy, &param);
481 if (rc != 0)
482 return PJ_RETURN_OS_ERROR(rc);
483
484 return PJ_SUCCESS;
485 }
486 #endif /* !PJ_ANDROID */
487
488 /*
489 * Set the thread priority.
490 */
491 PJ_DEF(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio)
492 {
493 #if PJ_HAS_THREADS
494
495 #if defined(PJ_ANDROID) && PJ_ANDROID != 0
496
497 PJ_ASSERT_RETURN(thread==NULL || thread==pj_thread_this(), PJ_EINVAL);
498 return set_android_thread_priority(prio);
499
500 # else
501 pj_status_t status = PJ_EUNKNOWN;
502
503 if (prio > 0)
504 status = set_prio(thread, prio, PJ_TRUE);
505
506 if (status != PJ_SUCCESS)
507 status = set_prio(thread, prio, PJ_FALSE);
508
509 return status;
510 # endif /* PJ_ANDROID */
511
512 #else
513 PJ_UNUSED_ARG(thread);
514 PJ_UNUSED_ARG(prio);
515 pj_assert("pj_thread_set_prio() called in non-threading mode!");
516 return 1;
517 #endif
518 }
519
520
521 /*
522 * Get the lowest priority value available on this system.
523 */
524 PJ_DEF(int) pj_thread_get_prio_min(pj_thread_t *thread)
525 {
526 struct sched_param param;
527 int policy;
528 int rc;
529
530 rc = pthread_getschedparam(thread->thread, &policy, &param);
531 if (rc != 0)
532 return -1;
533
534 #if defined(_POSIX_PRIORITY_SCHEDULING)
535 return sched_get_priority_min(policy);
536 #elif defined __OpenBSD__
537 /* Thread prio min/max are declared in OpenBSD private hdr */
538 return 0;
539 #else
540 pj_assert("pj_thread_get_prio_min() not supported!");
541 return 0;
542 #endif
543 }
544
545
546 static int get_prio_max(pj_thread_t *thread)
547 {
548 int ori_policy, policy;
549 int prio;
550 int rc;
551 struct sched_param ori_param, param;
552
553 rc = pthread_getschedparam (thread->thread, &ori_policy, &ori_param);
554 if (rc != 0)
555 return -1;
556
557 policy = SCHED_RR;
558 prio = sched_get_priority_max(policy);
559
560 /* Make sure the priority is usable. */
561 param.sched_priority = prio;
562
563 rc = pthread_setschedparam(thread->thread, policy, &param);
564 if (rc != 0)
565 return sched_get_priority_max(ori_policy);
566
567 /* Revert the original policy/param. */
568 rc = pthread_setschedparam(thread->thread, ori_policy, &ori_param);
569 return prio;
570 }
571
572
573 /*
574 * Get the highest priority value available on this system.
575 */
576 PJ_DEF(int) pj_thread_get_prio_max(pj_thread_t *thread)
577 {
578 #if defined(_POSIX_PRIORITY_SCHEDULING)
579 return get_prio_max(thread);
580 #elif defined __OpenBSD__
581 /* Thread prio min/max are declared in OpenBSD private hdr */
582 return 31;
583 #else
584 pj_assert("pj_thread_get_prio_max() not supported!");
585 return 0;
586 #endif
587 }
588
589
590 /*
591 * Get native thread handle
592 */
593 PJ_DEF(void*) pj_thread_get_os_handle(pj_thread_t *thread)
594 {
595 PJ_ASSERT_RETURN(thread, NULL);
596
597 #if PJ_HAS_THREADS
598 return &thread->thread;
599 #else
600 pj_assert("pj_thread_is_registered() called in non-threading mode!");
601 return NULL;
602 #endif
603 }
604
605 /*
606 * pj_thread_register(..)
607 */
608 PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name,
609 pj_thread_desc desc,
610 pj_thread_t **ptr_thread)
611 {
612 #if PJ_HAS_THREADS
613 char stack_ptr;
614 pj_status_t rc;
615 pj_thread_t *thread = (pj_thread_t *)desc;
616 pj_str_t thread_name = pj_str((char*)cstr_thread_name);
617
618 /* Size sanity check. */
619 if (sizeof(pj_thread_desc) < sizeof(pj_thread_t)) {
620 pj_assert(!"Not enough pj_thread_desc size!");
621 return PJ_EBUG;
622 }
623
624 /* Warn if this thread has been registered before */
625 if (pj_thread_local_get (thread_tls_id) != 0) {
626 // 2006-02-26 bennylp:
627 // This wouldn't work in all cases!.
628 // If thread is created by external module (e.g. sound thread),
629 // thread may be reused while the pool used for the thread descriptor
630 // has been deleted by application.
631 //*thread_ptr = (pj_thread_t*)pj_thread_local_get (thread_tls_id);
632 //return PJ_SUCCESS;
633 PJ_LOG(4,(THIS_FILE, "Info: possibly re-registering existing "
634 "thread"));
635 }
636
637 /* On the other hand, also warn if the thread descriptor buffer seem to
638 * have been used to register other threads.
639 */
640 pj_assert(thread->signature1 != SIGNATURE1 ||
641 thread->signature2 != SIGNATURE2 ||
642 (thread->thread == pthread_self()));
643
644 /* Initialize and set the thread entry. */
645 pj_bzero(desc, sizeof(struct pj_thread_t));
646 thread->thread = pthread_self();
647 thread->signature1 = SIGNATURE1;
648 thread->signature2 = SIGNATURE2;
649
650 if(cstr_thread_name && pj_strlen(&thread_name) < sizeof(thread->obj_name)-1)
651 pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name),
652 cstr_thread_name, thread->thread);
653 else
654 pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name),
655 "thr%p", (void*)thread->thread);
656
657 rc = pj_thread_local_set(thread_tls_id, thread);
658 if (rc != PJ_SUCCESS) {
659 pj_bzero(desc, sizeof(struct pj_thread_t));
660 return rc;
661 }
662
663 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
664 thread->stk_start = &stack_ptr;
665 thread->stk_size = 0xFFFFFFFFUL;
666 thread->stk_max_usage = 0;
667 #else
668 PJ_UNUSED_ARG(stack_ptr);
669 #endif
670
671 *ptr_thread = thread;
672 return PJ_SUCCESS;
673 #else
674 pj_thread_t *thread = (pj_thread_t*)desc;
675 *ptr_thread = thread;
676 return PJ_SUCCESS;
677 #endif
678 }
679
680 /*
681 * pj_thread_init(void)
682 */
683 pj_status_t pj_thread_init(void)
684 {
685 #if PJ_HAS_THREADS
686 pj_status_t rc;
687 pj_thread_t *dummy;
688
689 rc = pj_thread_local_alloc(&thread_tls_id );
690 if (rc != PJ_SUCCESS) {
691 return rc;
692 }
693 return pj_thread_register("thr%p", main_thread_desc, &dummy);
694 #else
695 PJ_LOG(2,(THIS_FILE, "Thread init error. Threading is not enabled!"));
696 return PJ_EINVALIDOP;
697 #endif
698 }
699
700 #if PJ_HAS_THREADS
701
702 /*
703 * Set current thread display name
704 * This can be useful for debugging, as the name is displayed in the thread status
705 */
706 static void set_thread_display_name(const char *name)
707 {
708 #if (defined(PJ_LINUX) && PJ_LINUX != 0) || \
709 (defined(PJ_ANDROID) && PJ_ANDROID != 0)
710 char xname[16];
711 // On linux, thread display name length is restricted to 16 (include '\0')
712 if (pj_ansi_strlen(name) >= 16) {
713 pj_memcpy(xname, name, 15);
714 xname[15] = '\0';
715 name = xname;
716 }
717 #endif
718
719 #if defined(PJ_HAS_PTHREAD_SETNAME_NP) && PJ_HAS_PTHREAD_SETNAME_NP != 0
720 # if defined(PJ_DARWINOS) && PJ_DARWINOS != 0
721 pthread_setname_np(name);
722 # else
723 pthread_setname_np(pthread_self(), name);
724 # endif
725 #elif defined(PJ_HAS_PTHREAD_SET_NAME_NP) && PJ_HAS_PTHREAD_SET_NAME_NP != 0
726 pthread_set_name_np(pthread_self(), name);
727 #else
728 // # warning "OS does not support set thread display name"
729 PJ_UNUSED_ARG(name);
730 #endif
731 }
732
733 /*
734 * thread_main()
735 *
736 * This is the main entry for all threads.
737 */
738 static void *thread_main(void *param)
739 {
740 pj_thread_t *rec = (pj_thread_t*)param;
741 void *result;
742 pj_status_t rc;
743
744 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
745 rec->stk_start = (char*)&rec;
746 #endif
747
748 /* Store the thread. */
749 rec->thread = pthread_self();
750
751 /* Set current thread id. */
752 rc = pj_thread_local_set(thread_tls_id, rec);
753 if (rc != PJ_SUCCESS) {
754 pj_assert(!"Thread TLS ID is not set (pj_init() error?)");
755 }
756
757 /* Check if suspension is required. */
758 if (rec->suspended_mutex) {
759 pj_mutex_lock(rec->suspended_mutex);
760 pj_mutex_unlock(rec->suspended_mutex);
761 }
762
763 PJ_LOG(6,(rec->obj_name, "Thread started"));
764
765 set_thread_display_name(rec->obj_name);
766
767 /* Call user's entry! */
768 result = (void*)(long)(*rec->proc)(rec->arg);
769
770 /* Done. */
771 PJ_LOG(6,(rec->obj_name, "Thread quitting"));
772
773 return result;
774 }
775
776 static pj_status_t create_thread(const char *thread_name,
777 pj_thread_proc *proc,
778 void *arg,
779 pj_size_t stack_size,
780 void *stack_addr,
781 pj_thread_t *rec)
782 {
783 pthread_attr_t thread_attr;
784 int rc;
785 const char *ch;
786
787 PJ_UNUSED_ARG(stack_addr);
788
789 PJ_CHECK_STACK();
790 PJ_ASSERT_RETURN(proc && rec, PJ_EINVAL);
791
792 /* Set name. */
793 if (!thread_name)
794 thread_name = "thr%p";
795
796 ch = pj_ansi_strchr(thread_name, '%');
797 if (ch && *(ch+1) == 'p') {
798 pj_ansi_snprintf(rec->obj_name, PJ_MAX_OBJ_NAME, thread_name, rec);
799 } else {
800 pj_ansi_strxcpy(rec->obj_name, thread_name, PJ_MAX_OBJ_NAME);
801 }
802
803 /* Set default stack size */
804 if (stack_size == 0)
805 stack_size = PJ_THREAD_DEFAULT_STACK_SIZE;
806
807 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
808 rec->stk_size = stack_size;
809 rec->stk_max_usage = 0;
810 #endif
811
812 /* Init thread attributes */
813 pthread_attr_init(&thread_attr);
814
815 #if defined(PJ_THREAD_SET_STACK_SIZE) && PJ_THREAD_SET_STACK_SIZE!=0
816 /* Set thread's stack size */
817 rc = pthread_attr_setstacksize(&thread_attr, stack_size);
818 if (rc != 0) {
819 pthread_attr_destroy(&thread_attr);
820 return PJ_RETURN_OS_ERROR(rc);
821 }
822 #endif /* PJ_THREAD_SET_STACK_SIZE */
823
824
825 #if defined(PJ_THREAD_ALLOCATE_STACK) && PJ_THREAD_ALLOCATE_STACK!=0
826 /* Allocate memory for the stack */
827 PJ_ASSERT_RETURN(stack_addr, PJ_EINVAL);
828
829 rc = pthread_attr_setstackaddr(&thread_attr, stack_addr);
830 if (rc != 0) {
831 pthread_attr_destroy(&thread_attr);
832 return PJ_RETURN_OS_ERROR(rc);
833 }
834 #endif /* PJ_THREAD_ALLOCATE_STACK */
835
836
837 /* Create the thread. */
838 rec->proc = proc;
839 rec->arg = arg;
840 rc = pthread_create( &rec->thread, &thread_attr, &thread_main, rec);
841 if (rc != 0) {
842 pthread_attr_destroy(&thread_attr);
843 return PJ_RETURN_OS_ERROR(rc);
844 }
845
846 /* Destroy thread attributes */
847 pthread_attr_destroy(&thread_attr);
848
849 PJ_LOG(6, (rec->obj_name, "Thread created"));
850 return PJ_SUCCESS;
851
852 }
853
854 #endif
855
856 /*
857 * pj_thread_create(...)
858 */
859 PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool,
860 const char *thread_name,
861 pj_thread_proc *proc,
862 void *arg,
863 pj_size_t stack_size,
864 unsigned flags,
865 pj_thread_t **ptr_thread)
866 {
867 #if PJ_HAS_THREADS
868 pj_status_t status;
869 pj_thread_t *rec;
870 void *stack_addr = NULL;
871 int rc;
872
873 PJ_CHECK_STACK();
874 PJ_ASSERT_RETURN(pool && proc && ptr_thread, PJ_EINVAL);
875
876 /* Create thread record and assign name for the thread */
877 rec = (struct pj_thread_t*) pj_pool_zalloc(pool, sizeof(pj_thread_t));
878 PJ_ASSERT_RETURN(rec, PJ_ENOMEM);
879
880 #if defined(PJ_THREAD_ALLOCATE_STACK) && PJ_THREAD_ALLOCATE_STACK!=0
881 /* Allocate memory for the stack */
882 stack_addr = pj_pool_alloc(pool, stack_size);
883 PJ_ASSERT_RETURN(stack_addr, PJ_ENOMEM);
884 #endif /* PJ_THREAD_ALLOCATE_STACK */
885
886 /* Emulate suspended thread with mutex. */
887 if (flags & PJ_THREAD_SUSPENDED) {
888 rc = pj_mutex_create_simple(pool, NULL, &rec->suspended_mutex);
889 if (rc != PJ_SUCCESS) {
890 return rc;
891 }
892
893 pj_mutex_lock(rec->suspended_mutex);
894 } else {
895 pj_assert(rec->suspended_mutex == NULL);
896 }
897
898 status = create_thread(thread_name, proc, arg, stack_size, stack_addr, rec);
899 if (status == PJ_SUCCESS) {
900 /* Success! */
901 *ptr_thread = rec;
902 }
903 return status;
904
905 #else
906 pj_assert(!"Threading is disabled!");
907 return PJ_EINVALIDOP;
908 #endif
909 }
910
911 PJ_DEF(pj_status_t) pj_thread_create2( const char *thread_name,
912 pj_thread_proc *proc,
913 void *arg,
914 pj_size_t stack_size,
915 void *stack_addr,
916 pj_thread_t *thread )
917 {
918 #if PJ_HAS_THREADS
919
920 PJ_CHECK_STACK();
921 PJ_ASSERT_RETURN(proc && thread, PJ_EINVAL);
922
923 if (thread == pj_thread_this())
924 return PJ_ECANCELLED;
925
926 return create_thread(thread_name, proc, arg, stack_size, stack_addr, thread);
927
928 #else
929 pj_assert(!"Threading is disabled!");
930 return PJ_EINVALIDOP;
931 #endif
932 }
933
934 /*
935 * pj_thread-get_name()
936 */
937 PJ_DEF(const char*) pj_thread_get_name(pj_thread_t *p)
938 {
939 #if PJ_HAS_THREADS
940 pj_thread_t *rec = (pj_thread_t*)p;
941
942 PJ_CHECK_STACK();
943 PJ_ASSERT_RETURN(p, "");
944
945 return rec->obj_name;
946 #else
947 return "";
948 #endif
949 }
950
951 /*
952 * pj_thread_resume()
953 */
954 PJ_DEF(pj_status_t) pj_thread_resume(pj_thread_t *p)
955 {
956 pj_status_t rc;
957
958 PJ_CHECK_STACK();
959 PJ_ASSERT_RETURN(p, PJ_EINVAL);
960
961 rc = pj_mutex_unlock(p->suspended_mutex);
962
963 return rc;
964 }
965
966 /*
967 * pj_thread_this()
968 */
969 PJ_DEF(pj_thread_t*) pj_thread_this(void)
970 {
971 #if PJ_HAS_THREADS
972 pj_thread_t *rec = (pj_thread_t*)pj_thread_local_get(thread_tls_id);
973
974 if (rec == NULL) {
975 pj_assert(!"Calling pjlib from unknown/external thread. You must "
976 "register external threads with pj_thread_register() "
977 "before calling any pjlib functions.");
978 }
979
980 /*
981 * MUST NOT check stack because this function is called
982 * by PJ_CHECK_STACK() itself!!!
983 *
984 */
985
986 return rec;
987 #else
988 pj_assert(!"Threading is not enabled!");
989 return NULL;
990 #endif
991 }
992
993 /*
994 * pj_thread_join()
995 */
996 PJ_DEF(pj_status_t) pj_thread_join(pj_thread_t *p)
997 {
998 #if PJ_HAS_THREADS
999 pj_thread_t *rec = (pj_thread_t *)p;
1000 void *ret;
1001 int result;
1002
1003 PJ_CHECK_STACK();
1004
1005 if (p == pj_thread_this())
1006 return PJ_ECANCELLED;
1007
1008 PJ_LOG(6, (pj_thread_this()->obj_name, "Joining thread %s", p->obj_name));
1009 result = pthread_join( rec->thread, &ret);
1010
1011 if (result == 0)
1012 return PJ_SUCCESS;
1013 else {
1014 /* Calling pthread_join() on a thread that no longer exists and
1015 * getting back ESRCH isn't an error (in this context).
1016 * Thanks Phil Torre <[email protected]>.
1017 */
1018 return result==ESRCH ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(result);
1019 }
1020 #else
1021 PJ_CHECK_STACK();
1022 pj_assert(!"No multithreading support!");
1023 return PJ_EINVALIDOP;
1024 #endif
1025 }
1026
1027 /*
1028 * pj_thread_unregister()
1029 */
1030 PJ_DEF(pj_status_t) pj_thread_unregister()
1031 {
1032 #if PJ_HAS_THREADS
1033 pj_status_t status;
1034 //int result;
1035 pj_thread_t *rec;
1036 PJ_CHECK_STACK();
1037
1038 rec = pj_thread_this();
1039 PJ_ASSERT_RETURN(rec, PJ_EBUG);
1040
1041 if ((status = pj_thread_destroy(rec)) != PJ_SUCCESS)
1042 return status;
1043 //else if ((result = pthread_detach(rec->thread)) != 0)
1044 // return PJ_RETURN_OS_ERROR(result);
1045 else
1046 return pj_thread_local_set(thread_tls_id, NULL);
1047 #else
1048 pj_assert(!"No multithreading support!");
1049 return PJ_EINVALIDOP;
1050 #endif
1051 }
1052
1053 /*
1054 * pj_thread_attach()
1055 */
1056 PJ_DEF(pj_status_t) pj_thread_attach(const char *cstr_thread_name,
1057 pj_thread_desc desc,
1058 pj_thread_t **thread_ptr)
1059 {
1060 return pj_thread_register(cstr_thread_name, desc, thread_ptr);
1061 }
1062
1063 /*
1064 * pj_thread_destroy()
1065 */
1066 PJ_DEF(pj_status_t) pj_thread_destroy(pj_thread_t *p)
1067 {
1068 PJ_CHECK_STACK();
1069 PJ_ASSERT_RETURN(p, PJ_EINVAL);
1070
1071 /* Destroy mutex used to suspend thread */
1072 if (p->suspended_mutex) {
1073 pj_mutex_destroy(p->suspended_mutex);
1074 p->suspended_mutex = NULL;
1075 }
1076
1077 return PJ_SUCCESS;
1078 }
1079
1080 /*
1081 * pj_thread_sleep()
1082 */
1083 PJ_DEF(pj_status_t) pj_thread_sleep(unsigned msec)
1084 {
1085 /* TODO: should change this to something like PJ_OS_HAS_NANOSLEEP */
1086 #if defined(PJ_RTEMS) && PJ_RTEMS!=0
1087 enum { NANOSEC_PER_MSEC = 1000000 };
1088 struct timespec req;
1089
1090 PJ_CHECK_STACK();
1091 req.tv_sec = msec / 1000;
1092 req.tv_nsec = (msec % 1000) * NANOSEC_PER_MSEC;
1093
1094 if (nanosleep(&req, NULL) == 0)
1095 return PJ_SUCCESS;
1096
1097 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
1098 #else
1099 PJ_CHECK_STACK();
1100
1101 pj_set_os_error(0);
1102
1103 usleep(msec * 1000);
1104
1105 /* MacOS X (reported on 10.5) seems to always set errno to ETIMEDOUT.
1106 * It does so because usleep() is declared to return int, and we're
1107 * supposed to check for errno only when usleep() returns non-zero.
1108 * Unfortunately, usleep() is declared to return void in other platforms
1109 * so it's not possible to always check for the return value (unless
1110 * we add a detection routine in autoconf).
1111 *
1112 * As a workaround, here we check if ETIMEDOUT is returned and
1113 * return successfully if it is.
1114 */
1115 if (pj_get_native_os_error() == ETIMEDOUT)
1116 return PJ_SUCCESS;
1117
1118 return pj_get_os_error();
1119
1120 #endif /* PJ_RTEMS */
1121 }
1122
1123 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
1124 /*
1125 * pj_thread_check_stack()
1126 * Implementation for PJ_CHECK_STACK()
1127 */
1128 PJ_DEF(void) pj_thread_check_stack(const char *file, int line)
1129 {
1130 char stk_ptr;
1131 pj_uint32_t usage;
1132 pj_thread_t *thread;
1133
1134 /* may be called after pj_thread_unregister() */
1135 if (!pj_thread_is_registered())
1136 return;
1137
1138 thread = pj_thread_this();
1139
1140 /* Calculate current usage. */
1141 usage = (&stk_ptr > thread->stk_start) ? &stk_ptr - thread->stk_start :
1142 thread->stk_start - &stk_ptr;
1143
1144 /* Assert if stack usage is dangerously high. */
1145 pj_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128));
1146
1147 /* Keep statistic. */
1148 if (usage > thread->stk_max_usage) {
1149 thread->stk_max_usage = usage;
1150 thread->caller_file = file;
1151 thread->caller_line = line;
1152 }
1153 }
1154
1155 /*
1156 * pj_thread_get_stack_max_usage()
1157 */
1158 PJ_DEF(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread)
1159 {
1160 return thread->stk_max_usage;
1161 }
1162
1163 /*
1164 * pj_thread_get_stack_info()
1165 */
1166 PJ_DEF(pj_status_t) pj_thread_get_stack_info( pj_thread_t *thread,
1167 const char **file,
1168 int *line )
1169 {
1170 pj_assert(thread);
1171
1172 *file = thread->caller_file;
1173 *line = thread->caller_line;
1174 return 0;
1175 }
1176
1177 #endif /* PJ_OS_HAS_CHECK_STACK */
1178
1179 ///////////////////////////////////////////////////////////////////////////////
1180 /*
1181 * pj_atomic_create()
1182 */
1183 PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool,
1184 pj_atomic_value_t initial,
1185 pj_atomic_t **ptr_atomic)
1186 {
1187 #if EMULATE_ATOMICS
1188 pj_status_t rc;
1189 #endif
1190 pj_atomic_t *atomic_var;
1191
1192 atomic_var = PJ_POOL_ZALLOC_T(pool, pj_atomic_t);
1193
1194 PJ_ASSERT_RETURN(atomic_var, PJ_ENOMEM);
1195
1196 #if HAS_STD_ATOMICS
1197 atomic_init(&atomic_var->value, initial);
1198 #elif EMULATE_ATOMICS
1199 rc = pj_mutex_create(pool, "atm%p", PJ_MUTEX_SIMPLE, &atomic_var->mutex);
1200 if (rc != PJ_SUCCESS)
1201 return rc;
1202 atomic_var->value = initial;
1203 #else
1204 atomic_var->value = initial;
1205 #endif
1206
1207 *ptr_atomic = atomic_var;
1208 return PJ_SUCCESS;
1209 }
1210
1211 /*
1212 * pj_atomic_destroy()
1213 */
1214 PJ_DEF(pj_status_t) pj_atomic_destroy( pj_atomic_t *atomic_var )
1215 {
1216 #if EMULATE_ATOMICS
1217 pj_status_t status;
1218 #endif
1219
1220 PJ_ASSERT_RETURN(atomic_var, PJ_EINVAL);
1221
1222 #if EMULATE_ATOMICS
1223 status = pj_mutex_destroy( atomic_var->mutex );
1224 if (status == PJ_SUCCESS) {
1225 atomic_var->mutex = NULL;
1226 }
1227 return status;
1228 #else
1229 return 0;
1230 #endif
1231 }
1232
1233 /*
1234 * pj_atomic_set()
1235 */
1236 PJ_DEF(void) pj_atomic_set(pj_atomic_t *atomic_var, pj_atomic_value_t value)
1237 {
1238 #if EMULATE_ATOMICS
1239 pj_status_t status;
1240 #endif
1241
1242 PJ_CHECK_STACK();
1243 PJ_ASSERT_ON_FAIL(atomic_var, return);
1244
1245 #if HAS_STD_ATOMICS
1246 atomic_store(&atomic_var->value, value);
1247 #elif EMULATE_ATOMICS
1248 status = pj_mutex_lock( atomic_var->mutex );
1249 if (status != PJ_SUCCESS) {
1250 return;
1251 }
1252 atomic_var->value = value;
1253 pj_mutex_unlock( atomic_var->mutex);
1254 #else
1255 atomic_var->value = value;
1256 #endif
1257 }
1258
1259 /*
1260 * pj_atomic_get()
1261 */
1262 PJ_DEF(pj_atomic_value_t) pj_atomic_get(pj_atomic_t *atomic_var)
1263 {
1264 pj_atomic_value_t oldval;
1265
1266 PJ_CHECK_STACK();
1267
1268 #if HAS_STD_ATOMICS
1269 oldval = atomic_load(&atomic_var->value);
1270 #elif EMULATE_ATOMICS
1271 pj_mutex_lock( atomic_var->mutex );
1272 oldval = atomic_var->value;
1273 pj_mutex_unlock( atomic_var->mutex);
1274 #else
1275 oldval = atomic_var->value;
1276 #endif
1277
1278 return oldval;
1279 }
1280
1281 /*
1282 * pj_atomic_inc_and_get()
1283 */
1284 PJ_DEF(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var)
1285 {
1286 pj_atomic_value_t new_value;
1287
1288 PJ_CHECK_STACK();
1289
1290 #if HAS_STD_ATOMICS
1291 new_value = atomic_fetch_add(&atomic_var->value, 1) + 1;
1292 #elif EMULATE_ATOMICS
1293 pj_mutex_lock( atomic_var->mutex );
1294 new_value = ++atomic_var->value;
1295 pj_mutex_unlock( atomic_var->mutex);
1296 #else
1297 new_value = ++atomic_var->value;
1298 #endif
1299
1300 return new_value;
1301 }
1302 /*
1303 * pj_atomic_inc()
1304 */
1305 PJ_DEF(void) pj_atomic_inc(pj_atomic_t *atomic_var)
1306 {
1307 PJ_ASSERT_ON_FAIL(atomic_var, return);
1308 pj_atomic_inc_and_get(atomic_var);
1309 }
1310
1311 /*
1312 * pj_atomic_dec_and_get()
1313 */
1314 PJ_DEF(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var)
1315 {
1316 pj_atomic_value_t new_value;
1317
1318 PJ_CHECK_STACK();
1319
1320 #if HAS_STD_ATOMICS
1321 new_value = atomic_fetch_sub(&atomic_var->value, 1) - 1;
1322 #elif EMULATE_ATOMICS
1323 pj_mutex_lock( atomic_var->mutex );
1324 new_value = --atomic_var->value;
1325 pj_mutex_unlock( atomic_var->mutex);
1326 #else
1327 new_value = --atomic_var->value;
1328 #endif
1329
1330 return new_value;
1331 }
1332
1333 /*
1334 * pj_atomic_dec()
1335 */
1336 PJ_DEF(void) pj_atomic_dec(pj_atomic_t *atomic_var)
1337 {
1338 PJ_ASSERT_ON_FAIL(atomic_var, return);
1339 pj_atomic_dec_and_get(atomic_var);
1340 }
1341
1342 /*
1343 * pj_atomic_add_and_get()
1344 */
1345 PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var,
1346 pj_atomic_value_t value )
1347 {
1348 pj_atomic_value_t new_value;
1349
1350 #if HAS_STD_ATOMICS
1351 new_value = atomic_fetch_add(&atomic_var->value, value) + value;
1352 #elif EMULATE_ATOMICS
1353 pj_mutex_lock( atomic_var->mutex );
1354 new_value = atomic_var->value += value;
1355 pj_mutex_unlock( atomic_var->mutex);
1356 #else
1357 new_value = atomic_var->value += value;
1358 #endif
1359
1360 return new_value;
1361 }
1362
1363 /*
1364 * pj_atomic_add()
1365 */
1366 PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var,
1367 pj_atomic_value_t value )
1368 {
1369 PJ_ASSERT_ON_FAIL(atomic_var, return);
1370 pj_atomic_add_and_get(atomic_var, value);
1371 }
1372
1373 ///////////////////////////////////////////////////////////////////////////////
1374 /*
1375 * pj_thread_local_alloc()
1376 */
1377 PJ_DEF(pj_status_t) pj_thread_local_alloc(long *p_index)
1378 {
1379 #if PJ_HAS_THREADS
1380 pthread_key_t key;
1381 int rc;
1382
1383 PJ_ASSERT_RETURN(p_index != NULL, PJ_EINVAL);
1384
1385 pj_assert( sizeof(pthread_key_t) <= sizeof(long));
1386 if ((rc=pthread_key_create(&key, NULL)) != 0)
1387 return PJ_RETURN_OS_ERROR(rc);
1388
1389 *p_index = key;
1390 return PJ_SUCCESS;
1391 #else
1392 int i;
1393 for (i=0; i<MAX_THREADS; ++i) {
1394 if (tls_flag[i] == 0)
1395 break;
1396 }
1397 if (i == MAX_THREADS)
1398 return PJ_ETOOMANY;
1399
1400 tls_flag[i] = 1;
1401 tls[i] = NULL;
1402
1403 *p_index = i;
1404 return PJ_SUCCESS;
1405 #endif
1406 }
1407
1408 /*
1409 * pj_thread_local_free()
1410 */
1411 PJ_DEF(void) pj_thread_local_free(long index)
1412 {
1413 PJ_CHECK_STACK();
1414 #if PJ_HAS_THREADS
1415 pthread_key_delete(index);
1416 #else
1417 tls_flag[index] = 0;
1418 #endif
1419 }
1420
1421 /*
1422 * pj_thread_local_set()
1423 */
1424 PJ_DEF(pj_status_t) pj_thread_local_set(long index, void *value)
1425 {
1426 //Can't check stack because this function is called in the
1427 //beginning before main thread is initialized.
1428 //PJ_CHECK_STACK();
1429 #if PJ_HAS_THREADS
1430 int rc=pthread_setspecific(index, value);
1431 return rc==0 ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(rc);
1432 #else
1433 pj_assert(index >= 0 && index < MAX_THREADS);
1434 tls[index] = value;
1435 return PJ_SUCCESS;
1436 #endif
1437 }
1438
1439 PJ_DEF(void*) pj_thread_local_get(long index)
1440 {
1441 //Can't check stack because this function is called
1442 //by PJ_CHECK_STACK() itself!!!
1443 //PJ_CHECK_STACK();
1444 #if PJ_HAS_THREADS
1445 return pthread_getspecific(index);
1446 #else
1447 pj_assert(index >= 0 && index < MAX_THREADS);
1448 return tls[index];
1449 #endif
1450 }
1451
1452 ///////////////////////////////////////////////////////////////////////////////
1453 PJ_DEF(void) pj_enter_critical_section(void)
1454 {
1455 #if PJ_HAS_THREADS
1456 pj_mutex_lock(&critical_section);
1457 #endif
1458 }
1459
1460 PJ_DEF(void) pj_leave_critical_section(void)
1461 {
1462 #if PJ_HAS_THREADS
1463 pj_mutex_unlock(&critical_section);
1464 #endif
1465 }
1466
1467
1468 ///////////////////////////////////////////////////////////////////////////////
1469 #if defined(PJ_LINUX) && PJ_LINUX!=0
1470 PJ_BEGIN_DECL
1471 PJ_DECL(int) pthread_mutexattr_settype(pthread_mutexattr_t*,int);
1472 PJ_END_DECL
1473 #endif
1474
1475 static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name, int type)
1476 {
1477 #if PJ_HAS_THREADS
1478 pthread_mutexattr_t attr;
1479 int rc;
1480
1481 PJ_CHECK_STACK();
1482
1483 rc = pthread_mutexattr_init(&attr);
1484 if (rc != 0)
1485 return PJ_RETURN_OS_ERROR(rc);
1486
1487 if (type == PJ_MUTEX_SIMPLE) {
1488 #if (defined(PJ_LINUX) && PJ_LINUX!=0) || \
1489 defined(PJ_HAS_PTHREAD_MUTEXATTR_SETTYPE)
1490 rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
1491 #elif (defined(PJ_RTEMS) && PJ_RTEMS!=0) || \
1492 defined(PJ_PTHREAD_MUTEXATTR_T_HAS_RECURSIVE)
1493 /* Nothing to do, default is simple */
1494 #else
1495 rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
1496 #endif
1497 } else {
1498 #if (defined(PJ_LINUX) && PJ_LINUX!=0) || \
1499 defined(PJ_HAS_PTHREAD_MUTEXATTR_SETTYPE)
1500 rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1501 #elif (defined(PJ_RTEMS) && PJ_RTEMS!=0) || \
1502 defined(PJ_PTHREAD_MUTEXATTR_T_HAS_RECURSIVE)
1503 // Phil Torre <[email protected]>:
1504 // The RTEMS implementation of POSIX mutexes doesn't include
1505 // pthread_mutexattr_settype(), so what follows is a hack
1506 // until I get RTEMS patched to support the set/get functions.
1507 //
1508 // More info:
1509 // newlib's pthread also lacks pthread_mutexattr_settype(),
1510 // but it seems to have mutexattr.recursive.
1511 PJ_TODO(FIX_RTEMS_RECURSIVE_MUTEX_TYPE)
1512 attr.recursive = 1;
1513 #else
1514 rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1515 #endif
1516 }
1517
1518 if (rc != 0) {
1519 return PJ_RETURN_OS_ERROR(rc);
1520 }
1521
1522 rc = pthread_mutex_init(&mutex->mutex, &attr);
1523 if (rc != 0) {
1524 return PJ_RETURN_OS_ERROR(rc);
1525 }
1526
1527 rc = pthread_mutexattr_destroy(&attr);
1528 if (rc != 0) {
1529 pj_status_t status = PJ_RETURN_OS_ERROR(rc);
1530 pthread_mutex_destroy(&mutex->mutex);
1531 return status;
1532 }
1533
1534 #if PJ_DEBUG
1535 /* Set owner. */
1536 mutex->nesting_level = 0;
1537 mutex->owner = NULL;
1538 mutex->owner_name[0] = '\0';
1539 #endif
1540
1541 /* Set name. */
1542 if (!name) {
1543 name = "mtx%p";
1544 }
1545 if (strchr(name, '%')) {
1546 pj_ansi_snprintf(mutex->obj_name, PJ_MAX_OBJ_NAME, name, mutex);
1547 } else {
1548 pj_ansi_strxcpy(mutex->obj_name, name, PJ_MAX_OBJ_NAME);
1549 }
1550
1551 PJ_LOG(6, (mutex->obj_name, "Mutex created"));
1552 return PJ_SUCCESS;
1553 #else /* PJ_HAS_THREADS */
1554 return PJ_SUCCESS;
1555 #endif
1556 }
1557
1558 /*
1559 * pj_mutex_create()
1560 */
1561 PJ_DEF(pj_status_t) pj_mutex_create(pj_pool_t *pool,
1562 const char *name,
1563 int type,
1564 pj_mutex_t **ptr_mutex)
1565 {
1566 #if PJ_HAS_THREADS
1567 pj_status_t rc;
1568 pj_mutex_t *mutex;
1569
1570 PJ_ASSERT_RETURN(pool && ptr_mutex, PJ_EINVAL);
1571
1572 mutex = PJ_POOL_ALLOC_T(pool, pj_mutex_t);
1573 PJ_ASSERT_RETURN(mutex, PJ_ENOMEM);
1574
1575 if ((rc=init_mutex(mutex, name, type)) != PJ_SUCCESS)
1576 return rc;
1577
1578 *ptr_mutex = mutex;
1579 return PJ_SUCCESS;
1580 #else /* PJ_HAS_THREADS */
1581 *ptr_mutex = (pj_mutex_t*)1;
1582 return PJ_SUCCESS;
1583 #endif
1584 }
1585
1586 /*
1587 * pj_mutex_create_simple()
1588 */
1589 PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool,
1590 const char *name,
1591 pj_mutex_t **mutex )
1592 {
1593 return pj_mutex_create(pool, name, PJ_MUTEX_SIMPLE, mutex);
1594 }
1595
1596 /*
1597 * pj_mutex_create_recursive()
1598 */
1599 PJ_DEF(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool,
1600 const char *name,
1601 pj_mutex_t **mutex )
1602 {
1603 return pj_mutex_create(pool, name, PJ_MUTEX_RECURSE, mutex);
1604 }
1605
1606 /*
1607 * pj_mutex_lock()
1608 */
1609 PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex)
1610 {
1611 #if PJ_HAS_THREADS
1612 pj_status_t status;
1613
1614 PJ_CHECK_STACK();
1615 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1616
1617 #if PJ_DEBUG
1618 PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s is waiting (mutex owner=%s)",
1619 pj_thread_this()->obj_name,
1620 mutex->owner_name));
1621 #else
1622 PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s is waiting",
1623 pj_thread_this()->obj_name));
1624 #endif
1625
1626 status = pthread_mutex_lock( &mutex->mutex );
1627
1628
1629 #if PJ_DEBUG
1630 if (status == PJ_SUCCESS) {
1631 mutex->owner = pj_thread_this();
1632 pj_ansi_strxcpy(mutex->owner_name, mutex->owner->obj_name,
1633 sizeof(mutex->owner_name));
1634 ++mutex->nesting_level;
1635 }
1636
1637 PJ_LOG(6,(mutex->obj_name,
1638 (status==0 ?
1639 "Mutex acquired by thread %s (level=%d)" :
1640 "Mutex acquisition FAILED by %s (level=%d)"),
1641 pj_thread_this()->obj_name,
1642 mutex->nesting_level));
1643 #else
1644 PJ_LOG(6,(mutex->obj_name,
1645 (status==0 ? "Mutex acquired by thread %s" : "FAILED by %s"),
1646 pj_thread_this()->obj_name));
1647 #endif
1648
1649 if (status == 0)
1650 return PJ_SUCCESS;
1651 else
1652 return PJ_RETURN_OS_ERROR(status);
1653 #else /* PJ_HAS_THREADS */
1654 pj_assert( mutex == (pj_mutex_t*)1 );
1655 return PJ_SUCCESS;
1656 #endif
1657 }
1658
1659 /*
1660 * pj_mutex_unlock()
1661 */
1662 PJ_DEF(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex)
1663 {
1664 #if PJ_HAS_THREADS
1665 pj_status_t status;
1666
1667 PJ_CHECK_STACK();
1668 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1669
1670 #if PJ_DEBUG
1671 pj_assert(mutex->owner == pj_thread_this());
1672 if (--mutex->nesting_level == 0) {
1673 mutex->owner = NULL;
1674 mutex->owner_name[0] = '\0';
1675 }
1676
1677 PJ_LOG(6,(mutex->obj_name, "Mutex released by thread %s (level=%d)",
1678 pj_thread_this()->obj_name,
1679 mutex->nesting_level));
1680 #else
1681 PJ_LOG(6,(mutex->obj_name, "Mutex released by thread %s",
1682 pj_thread_this()->obj_name));
1683 #endif
1684
1685 status = pthread_mutex_unlock( &mutex->mutex );
1686 if (status == 0)
1687 return PJ_SUCCESS;
1688 else
1689 return PJ_RETURN_OS_ERROR(status);
1690
1691 #else /* PJ_HAS_THREADS */
1692 pj_assert( mutex == (pj_mutex_t*)1 );
1693 return PJ_SUCCESS;
1694 #endif
1695 }
1696
1697 /*
1698 * pj_mutex_trylock()
1699 */
1700 PJ_DEF(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex)
1701 {
1702 #if PJ_HAS_THREADS
1703 int status;
1704
1705 PJ_CHECK_STACK();
1706 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1707
1708 PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s is trying",
1709 pj_thread_this()->obj_name));
1710
1711 status = pthread_mutex_trylock( &mutex->mutex );
1712
1713 if (status==0) {
1714 #if PJ_DEBUG
1715 mutex->owner = pj_thread_this();
1716 pj_ansi_strxcpy(mutex->owner_name, mutex->owner->obj_name,
1717 sizeof(mutex->owner_name));
1718 ++mutex->nesting_level;
1719
1720 PJ_LOG(6,(mutex->obj_name, "Mutex acquired by thread %s (level=%d)",
1721 pj_thread_this()->obj_name,
1722 mutex->nesting_level));
1723 #else
1724 PJ_LOG(6,(mutex->obj_name, "Mutex acquired by thread %s",
1725 pj_thread_this()->obj_name));
1726 #endif
1727 } else {
1728 PJ_LOG(6,(mutex->obj_name, "Mutex: thread %s's trylock() failed",
1729 pj_thread_this()->obj_name));
1730 }
1731
1732 if (status==0)
1733 return PJ_SUCCESS;
1734 else
1735 return PJ_RETURN_OS_ERROR(status);
1736 #else /* PJ_HAS_THREADS */
1737 pj_assert( mutex == (pj_mutex_t*)1);
1738 return PJ_SUCCESS;
1739 #endif
1740 }
1741
1742 /*
1743 * pj_mutex_destroy()
1744 */
1745 PJ_DEF(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex)
1746 {
1747 enum { RETRY = 4 };
1748 int status = 0;
1749 unsigned retry;
1750
1751 PJ_CHECK_STACK();
1752 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1753
1754 #if PJ_HAS_THREADS
1755 PJ_LOG(6,(mutex->obj_name, "Mutex destroyed by thread %s",
1756 pj_thread_this()->obj_name));
1757
1758 for (retry=0; retry<RETRY; ++retry) {
1759 status = pthread_mutex_destroy( &mutex->mutex );
1760 if (status == PJ_SUCCESS)
1761 break;
1762 else if (retry<RETRY-1 && status == EBUSY)
1763 pthread_mutex_unlock(&mutex->mutex);
1764 }
1765
1766 if (status == 0)
1767 return PJ_SUCCESS;
1768 else {
1769 return PJ_RETURN_OS_ERROR(status);
1770 }
1771 #else
1772 pj_assert( mutex == (pj_mutex_t*)1 );
1773 status = PJ_SUCCESS;
1774 return status;
1775 #endif
1776 }
1777
1778 #if PJ_DEBUG
1779 PJ_DEF(pj_bool_t) pj_mutex_is_locked(pj_mutex_t *mutex)
1780 {
1781 #if PJ_HAS_THREADS
1782 return mutex->owner == pj_thread_this();
1783 #else
1784 return 1;
1785 #endif
1786 }
1787 #endif
1788
1789 ///////////////////////////////////////////////////////////////////////////////
1790 /*
1791 * Include Read/Write mutex emulation for POSIX platforms that lack it (e.g.
1792 * RTEMS). Otherwise use POSIX rwlock.
1793 */
1794 #if defined(PJ_EMULATE_RWMUTEX) && PJ_EMULATE_RWMUTEX!=0
1795 /* We need semaphore functionality to emulate rwmutex */
1796 # if !defined(PJ_HAS_SEMAPHORE) || PJ_HAS_SEMAPHORE==0
1797 # error "Semaphore support needs to be enabled to emulate rwmutex"
1798 # endif
1799 # include "os_rwmutex.c"
1800 #else
1801 struct pj_rwmutex_t
1802 {
1803 pthread_rwlock_t rwlock;
1804 };
1805
1806 PJ_DEF(pj_status_t) pj_rwmutex_create(pj_pool_t *pool, const char *name,
1807 pj_rwmutex_t **p_mutex)
1808 {
1809 pj_rwmutex_t *rwm;
1810 pj_status_t status;
1811
1812 PJ_UNUSED_ARG(name);
1813
1814 rwm = PJ_POOL_ALLOC_T(pool, pj_rwmutex_t);
1815 PJ_ASSERT_RETURN(rwm, PJ_ENOMEM);
1816
1817 status = pthread_rwlock_init(&rwm->rwlock, NULL);
1818 if (status != 0)
1819 return PJ_RETURN_OS_ERROR(status);
1820
1821 *p_mutex = rwm;
1822 return PJ_SUCCESS;
1823 }
1824
1825 /*
1826 * Lock the mutex for reading.
1827 *
1828 */
1829 PJ_DEF(pj_status_t) pj_rwmutex_lock_read(pj_rwmutex_t *mutex)
1830 {
1831 pj_status_t status;
1832
1833 status = pthread_rwlock_rdlock(&mutex->rwlock);
1834 if (status != 0)
1835 return PJ_RETURN_OS_ERROR(status);
1836
1837 return PJ_SUCCESS;
1838 }
1839
1840 /*
1841 * Lock the mutex for writing.
1842 *
1843 */
1844 PJ_DEF(pj_status_t) pj_rwmutex_lock_write(pj_rwmutex_t *mutex)
1845 {
1846 pj_status_t status;
1847
1848 status = pthread_rwlock_wrlock(&mutex->rwlock);
1849 if (status != 0)
1850 return PJ_RETURN_OS_ERROR(status);
1851
1852 return PJ_SUCCESS;
1853 }
1854
1855 /*
1856 * Release read lock.
1857 *
1858 */
1859 PJ_DEF(pj_status_t) pj_rwmutex_unlock_read(pj_rwmutex_t *mutex)
1860 {
1861 return pj_rwmutex_unlock_write(mutex);
1862 }
1863
1864 /*
1865 * Release write lock.
1866 *
1867 */
1868 PJ_DEF(pj_status_t) pj_rwmutex_unlock_write(pj_rwmutex_t *mutex)
1869 {
1870 pj_status_t status;
1871
1872 status = pthread_rwlock_unlock(&mutex->rwlock);
1873 if (status != 0)
1874 return PJ_RETURN_OS_ERROR(status);
1875
1876 return PJ_SUCCESS;
1877 }
1878
1879 /*
1880 * Destroy reader/writer mutex.
1881 *
1882 */
1883 PJ_DEF(pj_status_t) pj_rwmutex_destroy(pj_rwmutex_t *mutex)
1884 {
1885 pj_status_t status;
1886
1887 status = pthread_rwlock_destroy(&mutex->rwlock);
1888 if (status != 0)
1889 return PJ_RETURN_OS_ERROR(status);
1890
1891 return PJ_SUCCESS;
1892 }
1893
1894 #endif /* PJ_EMULATE_RWMUTEX */
1895
1896
1897 ///////////////////////////////////////////////////////////////////////////////
1898 #if defined(PJ_HAS_SEMAPHORE) && PJ_HAS_SEMAPHORE != 0
1899
1900 /*
1901 * pj_sem_create()
1902 */
1903 PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool,
1904 const char *name,
1905 unsigned initial,
1906 unsigned max,
1907 pj_sem_t **ptr_sem)
1908 {
1909 #if PJ_HAS_THREADS
1910 pj_sem_t *sem;
1911 PJ_UNUSED_ARG(max);
1912
1913 PJ_CHECK_STACK();
1914 PJ_ASSERT_RETURN(pool != NULL && ptr_sem != NULL, PJ_EINVAL);
1915
1916 sem = PJ_POOL_ALLOC_T(pool, pj_sem_t);
1917 PJ_ASSERT_RETURN(sem, PJ_ENOMEM);
1918
1919 #if defined(PJ_DARWINOS) && PJ_DARWINOS!=0
1920 # if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
1921 sem->sem = dispatch_semaphore_create(initial);
1922 if (sem->sem == NULL)
1923 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
1924 # else
1925 /* MacOS X doesn't support anonymous semaphore */
1926 {
1927 char sem_name[PJ_GUID_MAX_LENGTH+1];
1928 pj_str_t nam;
1929
1930 /* We should use SEM_NAME_LEN, but this doesn't seem to be
1931 * declared anywhere? The value here is just from trial and error
1932 * to get the longest name supported.
1933 */
1934 # define MAX_SEM_NAME_LEN 23
1935
1936 /* Create a unique name for the semaphore. */
1937 if (PJ_GUID_STRING_LENGTH <= MAX_SEM_NAME_LEN) {
1938 nam.ptr = sem_name;
1939 pj_generate_unique_string(&nam);
1940 sem_name[nam.slen] = '\0';
1941 } else {
1942 pj_create_random_string(sem_name, MAX_SEM_NAME_LEN);
1943 sem_name[MAX_SEM_NAME_LEN] = '\0';
1944 }
1945
1946 /* Create semaphore */
1947 sem->sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR,
1948 initial);
1949 if (sem->sem == SEM_FAILED)
1950 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
1951
1952 /* And immediately release the name as we don't need it */
1953 sem_unlink(sem_name);
1954 }
1955 # endif
1956 #else
1957 sem->sem = PJ_POOL_ALLOC_T(pool, sem_t);
1958 if (sem_init( sem->sem, 0, initial) != 0)
1959 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
1960 #endif
1961
1962 /* Set name. */
1963 if (!name) {
1964 name = "sem%p";
1965 }
1966 if (strchr(name, '%')) {
1967 pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem);
1968 } else {
1969 pj_ansi_strxcpy(sem->obj_name, name, PJ_MAX_OBJ_NAME);
1970 }
1971
1972 PJ_LOG(6, (sem->obj_name, "Semaphore created"));
1973
1974 *ptr_sem = sem;
1975 return PJ_SUCCESS;
1976 #else
1977 PJ_UNUSED_ARG(pool);
1978 PJ_UNUSED_ARG(name);
1979 PJ_UNUSED_ARG(initial);
1980 PJ_UNUSED_ARG(max);
1981 *ptr_sem = (pj_sem_t*)1;
1982 return PJ_SUCCESS;
1983 #endif
1984 }
1985
1986 /*
1987 * pj_sem_wait()
1988 */
1989 PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem)
1990 {
1991 #if PJ_HAS_THREADS
1992 long result;
1993
1994 PJ_CHECK_STACK();
1995 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
1996
1997 PJ_LOG(6, (sem->obj_name, "Semaphore: thread %s is waiting",
1998 pj_thread_this()->obj_name));
1999
2000 #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
2001 result = dispatch_semaphore_wait(sem->sem, DISPATCH_TIME_FOREVER);
2002 #else
2003 result = sem_wait( sem->sem );
2004 #endif
2005
2006 if (result == 0) {
2007 PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s",
2008 pj_thread_this()->obj_name));
2009 } else {
2010 PJ_LOG(6, (sem->obj_name, "Semaphore: thread %s FAILED to acquire",
2011 pj_thread_this()->obj_name));
2012 }
2013
2014 if (result == 0)
2015 return PJ_SUCCESS;
2016 else
2017 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
2018 #else
2019 pj_assert( sem == (pj_sem_t*) 1 );
2020 return PJ_SUCCESS;
2021 #endif
2022 }
2023
2024 /*
2025 * pj_sem_trywait()
2026 */
2027 PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem)
2028 {
2029 #if PJ_HAS_THREADS
2030 long result;
2031
2032 PJ_CHECK_STACK();
2033 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
2034
2035 #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
2036 result = dispatch_semaphore_wait(sem->sem, DISPATCH_TIME_NOW);
2037 #else
2038 result = sem_trywait( sem->sem );
2039 #endif
2040
2041 if (result == 0) {
2042 PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s",
2043 pj_thread_this()->obj_name));
2044 }
2045 if (result == 0)
2046 return PJ_SUCCESS;
2047 else
2048 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
2049 #else
2050 pj_assert( sem == (pj_sem_t*)1 );
2051 return PJ_SUCCESS;
2052 #endif
2053 }
2054
2055 /*
2056 * pj_sem_post()
2057 */
2058 PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem)
2059 {
2060 #if PJ_HAS_THREADS
2061 int result;
2062 PJ_LOG(6, (sem->obj_name, "Semaphore released by thread %s",
2063 pj_thread_this()->obj_name));
2064 #if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
2065 dispatch_semaphore_signal(sem->sem);
2066 result = 0;
2067 #else
2068 result = sem_post( sem->sem );
2069 #endif
2070
2071 if (result == 0)
2072 return PJ_SUCCESS;
2073 else
2074 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
2075 #else
2076 pj_assert( sem == (pj_sem_t*) 1);
2077 return PJ_SUCCESS;
2078 #endif
2079 }
2080
2081 /*
2082 * pj_sem_destroy()
2083 */
2084 PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem)
2085 {
2086 #if PJ_HAS_THREADS
2087 int result;
2088
2089 PJ_CHECK_STACK();
2090 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
2091
2092 PJ_LOG(6, (sem->obj_name, "Semaphore destroyed by thread %s",
2093 pj_thread_this()->obj_name));
2094 #if defined(PJ_DARWINOS) && PJ_DARWINOS!=0
2095 # if defined(PJ_SEMAPHORE_USE_DISPATCH_SEM) && PJ_SEMAPHORE_USE_DISPATCH_SEM != 0
2096 dispatch_release(sem->sem);
2097 result = 0;
2098 # else
2099 result = sem_close( sem->sem );
2100 # endif
2101 #else
2102 result = sem_destroy( sem->sem );
2103 #endif
2104
2105 if (result == 0)
2106 return PJ_SUCCESS;
2107 else
2108 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
2109 #else
2110 pj_assert( sem == (pj_sem_t*) 1 );
2111 return PJ_SUCCESS;
2112 #endif
2113 }
2114
2115 #endif /* PJ_HAS_SEMAPHORE */
2116
2117 ///////////////////////////////////////////////////////////////////////////////
2118 #if defined(PJ_HAS_EVENT_OBJ) && PJ_HAS_EVENT_OBJ != 0
2119
2120 /*
2121 * pj_event_create()
2122 */
2123 PJ_DEF(pj_status_t) pj_event_create(pj_pool_t *pool, const char *name,
2124 pj_bool_t manual_reset, pj_bool_t initial,
2125 pj_event_t **ptr_event)
2126 {
2127 pj_event_t *event;
2128
2129 event = PJ_POOL_ALLOC_T(pool, pj_event_t);
2130
2131 init_mutex(&event->mutex, name, PJ_MUTEX_SIMPLE);
2132 pthread_cond_init(&event->cond, 0);
2133 event->auto_reset = !manual_reset;
2134 event->threads_waiting = 0;
2135
2136 if (initial) {
2137 event->state = EV_STATE_SET;
2138 event->threads_to_release = 1;
2139 } else {
2140 event->state = EV_STATE_OFF;
2141 event->threads_to_release = 0;
2142 }
2143
2144 *ptr_event = event;
2145 return PJ_SUCCESS;
2146 }
2147
2148 static void event_on_one_release(pj_event_t *event)
2149 {
2150 if (event->state == EV_STATE_SET) {
2151 if (event->auto_reset) {
2152 event->threads_to_release = 0;
2153 event->state = EV_STATE_OFF;
2154 } else {
2155 /* Manual reset remains on */
2156 }
2157 } else {
2158 if (event->auto_reset) {
2159 /* Only release one */
2160 event->threads_to_release = 0;
2161 event->state = EV_STATE_OFF;
2162 } else {
2163 event->threads_to_release--;
2164 pj_assert(event->threads_to_release >= 0);
2165 if (event->threads_to_release==0)
2166 event->state = EV_STATE_OFF;
2167 }
2168 }
2169 }
2170
2171 /*
2172 * pj_event_wait()
2173 */
2174 PJ_DEF(pj_status_t) pj_event_wait(pj_event_t *event)
2175 {
2176 pthread_mutex_lock(&event->mutex.mutex);
2177 event->threads_waiting++;
2178 while (event->state == EV_STATE_OFF)
2179 pthread_cond_wait(&event->cond, &event->mutex.mutex);
2180 event->threads_waiting--;
2181 event_on_one_release(event);
2182 pthread_mutex_unlock(&event->mutex.mutex);
2183 return PJ_SUCCESS;
2184 }
2185
2186 /*
2187 * pj_event_trywait()
2188 */
2189 PJ_DEF(pj_status_t) pj_event_trywait(pj_event_t *event)
2190 {
2191 pj_status_t status;
2192
2193 pthread_mutex_lock(&event->mutex.mutex);
2194 status = event->state != EV_STATE_OFF ? PJ_SUCCESS : -1;
2195 if (status==PJ_SUCCESS) {
2196 event_on_one_release(event);
2197 }
2198 pthread_mutex_unlock(&event->mutex.mutex);
2199
2200 return status;
2201 }
2202
2203 /*
2204 * pj_event_set()
2205 */
2206 PJ_DEF(pj_status_t) pj_event_set(pj_event_t *event)
2207 {
2208 pthread_mutex_lock(&event->mutex.mutex);
2209 event->threads_to_release = 1;
2210 event->state = EV_STATE_SET;
2211 if (event->auto_reset)
2212 pthread_cond_signal(&event->cond);
2213 else
2214 pthread_cond_broadcast(&event->cond);
2215 pthread_mutex_unlock(&event->mutex.mutex);
2216 return PJ_SUCCESS;
2217 }
2218
2219 /*
2220 * pj_event_pulse()
2221 */
2222 PJ_DEF(pj_status_t) pj_event_pulse(pj_event_t *event)
2223 {
2224 pthread_mutex_lock(&event->mutex.mutex);
2225 if (event->threads_waiting) {
2226 event->threads_to_release = event->auto_reset ? 1 :
2227 event->threads_waiting;
2228 event->state = EV_STATE_PULSED;
2229 if (event->threads_to_release==1)
2230 pthread_cond_signal(&event->cond);
2231 else
2232 pthread_cond_broadcast(&event->cond);
2233 }
2234 pthread_mutex_unlock(&event->mutex.mutex);
2235 return PJ_SUCCESS;
2236 }
2237
2238 /*
2239 * pj_event_reset()
2240 */
2241 PJ_DEF(pj_status_t) pj_event_reset(pj_event_t *event)
2242 {
2243 pthread_mutex_lock(&event->mutex.mutex);
2244 event->state = EV_STATE_OFF;
2245 event->threads_to_release = 0;
2246 pthread_mutex_unlock(&event->mutex.mutex);
2247 return PJ_SUCCESS;
2248 }
2249
2250 /*
2251 * pj_event_destroy()
2252 */
2253 PJ_DEF(pj_status_t) pj_event_destroy(pj_event_t *event)
2254 {
2255 pj_mutex_destroy(&event->mutex);
2256 pthread_cond_destroy(&event->cond);
2257 return PJ_SUCCESS;
2258 }
2259
2260 #endif /* PJ_HAS_EVENT_OBJ */
2261
2262 ///////////////////////////////////////////////////////////////////////////////
2263 #if defined(_POSIX_BARRIERS) && _POSIX_BARRIERS >= 200112L
2264 /* pthread_barrier is supported. */
2265
2266 /**
2267 * Barrier object.
2268 */
2269 PJ_DEF(pj_status_t) pj_barrier_create(pj_pool_t *pool, unsigned trip_count, pj_barrier_t **p_barrier)
2270 {
2271 pj_barrier_t *barrier;
2272 int rc;
2273 PJ_ASSERT_RETURN(pool && p_barrier, PJ_EINVAL);
2274 barrier = (pj_barrier_t *)pj_pool_zalloc(pool, sizeof(pj_barrier_t));
2275 if (barrier == NULL)
2276 return PJ_ENOMEM;
2277 rc = pthread_barrier_init(&barrier->barrier, NULL, trip_count);
2278 if (rc == 0)
2279 *p_barrier = barrier;
2280 return PJ_STATUS_FROM_OS(rc);
2281 }
2282
2283 /**
2284 * Wait on the barrier.
2285 */
2286 PJ_DEF(pj_int32_t) pj_barrier_wait(pj_barrier_t *barrier, pj_uint32_t flags)
2287 {
2288 int rc;
2289
2290 PJ_UNUSED_ARG(flags);
2291 rc = pthread_barrier_wait(&barrier->barrier);
2292 switch (rc) {
2293 case 0:
2294 return PJ_FALSE;
2295 case PTHREAD_BARRIER_SERIAL_THREAD:
2296 return PJ_TRUE;
2297 default:
2298 return PJ_STATUS_FROM_OS(rc);
2299 }
2300 }
2301
2302 /**
2303 * Destroy the barrier.
2304 */
2305 PJ_DEF(pj_status_t) pj_barrier_destroy(pj_barrier_t *barrier)
2306 {
2307 int status = pthread_barrier_destroy(&barrier->barrier);
2308 return PJ_STATUS_FROM_OS(status);
2309 }
2310
2311 #else // _POSIX_BARRIERS
2312 /* pthread_barrier is not supported. */
2313
2314 /**
2315 * Barrier object.
2316 */
2317 PJ_DEF(pj_status_t) pj_barrier_create(pj_pool_t *pool, unsigned trip_count, pj_barrier_t **p_barrier)
2318 {
2319 pj_barrier_t *barrier;
2320 pj_status_t status;
2321 int rc;
2322
2323 PJ_ASSERT_RETURN(pool && p_barrier, PJ_EINVAL);
2324 barrier = (pj_barrier_t*)pj_pool_zalloc(pool, sizeof(pj_barrier_t));
2325 if (barrier == NULL)
2326 return PJ_ENOMEM;
2327
2328 rc = pthread_cond_init(&barrier->cond, NULL);
2329 if ((status = PJ_STATUS_FROM_OS(rc)) == PJ_SUCCESS) {
2330 status = init_mutex(&barrier->mutex, "barrier%p", PJ_MUTEX_SIMPLE);
2331 if (status != PJ_SUCCESS) {
2332 rc = pthread_cond_destroy(&barrier->cond);
2333 pj_assert(!rc);
2334 } else {
2335 barrier->count = 0;
2336 barrier->trip_count = trip_count;
2337 *p_barrier = barrier;
2338 }
2339 }
2340 return status;
2341 }
2342
2343 /**
2344 * Wait on the barrier.
2345 */
2346 PJ_DEF(pj_int32_t) pj_barrier_wait(pj_barrier_t *barrier, pj_uint32_t flags)
2347 {
2348 pj_bool_t is_last = PJ_FALSE;
2349 int status;
2350
2351 PJ_UNUSED_ARG(flags);
2352
2353 pthread_mutex_lock(&barrier->mutex.mutex);
2354 if (++barrier->count >= barrier->trip_count) {
2355 barrier->count = 0;
2356 status = pthread_cond_broadcast(&barrier->cond);
2357 is_last = PJ_TRUE;
2358 } else {
2359 status = pthread_cond_wait(&barrier->cond, &barrier->mutex.mutex);
2360 }
2361 pthread_mutex_unlock(&barrier->mutex.mutex);
2362
2363 return !status ? is_last : PJ_STATUS_FROM_OS(status);
2364 }
2365
2366 /**
2367 * Destroy the barrier.
2368 */
2369 PJ_DEF(pj_status_t) pj_barrier_destroy(pj_barrier_t *barrier)
2370 {
2371 int status = pthread_cond_destroy(&barrier->cond);
2372 pj_assert(!status);
2373 PJ_UNUSED_ARG(status);
2374 return pj_mutex_destroy(&barrier->mutex);
2375 }
2376
2377 #endif // _POSIX_BARRIERS
2378
2379
2380 ///////////////////////////////////////////////////////////////////////////////
2381 #if defined(PJ_TERM_HAS_COLOR) && PJ_TERM_HAS_COLOR != 0
2382 /*
2383 * Terminal
2384 */
2385
2386 /**
2387 * Set terminal color.
2388 */
2389 PJ_DEF(pj_status_t) pj_term_set_color(pj_color_t color)
2390 {
2391 /* put bright prefix to ansi_color */
2392 char ansi_color[12] = "\033[01;3";
2393
2394 if (color & PJ_TERM_COLOR_BRIGHT) {
2395 color ^= PJ_TERM_COLOR_BRIGHT;
2396 } else {
2397 pj_ansi_strxcpy(ansi_color, "\033[00;3", sizeof(ansi_color));
2398 }
2399
2400 switch (color) {
2401 case 0:
2402 /* black color */
2403 pj_ansi_strxcat(ansi_color, "0m", sizeof(ansi_color));
2404 break;
2405 case PJ_TERM_COLOR_R:
2406 /* red color */
2407 pj_ansi_strxcat(ansi_color, "1m", sizeof(ansi_color));
2408 break;
2409 case PJ_TERM_COLOR_G:
2410 /* green color */
2411 pj_ansi_strxcat(ansi_color, "2m", sizeof(ansi_color));
2412 break;
2413 case PJ_TERM_COLOR_B:
2414 /* blue color */
2415 pj_ansi_strxcat(ansi_color, "4m", sizeof(ansi_color));
2416 break;
2417 case PJ_TERM_COLOR_R | PJ_TERM_COLOR_G:
2418 /* yellow color */
2419 pj_ansi_strxcat(ansi_color, "3m", sizeof(ansi_color));
2420 break;
2421 case PJ_TERM_COLOR_R | PJ_TERM_COLOR_B:
2422 /* magenta color */
2423 pj_ansi_strxcat(ansi_color, "5m", sizeof(ansi_color));
2424 break;
2425 case PJ_TERM_COLOR_G | PJ_TERM_COLOR_B:
2426 /* cyan color */
2427 pj_ansi_strxcat(ansi_color, "6m", sizeof(ansi_color));
2428 break;
2429 case PJ_TERM_COLOR_R | PJ_TERM_COLOR_G | PJ_TERM_COLOR_B:
2430 /* white color */
2431 pj_ansi_strxcat(ansi_color, "7m", sizeof(ansi_color));
2432 break;
2433 default:
2434 /* default console color */
2435 pj_ansi_strxcpy(ansi_color, "\033[00m", sizeof(ansi_color));
2436 break;
2437 }
2438
2439 fputs(ansi_color, stdout);
2440
2441 return PJ_SUCCESS;
2442 }
2443
2444 /**
2445 * Get current terminal foreground color.
2446 */
2447 PJ_DEF(pj_color_t) pj_term_get_color(void)
2448 {
2449 return 0;
2450 }
2451
2452 #endif /* PJ_TERM_HAS_COLOR */
2453
2454 #if !defined(PJ_DARWINOS) || PJ_DARWINOS == 0
2455 /*
2456 * pj_run_app()
2457 */
2458 PJ_DEF(int) pj_run_app(pj_main_func_ptr main_func, int argc, char *argv[],
2459 unsigned flags)
2460 {
2461 PJ_UNUSED_ARG(flags);
2462 return (*main_func)(argc, argv);
2463 }
2464 #endif
2465
2466 /*
2467 * Set file descriptor close-on-exec flag
2468 */
2469 PJ_DEF(pj_status_t) pj_set_cloexec_flag(int fd)
2470 {
2471 #if defined(FD_CLOEXEC)
2472 int flags = fcntl(fd, F_GETFD);
2473 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
2474 return PJ_RETURN_OS_ERROR(pj_get_native_netos_error());
2475 }
2476 #endif
2477 return PJ_SUCCESS;
2478 }