Debian Codegraph @

Xpjproject/pjlib/src/pj/os_core_win32.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 #include <pj/os.h>
20 #include <pj/pool.h>
21 #include <pj/log.h>
22 #include <pj/string.h>
23 #include <pj/guid.h>
24 #include <pj/rand.h>
25 #include <pj/assert.h>
26 #include <pj/errno.h>
27 #include <pj/except.h>
28 #include <pj/unicode.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32
33 #include <windows.h>
34 #include <process.h>
35
36 #if defined(PJ_HAS_WINSOCK2_H) && PJ_HAS_WINSOCK2_H != 0
37 # include <winsock2.h>
38 #elif defined(PJ_HAS_WINSOCK_H) && PJ_HAS_WINSOCK_H != 0
39 # include <winsock.h>
40 #endif
41
42 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
43 # include "../../../third_party/threademulation/include/ThreadEmulation.h"
44 #endif
45
46 /* Activate mutex related logging if PJ_DEBUG_MUTEX is set, otherwise
47 * use default level 6 logging.
48 */
49 #if defined(PJ_DEBUG_MUTEX) && PJ_DEBUG_MUTEX
50 # undef PJ_DEBUG
51 # define PJ_DEBUG 1
52 # define LOG_MUTEX(expr) PJ_LOG(5,expr)
53 #else
54 # define LOG_MUTEX(expr) PJ_LOG(6,expr)
55 #endif
56 # define LOG_MUTEX_WARN(expr) PJ_PERROR(3,expr)
57 #define THIS_FILE "os_core_win32.c"
58
59 /*
60 * Implementation of pj_thread_t.
61 */
62 struct pj_thread_t
63 {
64 char obj_name[PJ_MAX_OBJ_NAME];
65 HANDLE hthread;
66 DWORD idthread;
67 pj_thread_proc *proc;
68 void *arg;
69
70 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
71 pj_uint32_t stk_size;
72 pj_uint32_t stk_max_usage;
73 char *stk_start;
74 const char *caller_file;
75 int caller_line;
76 #endif
77 };
78
79
80 /*
81 * Implementation of pj_mutex_t.
82 */
83 struct pj_mutex_t
84 {
85 #if PJ_WIN32_WINNT >= 0x0400
86 CRITICAL_SECTION crit;
87 #else
88 HANDLE hMutex;
89 #endif
90 char obj_name[PJ_MAX_OBJ_NAME];
91 #if PJ_DEBUG
92 int nesting_level;
93 pj_thread_t *owner;
94 #endif
95 };
96
97 /*
98 * Implementation of pj_sem_t.
99 */
100 typedef struct pj_sem_t
101 {
102 HANDLE hSemaphore;
103 char obj_name[PJ_MAX_OBJ_NAME];
104 } pj_mem_t;
105
106
107 /*
108 * Implementation of pj_event_t.
109 */
110 struct pj_event_t
111 {
112 HANDLE hEvent;
113 char obj_name[PJ_MAX_OBJ_NAME];
114 };
115
116 /*
117 * Implementation of pj_atomic_t.
118 */
119 struct pj_atomic_t
120 {
121 long value;
122 };
123
124 /*
125 * Implementation of pj_barrier_t.
126 */
127 #if PJ_WIN32_WINNT >= _WIN32_WINNT_WIN8
128 struct pj_barrier_t {
129 SYNCHRONIZATION_BARRIER sync_barrier;
130 };
131 #elif PJ_WIN32_WINNT >= _WIN32_WINNT_VISTA
132 struct pj_barrier_t {
133 CRITICAL_SECTION mutex;
134 CONDITION_VARIABLE cond;
135 unsigned count;
136 unsigned waiting;
137 };
138 #else
139 struct pj_barrier_t {
140 HANDLE cond; /* Semaphore */
141 LONG count; /* Number of threads required to pass the barrier */
142 LONG waiting;/* Number of threads waiting at the barrier */
143 };
144 #endif
145
146 /*
147 * Flag and reference counter for PJLIB instance.
148 */
149 static int initialized;
150
151 /*
152 * Static global variables.
153 */
154 static pj_thread_desc main_thread;
155 static long thread_tls_id = -1;
156 static pj_mutex_t critical_section_mutex;
157 static unsigned atexit_count;
158 static void (*atexit_func[32])(void);
159
160 /*
161 * Some static prototypes.
162 */
163 static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name);
164
165 static void load_set_thread_description();
166 static void set_thread_display_name(const char *name);
167
168
169 /*
170 * pj_init(void).
171 * Init PJLIB!
172 */
173 PJ_DEF(pj_status_t) pj_init(void)
174 {
175 WSADATA wsa;
176 char dummy_guid[32]; /* use maximum GUID length */
177 pj_str_t guid;
178 pj_status_t rc;
179
180 /* Check if PJLIB have been initialized */
181 if (initialized) {
182 ++initialized;
183 return PJ_SUCCESS;
184 }
185
186 /* Init Winsock.. */
187 if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) {
188 return PJ_RETURN_OS_ERROR(WSAGetLastError());
189 }
190
191 /* load SetThreadDescription before setting thread name in pj_thread_init() call */
192 load_set_thread_description();
193
194 /* Init this thread's TLS. */
195 if ((rc=pj_thread_init()) != PJ_SUCCESS) {
196 return rc;
197 }
198
199 /* Init logging */
200 pj_log_init();
201
202 /* Init random seed. */
203 /* Or probably not. Let application in charge of this */
204 /* pj_srand( GetCurrentProcessId() ); */
205
206 /* Initialize critical section. */
207 if ((rc=init_mutex(&critical_section_mutex, "pj%p")) != PJ_SUCCESS)
208 return rc;
209
210 /* Startup GUID. */
211 guid.ptr = dummy_guid;
212 pj_generate_unique_string( &guid );
213
214 /* Initialize exception ID for the pool.
215 * Must do so after critical section is configured.
216 */
217 rc = pj_exception_id_alloc("PJLIB/No memory", &PJ_NO_MEMORY_EXCEPTION);
218 if (rc != PJ_SUCCESS)
219 return rc;
220
221 /* Startup timestamp */
222 #if defined(PJ_HAS_HIGH_RES_TIMER) && PJ_HAS_HIGH_RES_TIMER != 0
223 {
224 pj_timestamp dummy_ts;
225 if ((rc=pj_get_timestamp_freq(&dummy_ts)) != PJ_SUCCESS) {
226 return rc;
227 }
228 if ((rc=pj_get_timestamp(&dummy_ts)) != PJ_SUCCESS) {
229 return rc;
230 }
231 }
232 #endif
233
234 /* Flag PJLIB as initialized */
235 ++initialized;
236 pj_assert(initialized == 1);
237
238 PJ_LOG(4,(THIS_FILE, "pjlib %s for win32 initialized",
239 PJ_VERSION));
240
241 return PJ_SUCCESS;
242 }
243
244 /*
245 * pj_atexit()
246 */
247 PJ_DEF(pj_status_t) pj_atexit(void (*func)(void))
248 {
249 if (atexit_count >= PJ_ARRAY_SIZE(atexit_func))
250 return PJ_ETOOMANY;
251
252 atexit_func[atexit_count++] = func;
253 return PJ_SUCCESS;
254 }
255
256
257 /*
258 * pj_shutdown(void)
259 */
260 PJ_DEF(void) pj_shutdown()
261 {
262 int i;
263
264 /* Only perform shutdown operation when 'initialized' reaches zero */
265 pj_assert(initialized > 0);
266 if (--initialized != 0)
267 return;
268
269 /* Display stack usage */
270 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
271 {
272 pj_thread_t *rec = (pj_thread_t*)main_thread;
273 PJ_LOG(5,(rec->obj_name, "Main thread stack max usage=%u by %s:%d",
274 rec->stk_max_usage, rec->caller_file, rec->caller_line));
275 }
276 #endif
277
278 /* Call atexit() functions */
279 for (i=atexit_count-1; i>=0; --i) {
280 (*atexit_func[i])();
281 }
282 atexit_count = 0;
283
284 /* Free exception ID */
285 if (PJ_NO_MEMORY_EXCEPTION != -1) {
286 pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION);
287 PJ_NO_MEMORY_EXCEPTION = -1;
288 }
289
290 /* Destroy PJLIB critical section */
291 pj_mutex_destroy(&critical_section_mutex);
292
293 /* Free PJLIB TLS */
294 if (thread_tls_id != -1) {
295 if (pj_thread_this() == (pj_thread_t*)main_thread)
296 pj_thread_unregister();
297 pj_thread_local_free(thread_tls_id);
298 thread_tls_id = -1;
299 }
300
301 /* Clear static variables */
302 pj_errno_clear_handlers();
303
304 /* Ticket #1132: Assertion when (re)starting PJLIB on different thread */
305 pj_bzero(main_thread, sizeof(main_thread));
306
307 /* Shutdown Winsock */
308 WSACleanup();
309 }
310
311
312 /*
313 * pj_getpid(void)
314 */
315 PJ_DEF(pj_uint32_t) pj_getpid(void)
316 {
317 PJ_CHECK_STACK();
318 return GetCurrentProcessId();
319 }
320
321 /*
322 * Check if this thread has been registered to PJLIB.
323 */
324 PJ_DEF(pj_bool_t) pj_thread_is_registered(void)
325 {
326 return pj_thread_local_get(thread_tls_id) != 0;
327 }
328
329
330 /*
331 * Get thread priority value for the thread.
332 */
333 PJ_DEF(int) pj_thread_get_prio(pj_thread_t *thread)
334 {
335 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
336 PJ_UNUSED_ARG(thread);
337 return -1;
338 #else
339 return GetThreadPriority(thread->hthread);
340 #endif
341 }
342
343
344 /*
345 * Set the thread priority.
346 */
347 PJ_DEF(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio)
348 {
349 #if PJ_HAS_THREADS
350 PJ_ASSERT_RETURN(thread, PJ_EINVAL);
351 PJ_ASSERT_RETURN(prio>=THREAD_PRIORITY_IDLE &&
352 prio<=THREAD_PRIORITY_TIME_CRITICAL,
353 PJ_EINVAL);
354
355 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
356 if (SetThreadPriorityRT(thread->hthread, prio) == FALSE)
357 #else
358 if (SetThreadPriority(thread->hthread, prio) == FALSE)
359 #endif
360 return PJ_RETURN_OS_ERROR(GetLastError());
361
362 return PJ_SUCCESS;
363
364 #else
365 PJ_UNUSED_ARG(thread);
366 PJ_UNUSED_ARG(prio);
367 pj_assert("pj_thread_set_prio() called in non-threading mode!");
368 return PJ_EINVALIDOP;
369 #endif
370 }
371
372
373 /*
374 * Get the lowest priority value available on this system.
375 */
376 PJ_DEF(int) pj_thread_get_prio_min(pj_thread_t *thread)
377 {
378 PJ_UNUSED_ARG(thread);
379 return THREAD_PRIORITY_IDLE;
380 }
381
382
383 /*
384 * Get the highest priority value available on this system.
385 */
386 PJ_DEF(int) pj_thread_get_prio_max(pj_thread_t *thread)
387 {
388 PJ_UNUSED_ARG(thread);
389 return THREAD_PRIORITY_TIME_CRITICAL;
390 }
391
392
393 /*
394 * Get native thread handle
395 */
396 PJ_DEF(void*) pj_thread_get_os_handle(pj_thread_t *thread)
397 {
398 PJ_ASSERT_RETURN(thread, NULL);
399
400 #if PJ_HAS_THREADS
401 PJ_ASSERT_ON_FAIL(thread->hthread != GetCurrentThread(),
402 PJ_LOG(1, (THIS_FILE, "Can not use pseudo handle of the thread %s on other threads", thread->obj_name)));
403 return thread->hthread;
404 #else
405 pj_assert("pj_thread_is_registered() called in non-threading mode!");
406 return NULL;
407 #endif
408 }
409
410 /*
411 * pj_thread_register(..)
412 */
413 PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name,
414 pj_thread_desc desc,
415 pj_thread_t **thread_ptr)
416 {
417 char stack_ptr;
418 pj_status_t rc;
419 pj_thread_t *thread = (pj_thread_t *)desc;
420 pj_str_t thread_name = pj_str((char*)cstr_thread_name);
421
422 _STATIC_ASSERT(sizeof(pj_thread_desc) >= sizeof(pj_thread_t));
423
424 /* Size sanity check. */
425 if (sizeof(pj_thread_desc) < sizeof(pj_thread_t)) {
426 pj_assert(!"Not enough pj_thread_desc size!");
427 return PJ_EBUG;
428 }
429
430 //pj_assert(pj_thread_local_get(thread_tls_id) == NULL);
431
432 /* If a thread descriptor has been registered before, just return it. */
433 if (pj_thread_local_get (thread_tls_id) != 0) {
434 // 2006-02-26 bennylp:
435 // This wouldn't work in all cases!.
436 // If thread is created by external module (e.g. sound thread),
437 // thread may be reused while the pool used for the thread descriptor
438 // has been deleted by application.
439 //*thread_ptr = (pj_thread_t*)pj_thread_local_get (thread_tls_id);
440 //return PJ_SUCCESS;
441 PJ_LOG(4,(THIS_FILE, "Info: possibly re-registering existing "
442 "thread"));
443 }
444
445 /* Initialize and set the thread entry. */
446 pj_bzero(desc, sizeof(struct pj_thread_t));
447
448 //GetCurrentThread() returns the same pseudo-handle for all threads.
449 //The program will go into an infinite wait state if someone tries to
450 //pj_thread_join() to the thread_ptr registered here.
451 //If someone wants to use pj_thread_join() for thread registered here, they
452 //should call DuplicateHandle() here and properly CloseHandle() after using.
453 thread->hthread = GetCurrentThread();
454
455 thread->idthread = GetCurrentThreadId();
456
457 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
458 thread->stk_start = &stack_ptr;
459 thread->stk_size = 0xFFFFFFFFUL;
460 thread->stk_max_usage = 0;
461 #else
462 PJ_UNUSED_ARG(stack_ptr);
463 #endif
464
465 if (cstr_thread_name && pj_strlen(&thread_name) < sizeof(thread->obj_name)-1)
466 pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name),
467 cstr_thread_name, thread->idthread);
468 else
469 pj_ansi_snprintf(thread->obj_name, sizeof(thread->obj_name),
470 "thr%p", (void*)(pj_ssize_t)thread->idthread);
471
472 rc = pj_thread_local_set(thread_tls_id, thread);
473 if (rc != PJ_SUCCESS)
474 return rc;
475
476 set_thread_display_name(thread->obj_name);
477
478 *thread_ptr = thread;
479 return PJ_SUCCESS;
480 }
481
482 /*
483 * pj_thread_init(void)
484 */
485 pj_status_t pj_thread_init(void)
486 {
487 pj_status_t rc;
488 pj_thread_t *thread;
489
490 rc = pj_thread_local_alloc(&thread_tls_id);
491 if (rc != PJ_SUCCESS)
492 return rc;
493
494 return pj_thread_register("thr%p", main_thread, &thread);
495 }
496
497 /*
498 * Set current thread display name
499 * MSDN document:
500 * https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code
501 */
502 #pragma pack(push, 8)
503 typedef struct tagTHREADNAME_INFO {
504 DWORD dwType; // Must be 0x1000.
505 LPCSTR szName; // Pointer to name (in user addr space).
506 DWORD dwThreadID; // Thread ID (-1=caller thread).
507 DWORD dwFlags; // Reserved for future use, must be zero.
508 } THREADNAME_INFO;
509 #pragma pack(pop)
510
511 // The SetThreadDescription and GetThreadDescription API was brought
512 // in Windows Server 2016 or version 1607 of Windows 10.
513 typedef HRESULT(WINAPI* LPFN_SETTHREADDESCRIPTION)(_In_ HANDLE hThread,
514 _In_ PCWSTR lpThreadDescription);
515 typedef HRESULT(WINAPI* LPFN_GETTHREADDESCRIPTION)(_In_ HANDLE hThread,
516 _Outptr_result_z_ PWSTR* ppszThreadDescription);
517
518 static LPFN_SETTHREADDESCRIPTION pSetThreadDescription = NULL;
519 static LPFN_GETTHREADDESCRIPTION pGetThreadDescription = NULL;
520
521 static void load_set_thread_description()
522 {
523 #if !(defined(PJ_WIN32_UWP) && PJ_WIN32_UWP!=0) || \
524 (defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8!=0)
525
526 /* Windows Server 2016, Windows 10 LTSB 2016 and Windows 10 version 1607: SetThreadDescription is only available by
527 * Runtime Dynamic Linking in KernelBase.dll.
528 */
529 LPCTSTR module[] = {TEXT("Kernel32.dll"), TEXT("KernelBase.dll")};
530 size_t i;
531 for (i = 0; (pSetThreadDescription == NULL || pGetThreadDescription == NULL) && i < PJ_ARRAY_SIZE(module); ++i) {
532 HMODULE hModule = GetModuleHandle(module[i]);
533 if (hModule) {
534 pSetThreadDescription = (LPFN_SETTHREADDESCRIPTION)GetProcAddress(hModule, "SetThreadDescription");
535 pGetThreadDescription = (LPFN_GETTHREADDESCRIPTION)GetProcAddress(hModule, "GetThreadDescription");
536 }
537 }
538 #endif
539 }
540
541
542 static void set_thread_display_name(const char *name)
543 {
544 #if (defined(PJ_WIN32_UWP) && PJ_WIN32_UWP!=0) || \
545 (defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8!=0)
546
547 return;
548
549 #else
550
551 if (pSetThreadDescription) {
552 wchar_t wname[PJ_MAX_OBJ_NAME];
553 HRESULT hr;
554 pj_ansi_to_unicode(name, (int)pj_ansi_strlen(name), wname,
555 PJ_MAX_OBJ_NAME);
556
557 /* Set thread name by SetThreadDescription (if support) */
558 hr = pSetThreadDescription(GetCurrentThread(), wname);
559 pj_assert(SUCCEEDED(hr));
560 PJ_UNUSED_ARG(hr);
561
562 #if 0
563 PWSTR data;
564 hr = pGetThreadDescription(GetCurrentThread(), &data);
565 if (SUCCEEDED(hr))
566 LocalFree(data);
567 #endif
568 /* Thread names are visible when performing post-modern debugging
569 * by loading a crash dump in Visual Studio.
570 * But thread names are only visible in
571 * Visual Studio 2017 version 15.6 and later versions.
572 *
573 * And the thread names are not visible even in VS 2022,
574 * if remote debugging is running on Windows Server 2016.
575 *
576 * So additionally let's set a thread name by throwing an exception.
577 */
578 }
579
580 /* Set thread name by throwing an exception */
581 #if defined(__MINGW32__) || defined(__CYGWIN__)
582 #pragma message("Warning: Not support exception")
583 #else
584 // The debugger needs to be around to catch the name in the exception.
585 // If there isn't a debugger, we are needlessly throwing an exception.
586 if (!IsDebuggerPresent()) {
587 return;
588 }
589
590 {
591 const DWORD MS_VC_EXCEPTION = 0x406D1388;
592 THREADNAME_INFO info;
593 info.dwType = 0x1000;
594 info.szName = name;
595 info.dwThreadID = (DWORD)-1;
596 info.dwFlags = 0;
597 #pragma warning(push)
598 #pragma warning(disable : 6320 6322)
599 __try {
600 RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR),
601 (ULONG_PTR *)&info);
602 } __except (EXCEPTION_EXECUTE_HANDLER) {
603 }
604 #pragma warning(pop)
605 }
606 # endif
607
608 #endif
609 }
610
611 static unsigned WINAPI thread_main(void *param)
612 {
613 pj_thread_t *rec = param;
614 int result;
615
616 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
617 rec->stk_start = (char*)&rec;
618 #endif
619
620 if (pj_thread_local_set(thread_tls_id, rec) != PJ_SUCCESS) {
621 pj_assert(!"TLS is not set (pj_init() error?)");
622 }
623
624 PJ_LOG(6,(rec->obj_name, "Thread started"));
625
626 set_thread_display_name(rec->obj_name);
627
628 result = (*rec->proc)(rec->arg);
629
630 PJ_LOG(6,(rec->obj_name, "Thread quitting"));
631 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
632 PJ_LOG(5,(rec->obj_name, "Thread stack max usage=%u by %s:%d",
633 rec->stk_max_usage, rec->caller_file, rec->caller_line));
634 #endif
635
636 return result;
637 }
638
639 static pj_status_t create_thread(const char *thread_name,
640 pj_thread_proc *proc,
641 void *arg,
642 pj_size_t stack_size,
643 DWORD dwflags,
644 pj_thread_t *rec);
645
646 /*
647 * pj_thread_create(...)
648 */
649 PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool,
650 const char *thread_name,
651 pj_thread_proc *proc,
652 void *arg,
653 pj_size_t stack_size,
654 unsigned flags,
655 pj_thread_t **thread_ptr)
656 {
657 DWORD dwflags = 0;
658 pj_thread_t *rec;
659 pj_status_t status;
660
661 PJ_CHECK_STACK();
662 PJ_ASSERT_RETURN(pool && proc && thread_ptr, PJ_EINVAL);
663
664 /* Set flags */
665 if (flags & PJ_THREAD_SUSPENDED)
666 dwflags |= CREATE_SUSPENDED;
667
668 /* Create thread record and assign name for the thread */
669 rec = (struct pj_thread_t*) pj_pool_calloc(pool, 1, sizeof(pj_thread_t));
670 if (!rec)
671 return PJ_ENOMEM;
672
673 status = create_thread(thread_name, proc, arg, stack_size, dwflags, rec);
674 if (status == PJ_SUCCESS) {
675 /* Success! */
676 *thread_ptr = rec;
677 }
678 return status;
679 }
680
681 PJ_DEF(pj_status_t) pj_thread_create2(const char *thread_name,
682 pj_thread_proc *proc,
683 void *arg,
684 pj_size_t stack_size,
685 void *stack_addr,
686 pj_thread_t *thread)
687 {
688 PJ_CHECK_STACK();
689 PJ_ASSERT_RETURN(proc && thread, PJ_EINVAL);
690 PJ_UNUSED_ARG(stack_addr);
691
692 if (thread == pj_thread_this())
693 return PJ_ECANCELLED;
694
695 return create_thread(thread_name, proc, arg, stack_size, 0, thread);
696 }
697
698 static pj_status_t create_thread(const char *thread_name,
699 pj_thread_proc *proc,
700 void *arg,
701 pj_size_t stack_size,
702 DWORD dwflags,
703 pj_thread_t *rec)
704 {
705
706 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
707 PJ_UNUSED_ARG(stack_size);
708 #endif
709
710 PJ_CHECK_STACK();
711 PJ_ASSERT_RETURN(proc && rec, PJ_EINVAL);
712
713 /* Set name. */
714 if (!thread_name)
715 thread_name = "thr%p";
716
717 if (strchr(thread_name, '%')) {
718 pj_ansi_snprintf(rec->obj_name, PJ_MAX_OBJ_NAME, thread_name, rec);
719 } else {
720 pj_ansi_strxcpy(rec->obj_name, thread_name, PJ_MAX_OBJ_NAME);
721 }
722
723 PJ_LOG(6, (rec->obj_name, "Thread created"));
724
725 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0
726 rec->stk_size = stack_size ? (pj_uint32_t)stack_size : 0xFFFFFFFFUL;
727 rec->stk_max_usage = 0;
728 #endif
729
730 /* Create the thread. */
731 rec->proc = proc;
732 rec->arg = arg;
733
734 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
735 rec->hthread = CreateThreadRT(NULL, 0,
736 thread_main, rec,
737 dwflags, NULL);
738 #else
739 {
740 unsigned tid = 0;
741 rec->hthread = (HANDLE)_beginthreadex(NULL, (unsigned)stack_size,
742 thread_main, rec,
743 dwflags, &tid);
744 rec->idthread = tid;
745 }
746 #endif
747
748 if (rec->hthread == NULL)
749 return pj_get_os_error();
750
751 /* Success! */
752 return PJ_SUCCESS;
753 }
754
755 /*
756 * pj_thread-get_name()
757 */
758 PJ_DEF(const char*) pj_thread_get_name(pj_thread_t *p)
759 {
760 pj_thread_t *rec = (pj_thread_t*)p;
761
762 PJ_CHECK_STACK();
763 PJ_ASSERT_RETURN(p, "");
764
765 return rec->obj_name;
766 }
767
768 /*
769 * pj_thread_resume()
770 */
771 PJ_DEF(pj_status_t) pj_thread_resume(pj_thread_t *p)
772 {
773 pj_thread_t *rec = (pj_thread_t*)p;
774
775 PJ_CHECK_STACK();
776 PJ_ASSERT_RETURN(p, PJ_EINVAL);
777
778 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
779 if (ResumeThreadRT(rec->hthread) == (DWORD)-1)
780 #else
781 if (ResumeThread(rec->hthread) == (DWORD)-1)
782 #endif
783 return PJ_RETURN_OS_ERROR(GetLastError());
784 else
785 return PJ_SUCCESS;
786 }
787
788 /*
789 * pj_thread_this()
790 */
791 PJ_DEF(pj_thread_t*) pj_thread_this(void)
792 {
793 pj_thread_t *rec = pj_thread_local_get(thread_tls_id);
794
795 if (rec == NULL) {
796 pj_assert(!"Calling pjlib from unknown/external thread. You must "
797 "register external threads with pj_thread_register() "
798 "before calling any pjlib functions.");
799 }
800
801 /*
802 * MUST NOT check stack because this function is called
803 * by PJ_CHECK_STACK() itself!!!
804 *
805 */
806
807 return rec;
808 }
809
810 /*
811 * pj_thread_join()
812 */
813 PJ_DEF(pj_status_t) pj_thread_join(pj_thread_t *p)
814 {
815 pj_thread_t *rec = (pj_thread_t *)p;
816 DWORD rc;
817
818 PJ_CHECK_STACK();
819 PJ_ASSERT_RETURN(p, PJ_EINVAL);
820
821 if (p == pj_thread_this())
822 return PJ_ECANCELLED;
823
824 PJ_ASSERT_ON_FAIL(p->hthread != GetCurrentThread(), {
825 PJ_LOG(1, (THIS_FILE,
826 "Can not joining thread %s having a pseudo handle"
827 , p->obj_name));
828 return PJ_ETIMEDOUT;
829 });
830
831 PJ_LOG(6, (pj_thread_this()->obj_name, "Joining thread %s", p->obj_name));
832
833 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
834 rc = WaitForSingleObjectEx(rec->hthread, INFINITE, FALSE);
835 #else
836 rc = WaitForSingleObject(rec->hthread, INFINITE);
837 #endif
838
839 if (rc==WAIT_OBJECT_0)
840 return PJ_SUCCESS;
841 else if (rc==WAIT_TIMEOUT)
842 return PJ_ETIMEDOUT;
843 else
844 return PJ_RETURN_OS_ERROR(GetLastError());
845 }
846
847 /*
848 * pj_thread_unregister()
849 */
850 PJ_DEF(pj_status_t) pj_thread_unregister()
851 {
852 pj_status_t status;
853 pj_thread_t *rec;
854 PJ_CHECK_STACK();
855
856 rec = pj_thread_this();
857 PJ_ASSERT_RETURN(rec, PJ_EBUG);
858
859 if ((status = pj_thread_destroy(rec)) != PJ_SUCCESS)
860 return status;
861 else
862 return pj_thread_local_set(thread_tls_id, NULL);
863 }
864
865 PJ_DEF(pj_status_t) pj_thread_attach(const char *cstr_thread_name,
866 pj_thread_desc desc,
867 pj_thread_t **thread_ptr)
868 {
869 pj_status_t status;
870 if ((status = pj_thread_register(cstr_thread_name, desc, thread_ptr)) == PJ_SUCCESS &&
871 !DuplicateHandle(GetCurrentProcess(),
872 (*thread_ptr)->hthread,
873 GetCurrentProcess(),
874 &(*thread_ptr)->hthread,
875 0, FALSE,
876 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
877 {
878 status = pj_get_os_error();
879 }
880 return status;
881 }
882
883
884 /*
885 * pj_thread_destroy()
886 */
887 PJ_DEF(pj_status_t) pj_thread_destroy(pj_thread_t *p)
888 {
889 PJ_CHECK_STACK();
890 PJ_ASSERT_RETURN(p, PJ_EINVAL);
891
892 // As a general case CloseHandle() should not be called on pseudo-handles
893 // like the one returned by GetCurrentThread().
894 // However, CloseHandle() knows about GetCurrentThread()'s pseudo-handles,
895 // does nothing and returns non zero.
896 if (!CloseHandle(p->hthread))
897 return pj_get_os_error();
898 else
899 return PJ_SUCCESS;
900 }
901
902 /*
903 * pj_thread_sleep()
904 */
905 PJ_DEF(pj_status_t) pj_thread_sleep(unsigned msec)
906 {
907 PJ_CHECK_STACK();
908
909 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
910 SleepRT(msec);
911 #else
912 Sleep(msec);
913 #endif
914
915 return PJ_SUCCESS;
916 }
917
918 #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK != 0
919 /*
920 * pj_thread_check_stack()
921 * Implementation for PJ_CHECK_STACK()
922 */
923 PJ_DEF(void) pj_thread_check_stack(const char *file, int line)
924 {
925 char stk_ptr;
926 pj_uint32_t usage;
927 pj_thread_t *thread;
928
929 /* may be called after pj_thread_unregister() */
930 if (!pj_thread_is_registered())
931 return;
932
933 thread = pj_thread_this();
934
935 pj_assert(thread);
936
937 /* Calculate current usage. */
938 usage = (&stk_ptr > thread->stk_start) ?
939 (pj_uint32_t)(&stk_ptr - thread->stk_start) :
940 (pj_uint32_t)(thread->stk_start - &stk_ptr);
941
942 /* Assert if stack usage is dangerously high. */
943 pj_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128));
944
945 /* Keep statistic. */
946 if (usage > thread->stk_max_usage) {
947 thread->stk_max_usage = usage;
948 thread->caller_file = file;
949 thread->caller_line = line;
950 }
951
952 }
953
954 /*
955 * pj_thread_get_stack_max_usage()
956 */
957 PJ_DEF(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread)
958 {
959 return thread->stk_max_usage;
960 }
961
962 /*
963 * pj_thread_get_stack_info()
964 */
965 PJ_DEF(pj_status_t) pj_thread_get_stack_info( pj_thread_t *thread,
966 const char **file,
967 int *line )
968 {
969 pj_assert(thread);
970
971 *file = thread->caller_file;
972 *line = thread->caller_line;
973 return 0;
974 }
975
976 #endif /* PJ_OS_HAS_CHECK_STACK */
977
978
979 ///////////////////////////////////////////////////////////////////////////////
980
981 /*
982 * pj_atomic_create()
983 */
984 PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool,
985 pj_atomic_value_t initial,
986 pj_atomic_t **atomic_ptr)
987 {
988 pj_atomic_t *atomic_var = pj_pool_alloc(pool, sizeof(pj_atomic_t));
989 if (!atomic_var)
990 return PJ_ENOMEM;
991
992 atomic_var->value = initial;
993 *atomic_ptr = atomic_var;
994
995 return PJ_SUCCESS;
996 }
997
998 /*
999 * pj_atomic_destroy()
1000 */
1001 PJ_DEF(pj_status_t) pj_atomic_destroy( pj_atomic_t *var )
1002 {
1003 PJ_UNUSED_ARG(var);
1004 PJ_ASSERT_RETURN(var, PJ_EINVAL);
1005
1006 return 0;
1007 }
1008
1009 /*
1010 * pj_atomic_set()
1011 */
1012 PJ_DEF(void) pj_atomic_set( pj_atomic_t *atomic_var, pj_atomic_value_t value)
1013 {
1014 PJ_CHECK_STACK();
1015 PJ_ASSERT_ON_FAIL(atomic_var, return);
1016
1017 InterlockedExchange(&atomic_var->value, value);
1018 }
1019
1020 /*
1021 * pj_atomic_get()
1022 */
1023 PJ_DEF(pj_atomic_value_t) pj_atomic_get(pj_atomic_t *atomic_var)
1024 {
1025 PJ_CHECK_STACK();
1026 PJ_ASSERT_RETURN(atomic_var, 0);
1027
1028 return atomic_var->value;
1029 }
1030
1031 /*
1032 * pj_atomic_inc_and_get()
1033 */
1034 PJ_DEF(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var)
1035 {
1036 PJ_CHECK_STACK();
1037
1038 #if defined(PJ_WIN32_WINNT) && PJ_WIN32_WINNT >= 0x0400
1039 return InterlockedIncrement(&atomic_var->value);
1040 #else
1041 return InterlockedIncrement(&atomic_var->value);
1042 #endif
1043 }
1044
1045 /*
1046 * pj_atomic_inc()
1047 */
1048 PJ_DEF(void) pj_atomic_inc(pj_atomic_t *atomic_var)
1049 {
1050 PJ_ASSERT_ON_FAIL(atomic_var, return);
1051 pj_atomic_inc_and_get(atomic_var);
1052 }
1053
1054 /*
1055 * pj_atomic_dec_and_get()
1056 */
1057 PJ_DEF(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var)
1058 {
1059 PJ_CHECK_STACK();
1060
1061 #if defined(PJ_WIN32_WINNT) && PJ_WIN32_WINNT >= 0x0400
1062 return InterlockedDecrement(&atomic_var->value);
1063 #else
1064 return InterlockedDecrement(&atomic_var->value);
1065 #endif
1066 }
1067
1068 /*
1069 * pj_atomic_dec()
1070 */
1071 PJ_DEF(void) pj_atomic_dec(pj_atomic_t *atomic_var)
1072 {
1073 PJ_ASSERT_ON_FAIL(atomic_var, return);
1074 pj_atomic_dec_and_get(atomic_var);
1075 }
1076
1077 /*
1078 * pj_atomic_add()
1079 */
1080 PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var,
1081 pj_atomic_value_t value )
1082 {
1083 PJ_ASSERT_ON_FAIL(atomic_var, return);
1084 #if defined(PJ_WIN32_WINNT) && PJ_WIN32_WINNT >= 0x0400
1085 InterlockedExchangeAdd( &atomic_var->value, value );
1086 #else
1087 InterlockedExchangeAdd( &atomic_var->value, value );
1088 #endif
1089 }
1090
1091 /*
1092 * pj_atomic_add_and_get()
1093 */
1094 PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var,
1095 pj_atomic_value_t value)
1096 {
1097 #if defined(PJ_WIN32_WINNT) && PJ_WIN32_WINNT >= 0x0400
1098 long oldValue = InterlockedExchangeAdd( &atomic_var->value, value);
1099 return oldValue + value;
1100 #else
1101 long oldValue = InterlockedExchangeAdd( &atomic_var->value, value);
1102 return oldValue + value;
1103 #endif
1104 }
1105
1106 ///////////////////////////////////////////////////////////////////////////////
1107 /*
1108 * pj_thread_local_alloc()
1109 */
1110 PJ_DEF(pj_status_t) pj_thread_local_alloc(long *index)
1111 {
1112 DWORD tls_index;
1113 PJ_ASSERT_RETURN(index != NULL, PJ_EINVAL);
1114
1115 //Can't check stack because this function is called in the
1116 //beginning before main thread is initialized.
1117 //PJ_CHECK_STACK();
1118
1119 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1120 tls_index = TlsAllocRT();
1121 #else
1122 tls_index = TlsAlloc();
1123 #endif
1124
1125 if (tls_index == TLS_OUT_OF_INDEXES)
1126 return PJ_RETURN_OS_ERROR(GetLastError());
1127 else {
1128 *index = (long)tls_index;
1129 return PJ_SUCCESS;
1130 }
1131 }
1132
1133 /*
1134 * pj_thread_local_free()
1135 */
1136 PJ_DEF(void) pj_thread_local_free(long index)
1137 {
1138 PJ_CHECK_STACK();
1139 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1140 TlsFreeRT(index);
1141 #else
1142 TlsFree(index);
1143 #endif
1144 }
1145
1146 /*
1147 * pj_thread_local_set()
1148 */
1149 PJ_DEF(pj_status_t) pj_thread_local_set(long index, void *value)
1150 {
1151 BOOL rc;
1152
1153 //Can't check stack because this function is called in the
1154 //beginning before main thread is initialized.
1155 //PJ_CHECK_STACK();
1156
1157 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1158 rc = TlsSetValueRT(index, value);
1159 #else
1160 rc = TlsSetValue(index, value);
1161 #endif
1162
1163 return rc!=0 ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(GetLastError());
1164 }
1165
1166 /*
1167 * pj_thread_local_get()
1168 */
1169 PJ_DEF(void*) pj_thread_local_get(long index)
1170 {
1171 //Can't check stack because this function is called
1172 //by PJ_CHECK_STACK() itself!!!
1173 //PJ_CHECK_STACK();
1174 PJ_ASSERT_RETURN(index >= 0, NULL);
1175 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1176 return TlsGetValueRT(index);
1177 #else
1178 return TlsGetValue(index);
1179 #endif
1180 }
1181
1182 ///////////////////////////////////////////////////////////////////////////////
1183 static pj_status_t init_mutex(pj_mutex_t *mutex, const char *name)
1184 {
1185
1186 PJ_CHECK_STACK();
1187
1188 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1189 InitializeCriticalSectionEx(&mutex->crit, 0, 0);
1190 #elif PJ_WIN32_WINNT >= 0x0400
1191 InitializeCriticalSection(&mutex->crit);
1192 #else
1193 mutex->hMutex = CreateMutex(NULL, FALSE, NULL);
1194 if (!mutex->hMutex) {
1195 return PJ_RETURN_OS_ERROR(GetLastError());
1196 }
1197 #endif
1198
1199 #if PJ_DEBUG
1200 /* Set owner. */
1201 mutex->nesting_level = 0;
1202 mutex->owner = NULL;
1203 #endif
1204
1205 /* Set name. */
1206 if (!name) {
1207 name = "mtx%p";
1208 }
1209 if (strchr(name, '%')) {
1210 pj_ansi_snprintf(mutex->obj_name, PJ_MAX_OBJ_NAME, name, mutex);
1211 } else {
1212 pj_ansi_strxcpy(mutex->obj_name, name, PJ_MAX_OBJ_NAME);
1213 }
1214
1215 PJ_LOG(6, (mutex->obj_name, "Mutex created"));
1216 return PJ_SUCCESS;
1217 }
1218
1219 /*
1220 * pj_mutex_create()
1221 */
1222 PJ_DEF(pj_status_t) pj_mutex_create(pj_pool_t *pool,
1223 const char *name,
1224 int type,
1225 pj_mutex_t **mutex_ptr)
1226 {
1227 pj_status_t rc;
1228 pj_mutex_t *mutex;
1229
1230 PJ_UNUSED_ARG(type);
1231 PJ_ASSERT_RETURN(pool && mutex_ptr, PJ_EINVAL);
1232
1233 mutex = pj_pool_alloc(pool, sizeof(*mutex));
1234 if (!mutex)
1235 return PJ_ENOMEM;
1236
1237 rc = init_mutex(mutex, name);
1238 if (rc != PJ_SUCCESS)
1239 return rc;
1240
1241 *mutex_ptr = mutex;
1242
1243 return PJ_SUCCESS;
1244 }
1245
1246 /*
1247 * pj_mutex_create_simple()
1248 */
1249 PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool,
1250 const char *name,
1251 pj_mutex_t **mutex )
1252 {
1253 return pj_mutex_create(pool, name, PJ_MUTEX_SIMPLE, mutex);
1254 }
1255
1256 /*
1257 * pj_mutex_create_recursive()
1258 */
1259 PJ_DEF(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool,
1260 const char *name,
1261 pj_mutex_t **mutex )
1262 {
1263 return pj_mutex_create(pool, name, PJ_MUTEX_RECURSE, mutex);
1264 }
1265
1266 /*
1267 * pj_mutex_lock()
1268 */
1269 PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex)
1270 {
1271 pj_status_t status;
1272
1273 PJ_CHECK_STACK();
1274 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1275
1276 LOG_MUTEX((mutex->obj_name, "Mutex: thread %s is waiting",
1277 pj_thread_this()->obj_name));
1278
1279 #if PJ_WIN32_WINNT >= 0x0400
1280 EnterCriticalSection(&mutex->crit);
1281 status=PJ_SUCCESS;
1282 #else
1283 if (WaitForSingleObject(mutex->hMutex, INFINITE)==WAIT_OBJECT_0)
1284 status = PJ_SUCCESS;
1285 else
1286 status = PJ_STATUS_FROM_OS(GetLastError());
1287
1288 #endif
1289 if (status == PJ_SUCCESS) {
1290 LOG_MUTEX((mutex->obj_name,
1291 "Mutex acquired by thread %s",
1292 pj_thread_this()->obj_name));
1293 } else {
1294 LOG_MUTEX_WARN((mutex->obj_name, status,
1295 "Failed to acquire mutex by thread %s",
1296 pj_thread_this()->obj_name));
1297 }
1298 #if PJ_DEBUG
1299 if (status == PJ_SUCCESS) {
1300 mutex->owner = pj_thread_this();
1301 ++mutex->nesting_level;
1302 }
1303 #endif
1304
1305 return status;
1306 }
1307
1308 /*
1309 * pj_mutex_unlock()
1310 */
1311 PJ_DEF(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex)
1312 {
1313 pj_status_t status;
1314
1315 PJ_CHECK_STACK();
1316 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1317
1318 #if PJ_DEBUG
1319 pj_assert(mutex->owner == pj_thread_this());
1320 if (--mutex->nesting_level == 0) {
1321 mutex->owner = NULL;
1322 }
1323 #endif
1324
1325 LOG_MUTEX((mutex->obj_name, "Mutex released by thread %s",
1326 pj_thread_this()->obj_name));
1327
1328 #if PJ_WIN32_WINNT >= 0x0400
1329 LeaveCriticalSection(&mutex->crit);
1330 status=PJ_SUCCESS;
1331 #else
1332 status = ReleaseMutex(mutex->hMutex) ? PJ_SUCCESS :
1333 PJ_STATUS_FROM_OS(GetLastError());
1334 #endif
1335 return status;
1336 }
1337
1338 /*
1339 * pj_mutex_trylock()
1340 */
1341 PJ_DEF(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex)
1342 {
1343 pj_status_t status;
1344
1345 PJ_CHECK_STACK();
1346 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1347
1348 LOG_MUTEX((mutex->obj_name, "Mutex: thread %s is trying",
1349 pj_thread_this()->obj_name));
1350
1351 #if PJ_WIN32_WINNT >= 0x0400
1352 status=TryEnterCriticalSection(&mutex->crit) ? PJ_SUCCESS : PJ_EUNKNOWN;
1353 #else
1354 status = WaitForSingleObject(mutex->hMutex, 0)==WAIT_OBJECT_0 ?
1355 PJ_SUCCESS : PJ_ETIMEDOUT;
1356 #endif
1357 if (status==PJ_SUCCESS) {
1358 LOG_MUTEX((mutex->obj_name, "Mutex acquired by thread %s",
1359 pj_thread_this()->obj_name));
1360
1361 #if PJ_DEBUG
1362 mutex->owner = pj_thread_this();
1363 ++mutex->nesting_level;
1364 #endif
1365 } else {
1366 LOG_MUTEX((mutex->obj_name, "Mutex: thread %s's trylock() failed",
1367 pj_thread_this()->obj_name));
1368 }
1369
1370 return status;
1371 }
1372
1373 /*
1374 * pj_mutex_destroy()
1375 */
1376 PJ_DEF(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex)
1377 {
1378 PJ_CHECK_STACK();
1379 PJ_ASSERT_RETURN(mutex, PJ_EINVAL);
1380
1381 LOG_MUTEX((mutex->obj_name, "Mutex destroyed"));
1382
1383 #if PJ_WIN32_WINNT >= 0x0400
1384 DeleteCriticalSection(&mutex->crit);
1385 return PJ_SUCCESS;
1386 #else
1387 return CloseHandle(mutex->hMutex) ? PJ_SUCCESS :
1388 PJ_RETURN_OS_ERROR(GetLastError());
1389 #endif
1390 }
1391
1392 /*
1393 * pj_mutex_is_locked()
1394 */
1395 PJ_DEF(pj_bool_t) pj_mutex_is_locked(pj_mutex_t *mutex)
1396 {
1397 #if PJ_DEBUG
1398 return mutex->owner == pj_thread_this();
1399 #else
1400 PJ_UNUSED_ARG(mutex);
1401 pj_assert(!"PJ_DEBUG is not set!");
1402 return 1;
1403 #endif
1404 }
1405
1406 ///////////////////////////////////////////////////////////////////////////////
1407 /*
1408 * Win32 lacks Read/Write mutex, so include the emulation.
1409 */
1410 #include "os_rwmutex.c"
1411
1412 ///////////////////////////////////////////////////////////////////////////////
1413 /*
1414 * pj_enter_critical_section()
1415 */
1416 PJ_DEF(void) pj_enter_critical_section(void)
1417 {
1418 pj_mutex_lock(&critical_section_mutex);
1419 }
1420
1421
1422 /*
1423 * pj_leave_critical_section()
1424 */
1425 PJ_DEF(void) pj_leave_critical_section(void)
1426 {
1427 pj_mutex_unlock(&critical_section_mutex);
1428 }
1429
1430 ///////////////////////////////////////////////////////////////////////////////
1431 #if defined(PJ_HAS_SEMAPHORE) && PJ_HAS_SEMAPHORE != 0
1432
1433 /*
1434 * pj_sem_create()
1435 */
1436 PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool,
1437 const char *name,
1438 unsigned initial,
1439 unsigned max,
1440 pj_sem_t **sem_ptr)
1441 {
1442 pj_sem_t *sem;
1443
1444 PJ_CHECK_STACK();
1445 PJ_ASSERT_RETURN(pool && sem_ptr, PJ_EINVAL);
1446
1447 sem = pj_pool_alloc(pool, sizeof(*sem));
1448
1449 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1450 /** SEMAPHORE_ALL_ACCESS **/
1451 sem->hSemaphore = CreateSemaphoreEx(NULL, initial, max, NULL, 0,
1452 SEMAPHORE_ALL_ACCESS);
1453 #else
1454 sem->hSemaphore = CreateSemaphore(NULL, initial, max, NULL);
1455 #endif
1456
1457 if (!sem->hSemaphore)
1458 return PJ_RETURN_OS_ERROR(GetLastError());
1459
1460 /* Set name. */
1461 if (!name) {
1462 name = "sem%p";
1463 }
1464 if (strchr(name, '%')) {
1465 pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem);
1466 } else {
1467 pj_ansi_strxcpy(sem->obj_name, name, PJ_MAX_OBJ_NAME);
1468 }
1469
1470 LOG_MUTEX((sem->obj_name, "Semaphore created"));
1471
1472 *sem_ptr = sem;
1473 return PJ_SUCCESS;
1474 }
1475
1476 static pj_status_t pj_sem_wait_for(pj_sem_t *sem, unsigned timeout)
1477 {
1478 DWORD result;
1479 pj_status_t status = PJ_SUCCESS;
1480
1481 PJ_CHECK_STACK();
1482 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
1483
1484 LOG_MUTEX((sem->obj_name, "Semaphore: thread %s is waiting",
1485 pj_thread_this()->obj_name));
1486
1487 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1488 result = WaitForSingleObjectEx(sem->hSemaphore, timeout, FALSE);
1489 #else
1490 result = WaitForSingleObject(sem->hSemaphore, timeout);
1491 #endif
1492
1493 if (result == WAIT_OBJECT_0) {
1494 LOG_MUTEX((sem->obj_name, "Semaphore acquired by thread %s",
1495 pj_thread_this()->obj_name));
1496 } else {
1497 if (result == WAIT_TIMEOUT)
1498 status = PJ_ETIMEDOUT;
1499 else
1500 status = PJ_RETURN_OS_ERROR(GetLastError());
1501 LOG_MUTEX_WARN((sem->obj_name, status, "Semaphore: thread %s failed "
1502 "to acquire", pj_thread_this()->obj_name));
1503 }
1504
1505 return status;
1506 }
1507
1508 /*
1509 * pj_sem_wait()
1510 */
1511 PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem)
1512 {
1513 PJ_CHECK_STACK();
1514 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
1515
1516 return pj_sem_wait_for(sem, INFINITE);
1517 }
1518
1519 /*
1520 * pj_sem_trywait()
1521 */
1522 PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem)
1523 {
1524 PJ_CHECK_STACK();
1525 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
1526
1527 return pj_sem_wait_for(sem, 0);
1528 }
1529
1530 /*
1531 * pj_sem_post()
1532 */
1533 PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem)
1534 {
1535 PJ_CHECK_STACK();
1536 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
1537
1538 LOG_MUTEX((sem->obj_name, "Semaphore released by thread %s",
1539 pj_thread_this()->obj_name));
1540
1541 if (ReleaseSemaphore(sem->hSemaphore, 1, NULL))
1542 return PJ_SUCCESS;
1543 else
1544 return PJ_RETURN_OS_ERROR(GetLastError());
1545 }
1546
1547 /*
1548 * pj_sem_destroy()
1549 */
1550 PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem)
1551 {
1552 PJ_CHECK_STACK();
1553 PJ_ASSERT_RETURN(sem, PJ_EINVAL);
1554
1555 LOG_MUTEX((sem->obj_name, "Semaphore destroyed by thread %s",
1556 pj_thread_this()->obj_name));
1557
1558 if (CloseHandle(sem->hSemaphore))
1559 return PJ_SUCCESS;
1560 else
1561 return PJ_RETURN_OS_ERROR(GetLastError());
1562 }
1563
1564 #endif /* PJ_HAS_SEMAPHORE */
1565 ///////////////////////////////////////////////////////////////////////////////
1566
1567
1568 #if defined(PJ_HAS_EVENT_OBJ) && PJ_HAS_EVENT_OBJ != 0
1569
1570 /*
1571 * pj_event_create()
1572 */
1573 PJ_DEF(pj_status_t) pj_event_create( pj_pool_t *pool,
1574 const char *name,
1575 pj_bool_t manual_reset,
1576 pj_bool_t initial,
1577 pj_event_t **event_ptr)
1578 {
1579 pj_event_t *event;
1580
1581 PJ_CHECK_STACK();
1582 PJ_ASSERT_RETURN(pool && event_ptr, PJ_EINVAL);
1583
1584 event = pj_pool_alloc(pool, sizeof(*event));
1585 if (!event)
1586 return PJ_ENOMEM;
1587
1588 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1589 event->hEvent = CreateEventEx(NULL, NULL,
1590 (manual_reset? 0x1:0x0) | (initial? 0x2:0x0),
1591 EVENT_ALL_ACCESS);
1592 #else
1593 event->hEvent = CreateEvent(NULL, manual_reset ? TRUE : FALSE,
1594 initial ? TRUE : FALSE, NULL);
1595 #endif
1596
1597 if (!event->hEvent)
1598 return PJ_RETURN_OS_ERROR(GetLastError());
1599
1600 /* Set name. */
1601 if (!name) {
1602 name = "evt%p";
1603 }
1604 if (strchr(name, '%')) {
1605 pj_ansi_snprintf(event->obj_name, PJ_MAX_OBJ_NAME, name, event);
1606 } else {
1607 pj_ansi_strxcpy(event->obj_name, name, PJ_MAX_OBJ_NAME);
1608 }
1609
1610 PJ_LOG(6, (event->obj_name, "Event created"));
1611
1612 *event_ptr = event;
1613 return PJ_SUCCESS;
1614 }
1615
1616 static pj_status_t pj_event_wait_for(pj_event_t *event, unsigned timeout)
1617 {
1618 DWORD result;
1619
1620 PJ_CHECK_STACK();
1621 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1622
1623 PJ_LOG(6, (event->obj_name, "Event: thread %s is waiting",
1624 pj_thread_this()->obj_name));
1625
1626 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1627 result = WaitForSingleObjectEx(event->hEvent, timeout, FALSE);
1628 #else
1629 result = WaitForSingleObject(event->hEvent, timeout);
1630 #endif
1631
1632 if (result == WAIT_OBJECT_0) {
1633 PJ_LOG(6, (event->obj_name, "Event: thread %s is released",
1634 pj_thread_this()->obj_name));
1635 } else {
1636 PJ_LOG(6, (event->obj_name, "Event: thread %s FAILED to acquire",
1637 pj_thread_this()->obj_name));
1638 }
1639
1640 if (result==WAIT_OBJECT_0)
1641 return PJ_SUCCESS;
1642 else if (result==WAIT_TIMEOUT)
1643 return PJ_ETIMEDOUT;
1644 else
1645 return PJ_RETURN_OS_ERROR(GetLastError());
1646 }
1647
1648 /*
1649 * pj_event_wait()
1650 */
1651 PJ_DEF(pj_status_t) pj_event_wait(pj_event_t *event)
1652 {
1653 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1654
1655 return pj_event_wait_for(event, INFINITE);
1656 }
1657
1658 /*
1659 * pj_event_trywait()
1660 */
1661 PJ_DEF(pj_status_t) pj_event_trywait(pj_event_t *event)
1662 {
1663 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1664
1665 return pj_event_wait_for(event, 0);
1666 }
1667
1668 /*
1669 * pj_event_set()
1670 */
1671 PJ_DEF(pj_status_t) pj_event_set(pj_event_t *event)
1672 {
1673 PJ_CHECK_STACK();
1674 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1675
1676 PJ_LOG(6, (event->obj_name, "Setting event"));
1677
1678 if (SetEvent(event->hEvent))
1679 return PJ_SUCCESS;
1680 else
1681 return PJ_RETURN_OS_ERROR(GetLastError());
1682 }
1683
1684 /*
1685 * pj_event_pulse()
1686 */
1687 PJ_DEF(pj_status_t) pj_event_pulse(pj_event_t *event)
1688 {
1689 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1690 PJ_UNUSED_ARG(event);
1691 pj_assert(!"pj_event_pulse() not supported!");
1692 return PJ_ENOTSUP;
1693 #else
1694 PJ_CHECK_STACK();
1695 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1696
1697 PJ_LOG(6, (event->obj_name, "Pulsing event"));
1698
1699 if (PulseEvent(event->hEvent))
1700 return PJ_SUCCESS;
1701 else
1702 return PJ_RETURN_OS_ERROR(GetLastError());
1703 #endif
1704 }
1705
1706 /*
1707 * pj_event_reset()
1708 */
1709 PJ_DEF(pj_status_t) pj_event_reset(pj_event_t *event)
1710 {
1711 PJ_CHECK_STACK();
1712 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1713
1714 PJ_LOG(6, (event->obj_name, "Event is reset"));
1715
1716 if (ResetEvent(event->hEvent))
1717 return PJ_SUCCESS;
1718 else
1719 return PJ_RETURN_OS_ERROR(GetLastError());
1720 }
1721
1722 /*
1723 * pj_event_destroy()
1724 */
1725 PJ_DEF(pj_status_t) pj_event_destroy(pj_event_t *event)
1726 {
1727 PJ_CHECK_STACK();
1728 PJ_ASSERT_RETURN(event, PJ_EINVAL);
1729
1730 PJ_LOG(6, (event->obj_name, "Event is destroying"));
1731
1732 if (CloseHandle(event->hEvent))
1733 return PJ_SUCCESS;
1734 else
1735 return PJ_RETURN_OS_ERROR(GetLastError());
1736 }
1737
1738 #endif /* PJ_HAS_EVENT_OBJ */
1739
1740 ///////////////////////////////////////////////////////////////////////////////
1741
1742 /*
1743 * pj_barrier_create()
1744 */
1745 PJ_DEF(pj_status_t) pj_barrier_create(pj_pool_t *pool, unsigned trip_count, pj_barrier_t **p_barrier)
1746 {
1747 pj_barrier_t *barrier;
1748 PJ_ASSERT_RETURN(pool && p_barrier, PJ_EINVAL);
1749 barrier = (pj_barrier_t *)pj_pool_zalloc(pool, sizeof(pj_barrier_t));
1750 if (barrier == NULL)
1751 return PJ_ENOMEM;
1752 #if PJ_WIN32_WINNT >= _WIN32_WINNT_WIN8
1753 if (InitializeSynchronizationBarrier(&barrier->sync_barrier, trip_count, -1)) {
1754 *p_barrier = barrier;
1755 return PJ_SUCCESS;
1756 } else
1757 return pj_get_os_error();
1758 #elif PJ_WIN32_WINNT >= _WIN32_WINNT_VISTA
1759 InitializeCriticalSection(&barrier->mutex);
1760 InitializeConditionVariable(&barrier->cond);
1761 barrier->count = trip_count;
1762 barrier->waiting = 0;
1763 *p_barrier = barrier;
1764 return PJ_SUCCESS;
1765 #else
1766 barrier->cond = CreateSemaphore(NULL,
1767 0, /* initial count */
1768 trip_count, /* max count */
1769 NULL);
1770 if (!barrier->cond)
1771 return pj_get_os_error();
1772 barrier->count = trip_count;
1773 barrier->waiting = 0;
1774 *p_barrier = barrier;
1775 return PJ_SUCCESS;
1776 #endif
1777 }
1778
1779 /*
1780 * pj_barrier_destroy()
1781 */
1782 PJ_DEF(pj_status_t) pj_barrier_destroy(pj_barrier_t *barrier)
1783 {
1784 PJ_ASSERT_RETURN(barrier, PJ_EINVAL);
1785 #if PJ_WIN32_WINNT >= _WIN32_WINNT_WIN8
1786 DeleteSynchronizationBarrier(&barrier->sync_barrier);
1787 return PJ_SUCCESS;
1788 #elif PJ_WIN32_WINNT >= _WIN32_WINNT_VISTA
1789 DeleteCriticalSection(&barrier->mutex);
1790 return PJ_SUCCESS;
1791 #else
1792 if (CloseHandle(barrier->cond))
1793 return PJ_SUCCESS;
1794 else
1795 return pj_get_os_error();
1796 #endif
1797 }
1798
1799 /*
1800 * pj_barrier_wait()
1801 */
1802 PJ_DEF(pj_int32_t) pj_barrier_wait(pj_barrier_t *barrier, pj_uint32_t flags)
1803 {
1804 PJ_ASSERT_RETURN(barrier, PJ_EINVAL);
1805 #if PJ_WIN32_WINNT >= _WIN32_WINNT_WIN8
1806 DWORD dwFlags = ((flags & PJ_BARRIER_FLAGS_BLOCK_ONLY) ? SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY : 0) |
1807 ((flags & PJ_BARRIER_FLAGS_SPIN_ONLY) ? SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY : 0) |
1808 ((flags & PJ_BARRIER_FLAGS_NO_DELETE) ? SYNCHRONIZATION_BARRIER_FLAGS_NO_DELETE : 0);
1809 return EnterSynchronizationBarrier(&barrier->sync_barrier, dwFlags);
1810 #elif PJ_WIN32_WINNT >= _WIN32_WINNT_VISTA
1811 PJ_UNUSED_ARG(flags);
1812 EnterCriticalSection(&barrier->mutex);
1813 if (++barrier->waiting == barrier->count) {
1814 barrier->waiting = 0;
1815 LeaveCriticalSection(&barrier->mutex);
1816 WakeAllConditionVariable(&barrier->cond);
1817 return PJ_TRUE;
1818 } else {
1819 BOOL rc = SleepConditionVariableCS(&barrier->cond, &barrier->mutex, INFINITE);
1820 LeaveCriticalSection(&barrier->mutex);
1821 if (rc)
1822 /* Returning PJ_FALSE in this case (a successful return from
1823 * SleepConditionVariableCS) is intentional.
1824 */
1825 return PJ_FALSE;
1826 else
1827 return pj_get_os_error();
1828 }
1829 #else
1830 PJ_UNUSED_ARG(flags);
1831
1832 if (InterlockedIncrement(&barrier->waiting) == barrier->count) {
1833 LONG previousCount = 0;
1834 barrier->waiting = 0;
1835 /* Release all threads waiting on the semaphore */
1836 if (barrier->count == 1 ||
1837 ReleaseSemaphore(barrier->cond, barrier->count-1, &previousCount))
1838 {
1839 PJ_ASSERT_RETURN(previousCount == 0, PJ_EBUG);
1840 return PJ_TRUE;
1841 } else {
1842 return pj_get_os_error();
1843 }
1844 }
1845
1846 if (WaitForSingleObject(barrier->cond, INFINITE) == WAIT_OBJECT_0)
1847 return PJ_FALSE;
1848 else
1849 return pj_get_os_error();
1850 #endif
1851 }
1852
1853 ///////////////////////////////////////////////////////////////////////////////
1854 #if defined(PJ_TERM_HAS_COLOR) && PJ_TERM_HAS_COLOR != 0
1855 /*
1856 * Terminal color
1857 */
1858
1859 static WORD pj_color_to_os_attr(pj_color_t color)
1860 {
1861 WORD attr = 0;
1862
1863 if (color & PJ_TERM_COLOR_R)
1864 attr |= FOREGROUND_RED;
1865 if (color & PJ_TERM_COLOR_G)
1866 attr |= FOREGROUND_GREEN;
1867 if (color & PJ_TERM_COLOR_B)
1868 attr |= FOREGROUND_BLUE;
1869 if (color & PJ_TERM_COLOR_BRIGHT)
1870 attr |= FOREGROUND_INTENSITY;
1871
1872 return attr;
1873 }
1874
1875 static pj_color_t os_attr_to_pj_color(WORD attr)
1876 {
1877 int color = 0;
1878
1879 if (attr & FOREGROUND_RED)
1880 color |= PJ_TERM_COLOR_R;
1881 if (attr & FOREGROUND_GREEN)
1882 color |= PJ_TERM_COLOR_G;
1883 if (attr & FOREGROUND_BLUE)
1884 color |= PJ_TERM_COLOR_B;
1885 if (attr & FOREGROUND_INTENSITY)
1886 color |= PJ_TERM_COLOR_BRIGHT;
1887
1888 return color;
1889 }
1890
1891
1892 /*
1893 * pj_term_set_color()
1894 */
1895 PJ_DEF(pj_status_t) pj_term_set_color(pj_color_t color)
1896 {
1897 BOOL rc;
1898 WORD attr = 0;
1899
1900 PJ_CHECK_STACK();
1901
1902 attr = pj_color_to_os_attr(color);
1903 rc = SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), attr);
1904 return rc ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(GetLastError());
1905 }
1906
1907 /*
1908 * pj_term_get_color()
1909 * Get current terminal foreground color.
1910 */
1911 PJ_DEF(pj_color_t) pj_term_get_color(void)
1912 {
1913 CONSOLE_SCREEN_BUFFER_INFO info;
1914
1915 PJ_CHECK_STACK();
1916
1917 GetConsoleScreenBufferInfo( GetStdHandle(STD_OUTPUT_HANDLE), &info);
1918 return os_attr_to_pj_color(info.wAttributes);
1919 }
1920
1921 #endif /* PJ_TERM_HAS_COLOR */
1922
1923 /*
1924 * pj_run_app()
1925 */
1926 PJ_DEF(int) pj_run_app(pj_main_func_ptr main_func, int argc, char *argv[],
1927 unsigned flags)
1928 {
1929 PJ_UNUSED_ARG(flags);
1930 return (*main_func)(argc, argv);
1931 }
1932
1933 /*
1934 * Set file descriptor close-on-exec flag
1935 */
1936 PJ_DEF(pj_status_t) pj_set_cloexec_flag(int fd)
1937 {
1938 PJ_UNUSED_ARG(fd);
1939 return PJ_ENOTSUP;
1940 }