1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to
5 * deal in the Software without restriction, including without limitation the
6 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 * sell copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 #if defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)
35 #include "handle-inl.h"
39 /* uv_once initialization guards */
40 static uv_once_t uv_init_guard_ = UV_ONCE_INIT;
43 #if defined(_DEBUG) && (defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR))
44 /* Our crt debug report handler allows us to temporarily disable asserts
45 * just for the current thread.
48 UV_THREAD_LOCAL int uv__crt_assert_enabled = TRUE;
50 static int uv__crt_dbg_report_handler(int report_type, char *message, int *ret_val) {
51 if (uv__crt_assert_enabled || report_type != _CRT_ASSERT)
55 /* Set ret_val to 0 to continue with normal execution.
56 * Set ret_val to 1 to trigger a breakpoint.
59 if(IsDebuggerPresent())
65 /* Don't call _CrtDbgReport. */
69 UV_THREAD_LOCAL int uv__crt_assert_enabled = FALSE;
73 #if !defined(__MINGW32__) || __MSVCRT_VERSION__ >= 0x800
74 static void uv__crt_invalid_parameter_handler(const wchar_t* expression,
75 const wchar_t* function, const wchar_t * file, unsigned int line,
81 static uv_loop_t** uv__loops;
82 static int uv__loops_size;
83 static int uv__loops_capacity;
84 #define UV__LOOPS_CHUNK_SIZE 8
85 static uv_mutex_t uv__loops_lock;
88 static void uv__loops_init(void) {
89 uv_mutex_init(&uv__loops_lock);
93 static int uv__loops_add(uv_loop_t* loop) {
94 uv_loop_t** new_loops;
97 uv_mutex_lock(&uv__loops_lock);
99 if (uv__loops_size == uv__loops_capacity) {
100 new_capacity = uv__loops_capacity + UV__LOOPS_CHUNK_SIZE;
101 new_loops = uv__realloc(uv__loops, sizeof(uv_loop_t*) * new_capacity);
103 goto failed_loops_realloc;
104 uv__loops = new_loops;
105 for (i = uv__loops_capacity; i < new_capacity; ++i)
107 uv__loops_capacity = new_capacity;
109 uv__loops[uv__loops_size] = loop;
112 uv_mutex_unlock(&uv__loops_lock);
115 failed_loops_realloc:
116 uv_mutex_unlock(&uv__loops_lock);
117 return ERROR_OUTOFMEMORY;
121 static void uv__loops_remove(uv_loop_t* loop) {
123 int smaller_capacity;
124 uv_loop_t** new_loops;
126 uv_mutex_lock(&uv__loops_lock);
128 for (loop_index = 0; loop_index < uv__loops_size; ++loop_index) {
129 if (uv__loops[loop_index] == loop)
132 /* If loop was not found, ignore */
133 if (loop_index == uv__loops_size)
136 uv__loops[loop_index] = uv__loops[uv__loops_size - 1];
137 uv__loops[uv__loops_size - 1] = NULL;
140 if (uv__loops_size == 0) {
141 uv__loops_capacity = 0;
147 /* If we didn't grow to big skip downsizing */
148 if (uv__loops_capacity < 4 * UV__LOOPS_CHUNK_SIZE)
151 /* Downsize only if more than half of buffer is free */
152 smaller_capacity = uv__loops_capacity / 2;
153 if (uv__loops_size >= smaller_capacity)
155 new_loops = uv__realloc(uv__loops, sizeof(uv_loop_t*) * smaller_capacity);
158 uv__loops = new_loops;
159 uv__loops_capacity = smaller_capacity;
162 uv_mutex_unlock(&uv__loops_lock);
165 void uv__wake_all_loops(void) {
169 uv_mutex_lock(&uv__loops_lock);
170 for (i = 0; i < uv__loops_size; ++i) {
173 if (loop->iocp != INVALID_HANDLE_VALUE)
174 PostQueuedCompletionStatus(loop->iocp, 0, 0, NULL);
176 uv_mutex_unlock(&uv__loops_lock);
179 static void uv__init(void) {
180 /* Tell Windows that we will handle critical errors. */
181 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
182 SEM_NOOPENFILEERRORBOX);
184 /* Tell the CRT to not exit the application when an invalid parameter is
185 * passed. The main issue is that invalid FDs will trigger this behavior.
187 #if !defined(__MINGW32__) || __MSVCRT_VERSION__ >= 0x800
188 _set_invalid_parameter_handler(uv__crt_invalid_parameter_handler);
191 /* We also need to setup our debug report handler because some CRT
192 * functions (eg _get_osfhandle) raise an assert when called with invalid
193 * FDs even though they return the proper error code in the release build.
195 #if defined(_DEBUG) && (defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR))
196 _CrtSetReportHook(uv__crt_dbg_report_handler);
199 /* Initialize tracking of all uv loops */
202 /* Fetch winapi function pointers. This must be done first because other
203 * initialization code might need these function pointers to be loaded.
207 /* Initialize winsock */
213 /* Initialize signal stuff */
216 /* Initialize console */
219 /* Initialize utilities */
222 /* Initialize system wakeup detection */
223 uv__init_detect_system_wakeup();
227 int uv_loop_init(uv_loop_t* loop) {
228 uv__loop_internal_fields_t* lfields;
229 struct heap* timer_heap;
232 /* Initialize libuv itself first */
235 /* Create an I/O completion port */
236 loop->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
237 if (loop->iocp == NULL)
238 return uv_translate_sys_error(GetLastError());
240 lfields = (uv__loop_internal_fields_t*) uv__calloc(1, sizeof(*lfields));
243 loop->internal_fields = lfields;
245 err = uv_mutex_init(&lfields->loop_metrics.lock);
247 goto fail_metrics_mutex_init;
249 /* To prevent uninitialized memory access, loop->time must be initialized
250 * to zero before calling uv_update_time for the first time.
253 uv_update_time(loop);
255 QUEUE_INIT(&loop->wq);
256 QUEUE_INIT(&loop->handle_queue);
257 loop->active_reqs.count = 0;
258 loop->active_handles = 0;
260 loop->pending_reqs_tail = NULL;
262 loop->endgame_handles = NULL;
264 loop->timer_heap = timer_heap = uv__malloc(sizeof(*timer_heap));
265 if (timer_heap == NULL) {
267 goto fail_timers_alloc;
270 heap_init(timer_heap);
272 loop->check_handles = NULL;
273 loop->prepare_handles = NULL;
274 loop->idle_handles = NULL;
276 loop->next_prepare_handle = NULL;
277 loop->next_check_handle = NULL;
278 loop->next_idle_handle = NULL;
280 memset(&loop->poll_peer_sockets, 0, sizeof loop->poll_peer_sockets);
282 loop->active_tcp_streams = 0;
283 loop->active_udp_streams = 0;
285 loop->timer_counter = 0;
288 err = uv_mutex_init(&loop->wq_mutex);
290 goto fail_mutex_init;
292 err = uv_async_init(loop, &loop->wq_async, uv__work_done);
294 goto fail_async_init;
296 uv__handle_unref(&loop->wq_async);
297 loop->wq_async.flags |= UV_HANDLE_INTERNAL;
299 err = uv__loops_add(loop);
301 goto fail_async_init;
306 uv_mutex_destroy(&loop->wq_mutex);
309 uv__free(timer_heap);
310 loop->timer_heap = NULL;
313 uv_mutex_destroy(&lfields->loop_metrics.lock);
315 fail_metrics_mutex_init:
317 loop->internal_fields = NULL;
318 CloseHandle(loop->iocp);
319 loop->iocp = INVALID_HANDLE_VALUE;
325 void uv_update_time(uv_loop_t* loop) {
326 uint64_t new_time = uv__hrtime(1000);
327 assert(new_time >= loop->time);
328 loop->time = new_time;
332 void uv__once_init(void) {
333 uv_once(&uv_init_guard_, uv__init);
337 void uv__loop_close(uv_loop_t* loop) {
338 uv__loop_internal_fields_t* lfields;
341 uv__loops_remove(loop);
343 /* Close the async handle without needing an extra loop iteration.
344 * We might have a pending message, but we're just going to destroy the IOCP
345 * soon, so we can just discard it now without the usual risk of a getting
346 * another notification from GetQueuedCompletionStatusEx after calling the
347 * close_cb (which we also skip defining). We'll assert later that queue was
348 * actually empty and all reqs handled. */
349 loop->wq_async.async_sent = 0;
350 loop->wq_async.close_cb = NULL;
351 uv__handle_closing(&loop->wq_async);
352 uv__handle_close(&loop->wq_async);
354 for (i = 0; i < ARRAY_SIZE(loop->poll_peer_sockets); i++) {
355 SOCKET sock = loop->poll_peer_sockets[i];
356 if (sock != 0 && sock != INVALID_SOCKET)
360 uv_mutex_lock(&loop->wq_mutex);
361 assert(QUEUE_EMPTY(&loop->wq) && "thread pool work queue not empty!");
362 assert(!uv__has_active_reqs(loop));
363 uv_mutex_unlock(&loop->wq_mutex);
364 uv_mutex_destroy(&loop->wq_mutex);
366 uv__free(loop->timer_heap);
367 loop->timer_heap = NULL;
369 lfields = uv__get_internal_fields(loop);
370 uv_mutex_destroy(&lfields->loop_metrics.lock);
372 loop->internal_fields = NULL;
374 CloseHandle(loop->iocp);
378 int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) {
379 uv__loop_internal_fields_t* lfields;
381 lfields = uv__get_internal_fields(loop);
382 if (option == UV_METRICS_IDLE_TIME) {
383 lfields->flags |= UV_METRICS_IDLE_TIME;
391 int uv_backend_fd(const uv_loop_t* loop) {
396 int uv_loop_fork(uv_loop_t* loop) {
401 static int uv__loop_alive(const uv_loop_t* loop) {
402 return uv__has_active_handles(loop) ||
403 uv__has_active_reqs(loop) ||
404 loop->pending_reqs_tail != NULL ||
405 loop->endgame_handles != NULL;
409 int uv_loop_alive(const uv_loop_t* loop) {
410 return uv__loop_alive(loop);
414 int uv_backend_timeout(const uv_loop_t* loop) {
415 if (loop->stop_flag == 0 &&
416 /* uv__loop_alive(loop) && */
417 (uv__has_active_handles(loop) || uv__has_active_reqs(loop)) &&
418 loop->pending_reqs_tail == NULL &&
419 loop->idle_handles == NULL &&
420 loop->endgame_handles == NULL)
421 return uv__next_timeout(loop);
426 static void uv__poll_wine(uv_loop_t* loop, DWORD timeout) {
429 OVERLAPPED* overlapped;
432 uint64_t timeout_time;
433 uint64_t user_timeout;
436 timeout_time = loop->time + timeout;
438 if (uv__get_internal_fields(loop)->flags & UV_METRICS_IDLE_TIME) {
440 user_timeout = timeout;
446 for (repeat = 0; ; repeat++) {
447 /* Only need to set the provider_entry_time if timeout != 0. The function
448 * will return early if the loop isn't configured with UV_METRICS_IDLE_TIME.
451 uv__metrics_set_provider_entry_time(loop);
453 GetQueuedCompletionStatus(loop->iocp,
459 if (reset_timeout != 0) {
460 timeout = user_timeout;
464 /* Placed here because on success the loop will break whether there is an
465 * empty package or not, or if GetQueuedCompletionStatus returned early then
466 * the timeout will be updated and the loop will run again. In either case
467 * the idle time will need to be updated.
469 uv__metrics_update_idle_time(loop);
472 /* Package was dequeued */
473 req = uv__overlapped_to_req(overlapped);
474 uv__insert_pending_req(loop, req);
476 /* Some time might have passed waiting for I/O,
477 * so update the loop time here.
479 uv_update_time(loop);
480 } else if (GetLastError() != WAIT_TIMEOUT) {
482 uv_fatal_error(GetLastError(), "GetQueuedCompletionStatus");
483 } else if (timeout > 0) {
484 /* GetQueuedCompletionStatus can occasionally return a little early.
485 * Make sure that the desired timeout target time is reached.
487 uv_update_time(loop);
488 if (timeout_time > loop->time) {
489 timeout = (DWORD)(timeout_time - loop->time);
490 /* The first call to GetQueuedCompletionStatus should return very
491 * close to the target time and the second should reach it, but
492 * this is not stated in the documentation. To make sure a busy
493 * loop cannot happen, the timeout is increased exponentially
494 * starting on the third round.
496 timeout += repeat ? (1 << (repeat - 1)) : 0;
505 static void uv__poll(uv_loop_t* loop, DWORD timeout) {
508 OVERLAPPED_ENTRY overlappeds[128];
512 uint64_t timeout_time;
513 uint64_t user_timeout;
516 timeout_time = loop->time + timeout;
518 if (uv__get_internal_fields(loop)->flags & UV_METRICS_IDLE_TIME) {
520 user_timeout = timeout;
526 for (repeat = 0; ; repeat++) {
527 /* Only need to set the provider_entry_time if timeout != 0. The function
528 * will return early if the loop isn't configured with UV_METRICS_IDLE_TIME.
531 uv__metrics_set_provider_entry_time(loop);
533 success = pGetQueuedCompletionStatusEx(loop->iocp,
535 ARRAY_SIZE(overlappeds),
540 if (reset_timeout != 0) {
541 timeout = user_timeout;
545 /* Placed here because on success the loop will break whether there is an
546 * empty package or not, or if GetQueuedCompletionStatus returned early then
547 * the timeout will be updated and the loop will run again. In either case
548 * the idle time will need to be updated.
550 uv__metrics_update_idle_time(loop);
553 for (i = 0; i < count; i++) {
554 /* Package was dequeued, but see if it is not a empty package
555 * meant only to wake us up.
557 if (overlappeds[i].lpOverlapped) {
558 req = uv__overlapped_to_req(overlappeds[i].lpOverlapped);
559 uv__insert_pending_req(loop, req);
563 /* Some time might have passed waiting for I/O,
564 * so update the loop time here.
566 uv_update_time(loop);
567 } else if (GetLastError() != WAIT_TIMEOUT) {
569 uv_fatal_error(GetLastError(), "GetQueuedCompletionStatusEx");
570 } else if (timeout > 0) {
571 /* GetQueuedCompletionStatus can occasionally return a little early.
572 * Make sure that the desired timeout target time is reached.
574 uv_update_time(loop);
575 if (timeout_time > loop->time) {
576 timeout = (DWORD)(timeout_time - loop->time);
577 /* The first call to GetQueuedCompletionStatus should return very
578 * close to the target time and the second should reach it, but
579 * this is not stated in the documentation. To make sure a busy
580 * loop cannot happen, the timeout is increased exponentially
581 * starting on the third round.
583 timeout += repeat ? (1 << (repeat - 1)) : 0;
592 int uv_run(uv_loop_t *loop, uv_run_mode mode) {
597 r = uv__loop_alive(loop);
599 uv_update_time(loop);
601 while (r != 0 && loop->stop_flag == 0) {
602 uv_update_time(loop);
603 uv__run_timers(loop);
605 can_sleep = loop->pending_reqs_tail == NULL && loop->idle_handles == NULL;
607 uv__process_reqs(loop);
608 uv__idle_invoke(loop);
609 uv__prepare_invoke(loop);
612 if ((mode == UV_RUN_ONCE && can_sleep) || mode == UV_RUN_DEFAULT)
613 timeout = uv_backend_timeout(loop);
615 if (pGetQueuedCompletionStatusEx)
616 uv__poll(loop, timeout);
618 uv__poll_wine(loop, timeout);
620 /* Process immediate callbacks (e.g. write_cb) a small fixed number of
621 * times to avoid loop starvation.*/
622 for (r = 0; r < 8 && loop->pending_reqs_tail != NULL; r++)
623 uv__process_reqs(loop);
625 /* Run one final update on the provider_idle_time in case uv__poll*
626 * returned because the timeout expired, but no events were received. This
627 * call will be ignored if the provider_entry_time was either never set (if
628 * the timeout == 0) or was already updated b/c an event was received.
630 uv__metrics_update_idle_time(loop);
632 uv__check_invoke(loop);
633 uv__process_endgames(loop);
635 if (mode == UV_RUN_ONCE) {
636 /* UV_RUN_ONCE implies forward progress: at least one callback must have
637 * been invoked when it returns. uv__io_poll() can return without doing
638 * I/O (meaning: no callbacks) when its timeout expires - which means we
639 * have pending timers that satisfy the forward progress constraint.
641 * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
644 uv_update_time(loop);
645 uv__run_timers(loop);
648 r = uv__loop_alive(loop);
649 if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
653 /* The if statement lets the compiler compile it to a conditional store.
654 * Avoids dirtying a cache line.
656 if (loop->stop_flag != 0)
663 int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
666 switch (handle->type) {
668 fd_out = (uv_os_fd_t)((uv_tcp_t*) handle)->socket;
672 fd_out = ((uv_pipe_t*) handle)->handle;
676 fd_out = ((uv_tty_t*) handle)->handle;
680 fd_out = (uv_os_fd_t)((uv_udp_t*) handle)->socket;
684 fd_out = (uv_os_fd_t)((uv_poll_t*) handle)->socket;
691 if (uv_is_closing(handle) || fd_out == INVALID_HANDLE_VALUE)
699 int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
704 if (handle == NULL || value == NULL)
707 if (handle->type == UV_TCP)
708 socket = ((uv_tcp_t*) handle)->socket;
709 else if (handle->type == UV_UDP)
710 socket = ((uv_udp_t*) handle)->socket;
714 len = sizeof(*value);
717 r = getsockopt(socket, SOL_SOCKET, optname, (char*) value, &len);
719 r = setsockopt(socket, SOL_SOCKET, optname, (const char*) value, len);
721 if (r == SOCKET_ERROR)
722 return uv_translate_sys_error(WSAGetLastError());
727 int uv_cpumask_size(void) {
728 return (int)(sizeof(DWORD_PTR) * 8);
731 int uv__getsockpeername(const uv_handle_t* handle,
732 uv__peersockfunc func,
733 struct sockaddr* name,
740 result = uv_fileno(handle, &fd);
745 return uv_translate_sys_error(delayed_error);
747 result = func((SOCKET) fd, name, namelen);
749 return uv_translate_sys_error(WSAGetLastError());