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
33 /* clang-format off */
45 * Max title length; the only thing MSDN tells us about the maximum length
46 * of the console title is that it is smaller than 64K. However in practice
47 * it is much smaller, and there is no way to figure out what the exact length
48 * of the title is or can be, at least not on XP. To make it even more
49 * annoying, GetConsoleTitle fails when the buffer to be read into is bigger
50 * than the actual maximum length. So we make a conservative guess here;
51 * just don't put the novel you're writing in the title, unless the plot
52 * survives truncation.
54 #define MAX_TITLE_LENGTH 8192
56 /* The number of nanoseconds in one second. */
57 #define UV__NANOSEC 1000000000
59 /* Max user name length, from iphlpapi.h */
65 /* A RtlGenRandom() by any other name... */
66 extern BOOLEAN NTAPI SystemFunction036(PVOID Buffer, ULONG BufferLength);
68 /* Cached copy of the process title, plus a mutex guarding it. */
69 static char *process_title;
70 static CRITICAL_SECTION process_title_lock;
72 /* Frequency of the high-resolution clock. */
73 static uint64_t hrtime_frequency_ = 0;
77 * One-time initialization code for functionality defined in util.c.
79 void uv__util_init(void) {
80 LARGE_INTEGER perf_frequency;
82 /* Initialize process title access mutex. */
83 InitializeCriticalSection(&process_title_lock);
85 /* Retrieve high-resolution timer frequency
86 * and precompute its reciprocal.
88 if (QueryPerformanceFrequency(&perf_frequency)) {
89 hrtime_frequency_ = perf_frequency.QuadPart;
91 uv_fatal_error(GetLastError(), "QueryPerformanceFrequency");
96 int uv_exepath(char* buffer, size_t* size_ptr) {
97 int utf8_len, utf16_buffer_len, utf16_len;
101 if (buffer == NULL || size_ptr == NULL || *size_ptr == 0) {
105 if (*size_ptr > 32768) {
106 /* Windows paths can never be longer than this. */
107 utf16_buffer_len = 32768;
109 utf16_buffer_len = (int) *size_ptr;
112 utf16_buffer = (WCHAR*) uv__malloc(sizeof(WCHAR) * utf16_buffer_len);
117 /* Get the path as UTF-16. */
118 utf16_len = GetModuleFileNameW(NULL, utf16_buffer, utf16_buffer_len);
119 if (utf16_len <= 0) {
120 err = GetLastError();
124 /* utf16_len contains the length, *not* including the terminating null. */
125 utf16_buffer[utf16_len] = L'\0';
127 /* Convert to UTF-8 */
128 utf8_len = WideCharToMultiByte(CP_UTF8,
137 err = GetLastError();
141 uv__free(utf16_buffer);
143 /* utf8_len *does* include the terminating null at this point, but the
144 * returned size shouldn't. */
145 *size_ptr = utf8_len - 1;
149 uv__free(utf16_buffer);
150 return uv_translate_sys_error(err);
154 int uv_cwd(char* buffer, size_t* size) {
159 if (buffer == NULL || size == NULL) {
163 utf16_len = GetCurrentDirectoryW(0, NULL);
164 if (utf16_len == 0) {
165 return uv_translate_sys_error(GetLastError());
167 utf16_buffer = uv__malloc(utf16_len * sizeof(WCHAR));
168 if (utf16_buffer == NULL) {
172 utf16_len = GetCurrentDirectoryW(utf16_len, utf16_buffer);
173 if (utf16_len == 0) {
174 uv__free(utf16_buffer);
175 return uv_translate_sys_error(GetLastError());
178 /* utf16_len contains the length, *not* including the terminating null. */
179 utf16_buffer[utf16_len] = L'\0';
181 /* The returned directory should not have a trailing slash, unless it points
182 * at a drive root, like c:\. Remove it if needed. */
183 if (utf16_buffer[utf16_len - 1] == L'\\' &&
184 !(utf16_len == 3 && utf16_buffer[1] == L':')) {
186 utf16_buffer[utf16_len] = L'\0';
189 /* Check how much space we need */
190 r = WideCharToMultiByte(CP_UTF8,
199 uv__free(utf16_buffer);
200 return uv_translate_sys_error(GetLastError());
201 } else if (r > (int) *size) {
202 uv__free(utf16_buffer);
207 /* Convert to UTF-8 */
208 r = WideCharToMultiByte(CP_UTF8,
213 *size > INT_MAX ? INT_MAX : (int) *size,
216 uv__free(utf16_buffer);
219 return uv_translate_sys_error(GetLastError());
227 int uv_chdir(const char* dir) {
229 size_t utf16_len, new_utf16_len;
230 WCHAR drive_letter, env_var[4];
236 utf16_len = MultiByteToWideChar(CP_UTF8,
242 if (utf16_len == 0) {
243 return uv_translate_sys_error(GetLastError());
245 utf16_buffer = uv__malloc(utf16_len * sizeof(WCHAR));
246 if (utf16_buffer == NULL) {
250 if (MultiByteToWideChar(CP_UTF8,
256 uv__free(utf16_buffer);
257 return uv_translate_sys_error(GetLastError());
260 if (!SetCurrentDirectoryW(utf16_buffer)) {
261 uv__free(utf16_buffer);
262 return uv_translate_sys_error(GetLastError());
265 /* Windows stores the drive-local path in an "hidden" environment variable,
266 * which has the form "=C:=C:\Windows". SetCurrentDirectory does not update
267 * this, so we'll have to do it. */
268 new_utf16_len = GetCurrentDirectoryW(utf16_len, utf16_buffer);
269 if (new_utf16_len > utf16_len ) {
270 uv__free(utf16_buffer);
271 utf16_buffer = uv__malloc(new_utf16_len * sizeof(WCHAR));
272 if (utf16_buffer == NULL) {
273 /* When updating the environment variable fails, return UV_OK anyway.
274 * We did successfully change current working directory, only updating
275 * hidden env variable failed. */
278 new_utf16_len = GetCurrentDirectoryW(new_utf16_len, utf16_buffer);
280 if (utf16_len == 0) {
281 uv__free(utf16_buffer);
285 /* The returned directory should not have a trailing slash, unless it points
286 * at a drive root, like c:\. Remove it if needed. */
287 if (utf16_buffer[utf16_len - 1] == L'\\' &&
288 !(utf16_len == 3 && utf16_buffer[1] == L':')) {
290 utf16_buffer[utf16_len] = L'\0';
293 if (utf16_len < 2 || utf16_buffer[1] != L':') {
294 /* Doesn't look like a drive letter could be there - probably an UNC path.
295 * TODO: Need to handle win32 namespaces like \\?\C:\ ? */
297 } else if (utf16_buffer[0] >= L'A' && utf16_buffer[0] <= L'Z') {
298 drive_letter = utf16_buffer[0];
299 } else if (utf16_buffer[0] >= L'a' && utf16_buffer[0] <= L'z') {
300 /* Convert to uppercase. */
301 drive_letter = utf16_buffer[0] - L'a' + L'A';
307 if (drive_letter != 0) {
308 /* Construct the environment variable name and set it. */
310 env_var[1] = drive_letter;
314 SetEnvironmentVariableW(env_var, utf16_buffer);
317 uv__free(utf16_buffer);
322 void uv_loadavg(double avg[3]) {
323 /* Can't be implemented */
324 avg[0] = avg[1] = avg[2] = 0;
328 uint64_t uv_get_free_memory(void) {
329 MEMORYSTATUSEX memory_status;
330 memory_status.dwLength = sizeof(memory_status);
332 if (!GlobalMemoryStatusEx(&memory_status)) {
336 return (uint64_t)memory_status.ullAvailPhys;
340 uint64_t uv_get_total_memory(void) {
341 MEMORYSTATUSEX memory_status;
342 memory_status.dwLength = sizeof(memory_status);
344 if (!GlobalMemoryStatusEx(&memory_status)) {
348 return (uint64_t)memory_status.ullTotalPhys;
352 uint64_t uv_get_constrained_memory(void) {
353 return 0; /* Memory constraints are unknown. */
357 uv_pid_t uv_os_getpid(void) {
358 return GetCurrentProcessId();
362 uv_pid_t uv_os_getppid(void) {
366 DWORD current_pid = GetCurrentProcessId();
368 pe.dwSize = sizeof(PROCESSENTRY32);
369 handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
371 if (Process32First(handle, &pe)) {
373 if (pe.th32ProcessID == current_pid) {
374 parent_pid = pe.th32ParentProcessID;
377 } while( Process32Next(handle, &pe));
385 char** uv_setup_args(int argc, char** argv) {
390 void uv__process_title_cleanup(void) {
394 int uv_set_process_title(const char* title) {
397 WCHAR* title_w = NULL;
401 /* Find out how big the buffer for the wide-char title must be */
402 length = MultiByteToWideChar(CP_UTF8, 0, title, -1, NULL, 0);
404 err = GetLastError();
408 /* Convert to wide-char string */
409 title_w = (WCHAR*)uv__malloc(sizeof(WCHAR) * length);
411 uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
414 length = MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w, length);
416 err = GetLastError();
420 /* If the title must be truncated insert a \0 terminator there */
421 if (length > MAX_TITLE_LENGTH) {
422 title_w[MAX_TITLE_LENGTH - 1] = L'\0';
425 if (!SetConsoleTitleW(title_w)) {
426 err = GetLastError();
430 EnterCriticalSection(&process_title_lock);
431 uv__free(process_title);
432 process_title = uv__strdup(title);
433 LeaveCriticalSection(&process_title_lock);
439 return uv_translate_sys_error(err);
443 static int uv__get_process_title(void) {
444 WCHAR title_w[MAX_TITLE_LENGTH];
446 if (!GetConsoleTitleW(title_w, sizeof(title_w) / sizeof(WCHAR))) {
450 if (uv__convert_utf16_to_utf8(title_w, -1, &process_title) != 0)
457 int uv_get_process_title(char* buffer, size_t size) {
460 if (buffer == NULL || size == 0)
465 EnterCriticalSection(&process_title_lock);
467 * If the process_title was never read before nor explicitly set,
468 * we must query it with getConsoleTitleW
470 if (!process_title && uv__get_process_title() == -1) {
471 LeaveCriticalSection(&process_title_lock);
472 return uv_translate_sys_error(GetLastError());
475 assert(process_title);
476 len = strlen(process_title) + 1;
479 LeaveCriticalSection(&process_title_lock);
483 memcpy(buffer, process_title, len);
484 LeaveCriticalSection(&process_title_lock);
490 uint64_t uv_hrtime(void) {
492 return uv__hrtime(UV__NANOSEC);
495 uint64_t uv__hrtime(unsigned int scale) {
496 LARGE_INTEGER counter;
500 assert(hrtime_frequency_ != 0);
502 if (!QueryPerformanceCounter(&counter)) {
503 uv_fatal_error(GetLastError(), "QueryPerformanceCounter");
505 assert(counter.QuadPart != 0);
507 /* Because we have no guarantee about the order of magnitude of the
508 * performance counter interval, integer math could cause this computation
509 * to overflow. Therefore we resort to floating point math.
511 scaled_freq = (double) hrtime_frequency_ / scale;
512 result = (double) counter.QuadPart / scaled_freq;
513 return (uint64_t) result;
517 int uv_resident_set_memory(size_t* rss) {
518 HANDLE current_process;
519 PROCESS_MEMORY_COUNTERS pmc;
521 current_process = GetCurrentProcess();
523 if (!GetProcessMemoryInfo(current_process, &pmc, sizeof(pmc))) {
524 return uv_translate_sys_error(GetLastError());
527 *rss = pmc.WorkingSetSize;
533 int uv_uptime(double* uptime) {
534 BYTE stack_buffer[4096];
535 BYTE* malloced_buffer = NULL;
536 BYTE* buffer = (BYTE*) stack_buffer;
537 size_t buffer_size = sizeof(stack_buffer);
540 PERF_DATA_BLOCK* data_block;
541 PERF_OBJECT_TYPE* object_type;
542 PERF_COUNTER_DEFINITION* counter_definition;
549 data_size = (DWORD) buffer_size;
550 result = RegQueryValueExW(HKEY_PERFORMANCE_DATA,
556 if (result == ERROR_SUCCESS) {
558 } else if (result != ERROR_MORE_DATA) {
560 return uv_translate_sys_error(result);
564 /* Don't let the buffer grow infinitely. */
565 if (buffer_size > 1 << 20) {
569 uv__free(malloced_buffer);
571 buffer = malloced_buffer = (BYTE*) uv__malloc(buffer_size);
572 if (malloced_buffer == NULL) {
578 if (data_size < sizeof(*data_block))
581 data_block = (PERF_DATA_BLOCK*) buffer;
583 if (wmemcmp(data_block->Signature, L"PERF", 4) != 0)
586 if (data_size < data_block->HeaderLength + sizeof(*object_type))
589 object_type = (PERF_OBJECT_TYPE*) (buffer + data_block->HeaderLength);
591 if (object_type->NumInstances != PERF_NO_INSTANCES)
594 counter_definition = (PERF_COUNTER_DEFINITION*) (buffer +
595 data_block->HeaderLength + object_type->HeaderLength);
596 for (i = 0; i < object_type->NumCounters; i++) {
597 if ((BYTE*) counter_definition + sizeof(*counter_definition) >
598 buffer + data_size) {
602 if (counter_definition->CounterNameTitleIndex == 674 &&
603 counter_definition->CounterSize == sizeof(uint64_t)) {
604 if (counter_definition->CounterOffset + sizeof(uint64_t) > data_size ||
605 !(counter_definition->CounterType & PERF_OBJECT_TIMER)) {
608 BYTE* address = (BYTE*) object_type + object_type->DefinitionLength +
609 counter_definition->CounterOffset;
610 uint64_t value = *((uint64_t*) address);
611 *uptime = floor((double) (object_type->PerfTime.QuadPart - value) /
612 (double) object_type->PerfFreq.QuadPart);
613 uv__free(malloced_buffer);
618 counter_definition = (PERF_COUNTER_DEFINITION*)
619 ((BYTE*) counter_definition + counter_definition->ByteLength);
622 /* If we get here, the uptime value was not found. */
623 uv__free(malloced_buffer);
628 uv__free(malloced_buffer);
634 int uv_cpu_info(uv_cpu_info_t** cpu_infos_ptr, int* cpu_count_ptr) {
635 uv_cpu_info_t* cpu_infos;
636 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi;
638 SYSTEM_INFO system_info;
643 uv_cpu_info_t* cpu_info;
651 GetSystemInfo(&system_info);
652 cpu_count = system_info.dwNumberOfProcessors;
654 cpu_infos = uv__calloc(cpu_count, sizeof *cpu_infos);
655 if (cpu_infos == NULL) {
656 err = ERROR_OUTOFMEMORY;
660 sppi_size = cpu_count * sizeof(*sppi);
661 sppi = uv__malloc(sppi_size);
663 err = ERROR_OUTOFMEMORY;
667 status = pNtQuerySystemInformation(SystemProcessorPerformanceInformation,
671 if (!NT_SUCCESS(status)) {
672 err = pRtlNtStatusToDosError(status);
676 assert(result_size == sppi_size);
678 for (i = 0; i < cpu_count; i++) {
682 DWORD cpu_speed_size = sizeof(cpu_speed);
683 WCHAR cpu_brand[256];
684 DWORD cpu_brand_size = sizeof(cpu_brand);
687 len = _snwprintf(key_name,
688 ARRAY_SIZE(key_name),
689 L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d",
692 assert(len > 0 && len < ARRAY_SIZE(key_name));
694 err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
699 if (err != ERROR_SUCCESS) {
703 err = RegQueryValueExW(processor_key,
709 if (err != ERROR_SUCCESS) {
710 RegCloseKey(processor_key);
714 err = RegQueryValueExW(processor_key,
715 L"ProcessorNameString",
720 RegCloseKey(processor_key);
721 if (err != ERROR_SUCCESS)
724 cpu_info = &cpu_infos[i];
725 cpu_info->speed = cpu_speed;
726 cpu_info->cpu_times.user = sppi[i].UserTime.QuadPart / 10000;
727 cpu_info->cpu_times.sys = (sppi[i].KernelTime.QuadPart -
728 sppi[i].IdleTime.QuadPart) / 10000;
729 cpu_info->cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000;
730 cpu_info->cpu_times.irq = sppi[i].InterruptTime.QuadPart / 10000;
731 cpu_info->cpu_times.nice = 0;
733 uv__convert_utf16_to_utf8(cpu_brand,
734 cpu_brand_size / sizeof(WCHAR),
740 *cpu_count_ptr = cpu_count;
741 *cpu_infos_ptr = cpu_infos;
746 if (cpu_infos != NULL) {
747 /* This is safe because the cpu_infos array is zeroed on allocation. */
748 for (i = 0; i < cpu_count; i++)
749 uv__free(cpu_infos[i].model);
755 return uv_translate_sys_error(err);
759 static int is_windows_version_or_greater(DWORD os_major,
761 WORD service_pack_major,
762 WORD service_pack_minor) {
763 OSVERSIONINFOEX osvi;
764 DWORDLONG condition_mask = 0;
765 int op = VER_GREATER_EQUAL;
767 /* Initialize the OSVERSIONINFOEX structure. */
768 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
769 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
770 osvi.dwMajorVersion = os_major;
771 osvi.dwMinorVersion = os_minor;
772 osvi.wServicePackMajor = service_pack_major;
773 osvi.wServicePackMinor = service_pack_minor;
775 /* Initialize the condition mask. */
776 VER_SET_CONDITION(condition_mask, VER_MAJORVERSION, op);
777 VER_SET_CONDITION(condition_mask, VER_MINORVERSION, op);
778 VER_SET_CONDITION(condition_mask, VER_SERVICEPACKMAJOR, op);
779 VER_SET_CONDITION(condition_mask, VER_SERVICEPACKMINOR, op);
781 /* Perform the test. */
782 return (int) VerifyVersionInfo(
784 VER_MAJORVERSION | VER_MINORVERSION |
785 VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
790 static int address_prefix_match(int family,
791 struct sockaddr* address,
792 struct sockaddr* prefix_address,
794 uint8_t* address_data;
795 uint8_t* prefix_address_data;
798 assert(address->sa_family == family);
799 assert(prefix_address->sa_family == family);
801 if (family == AF_INET6) {
802 address_data = (uint8_t*) &(((struct sockaddr_in6 *) address)->sin6_addr);
803 prefix_address_data =
804 (uint8_t*) &(((struct sockaddr_in6 *) prefix_address)->sin6_addr);
806 address_data = (uint8_t*) &(((struct sockaddr_in *) address)->sin_addr);
807 prefix_address_data =
808 (uint8_t*) &(((struct sockaddr_in *) prefix_address)->sin_addr);
811 for (i = 0; i < prefix_len >> 3; i++) {
812 if (address_data[i] != prefix_address_data[i])
817 return prefix_address_data[i] ==
818 (address_data[i] & (0xff << (8 - prefix_len % 8)));
824 int uv_interface_addresses(uv_interface_address_t** addresses_ptr,
826 IP_ADAPTER_ADDRESSES* win_address_buf;
827 ULONG win_address_buf_size;
828 IP_ADAPTER_ADDRESSES* adapter;
830 uv_interface_address_t* uv_address_buf;
832 size_t uv_address_buf_size;
833 uv_interface_address_t* uv_address;
837 int is_vista_or_greater;
840 *addresses_ptr = NULL;
843 is_vista_or_greater = is_windows_version_or_greater(6, 0, 0, 0);
844 if (is_vista_or_greater) {
845 flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
846 GAA_FLAG_SKIP_DNS_SERVER;
848 /* We need at least XP SP1. */
849 if (!is_windows_version_or_greater(5, 1, 1, 0))
852 flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
853 GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_INCLUDE_PREFIX;
857 /* Fetch the size of the adapters reported by windows, and then get the list
859 win_address_buf_size = 0;
860 win_address_buf = NULL;
865 /* If win_address_buf is 0, then GetAdaptersAddresses will fail with.
866 * ERROR_BUFFER_OVERFLOW, and the required buffer size will be stored in
867 * win_address_buf_size. */
868 r = GetAdaptersAddresses(AF_UNSPEC,
872 &win_address_buf_size);
874 if (r == ERROR_SUCCESS)
877 uv__free(win_address_buf);
880 case ERROR_BUFFER_OVERFLOW:
881 /* This happens when win_address_buf is NULL or too small to hold all
883 win_address_buf = uv__malloc(win_address_buf_size);
884 if (win_address_buf == NULL)
889 case ERROR_NO_DATA: {
890 /* No adapters were found. */
891 uv_address_buf = uv__malloc(1);
892 if (uv_address_buf == NULL)
896 *addresses_ptr = uv_address_buf;
901 case ERROR_ADDRESS_NOT_ASSOCIATED:
904 case ERROR_INVALID_PARAMETER:
906 * "This error is returned for any of the following conditions: the
907 * SizePointer parameter is NULL, the Address parameter is not
908 * AF_INET, AF_INET6, or AF_UNSPEC, or the address information for
909 * the parameters requested is greater than ULONG_MAX."
910 * Since the first two conditions are not met, it must be that the
911 * adapter data is too big.
916 /* Other (unspecified) errors can happen, but we don't have any special
917 * meaning for them. */
918 assert(r != ERROR_SUCCESS);
919 return uv_translate_sys_error(r);
923 /* Count the number of enabled interfaces and compute how much space is
924 * needed to store their info. */
926 uv_address_buf_size = 0;
928 for (adapter = win_address_buf;
930 adapter = adapter->Next) {
931 IP_ADAPTER_UNICAST_ADDRESS* unicast_address;
934 /* Interfaces that are not 'up' should not be reported. Also skip
935 * interfaces that have no associated unicast address, as to avoid
936 * allocating space for the name for this interface. */
937 if (adapter->OperStatus != IfOperStatusUp ||
938 adapter->FirstUnicastAddress == NULL)
941 /* Compute the size of the interface name. */
942 name_size = WideCharToMultiByte(CP_UTF8,
944 adapter->FriendlyName,
950 if (name_size <= 0) {
951 uv__free(win_address_buf);
952 return uv_translate_sys_error(GetLastError());
954 uv_address_buf_size += name_size;
956 /* Count the number of addresses associated with this interface, and
957 * compute the size. */
958 for (unicast_address = (IP_ADAPTER_UNICAST_ADDRESS*)
959 adapter->FirstUnicastAddress;
960 unicast_address != NULL;
961 unicast_address = unicast_address->Next) {
963 uv_address_buf_size += sizeof(uv_interface_address_t);
967 /* Allocate space to store interface data plus adapter names. */
968 uv_address_buf = uv__malloc(uv_address_buf_size);
969 if (uv_address_buf == NULL) {
970 uv__free(win_address_buf);
974 /* Compute the start of the uv_interface_address_t array, and the place in
975 * the buffer where the interface names will be stored. */
976 uv_address = uv_address_buf;
977 name_buf = (char*) (uv_address_buf + count);
979 /* Fill out the output buffer. */
980 for (adapter = win_address_buf;
982 adapter = adapter->Next) {
983 IP_ADAPTER_UNICAST_ADDRESS* unicast_address;
985 size_t max_name_size;
987 if (adapter->OperStatus != IfOperStatusUp ||
988 adapter->FirstUnicastAddress == NULL)
991 /* Convert the interface name to UTF8. */
992 max_name_size = (char*) uv_address_buf + uv_address_buf_size - name_buf;
993 if (max_name_size > (size_t) INT_MAX)
994 max_name_size = INT_MAX;
995 name_size = WideCharToMultiByte(CP_UTF8,
997 adapter->FriendlyName,
1000 (int) max_name_size,
1003 if (name_size <= 0) {
1004 uv__free(win_address_buf);
1005 uv__free(uv_address_buf);
1006 return uv_translate_sys_error(GetLastError());
1009 /* Add an uv_interface_address_t element for every unicast address. */
1010 for (unicast_address = (IP_ADAPTER_UNICAST_ADDRESS*)
1011 adapter->FirstUnicastAddress;
1012 unicast_address != NULL;
1013 unicast_address = unicast_address->Next) {
1014 struct sockaddr* sa;
1017 sa = unicast_address->Address.lpSockaddr;
1019 /* XP has no OnLinkPrefixLength field. */
1020 if (is_vista_or_greater) {
1022 ((IP_ADAPTER_UNICAST_ADDRESS_LH*) unicast_address)->OnLinkPrefixLength;
1024 /* Prior to Windows Vista the FirstPrefix pointed to the list with
1025 * single prefix for each IP address assigned to the adapter.
1026 * Order of FirstPrefix does not match order of FirstUnicastAddress,
1027 * so we need to find corresponding prefix.
1029 IP_ADAPTER_PREFIX* prefix;
1032 for (prefix = adapter->FirstPrefix; prefix; prefix = prefix->Next) {
1033 /* We want the longest matching prefix. */
1034 if (prefix->Address.lpSockaddr->sa_family != sa->sa_family ||
1035 prefix->PrefixLength <= prefix_len)
1038 if (address_prefix_match(sa->sa_family, sa,
1039 prefix->Address.lpSockaddr, prefix->PrefixLength)) {
1040 prefix_len = prefix->PrefixLength;
1044 /* If there is no matching prefix information, return a single-host
1045 * subnet mask (e.g. 255.255.255.255 for IPv4).
1048 prefix_len = (sa->sa_family == AF_INET6) ? 128 : 32;
1051 memset(uv_address, 0, sizeof *uv_address);
1053 uv_address->name = name_buf;
1055 if (adapter->PhysicalAddressLength == sizeof(uv_address->phys_addr)) {
1056 memcpy(uv_address->phys_addr,
1057 adapter->PhysicalAddress,
1058 sizeof(uv_address->phys_addr));
1061 uv_address->is_internal =
1062 (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK);
1064 if (sa->sa_family == AF_INET6) {
1065 uv_address->address.address6 = *((struct sockaddr_in6 *) sa);
1067 uv_address->netmask.netmask6.sin6_family = AF_INET6;
1068 memset(uv_address->netmask.netmask6.sin6_addr.s6_addr, 0xff, prefix_len >> 3);
1069 /* This check ensures that we don't write past the size of the data. */
1070 if (prefix_len % 8) {
1071 uv_address->netmask.netmask6.sin6_addr.s6_addr[prefix_len >> 3] =
1072 0xff << (8 - prefix_len % 8);
1076 uv_address->address.address4 = *((struct sockaddr_in *) sa);
1078 uv_address->netmask.netmask4.sin_family = AF_INET;
1079 uv_address->netmask.netmask4.sin_addr.s_addr = (prefix_len > 0) ?
1080 htonl(0xffffffff << (32 - prefix_len)) : 0;
1086 name_buf += name_size;
1089 uv__free(win_address_buf);
1091 *addresses_ptr = uv_address_buf;
1098 void uv_free_interface_addresses(uv_interface_address_t* addresses,
1100 uv__free(addresses);
1104 int uv_getrusage(uv_rusage_t *uv_rusage) {
1105 FILETIME createTime, exitTime, kernelTime, userTime;
1106 SYSTEMTIME kernelSystemTime, userSystemTime;
1107 PROCESS_MEMORY_COUNTERS memCounters;
1108 IO_COUNTERS ioCounters;
1111 ret = GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime);
1113 return uv_translate_sys_error(GetLastError());
1116 ret = FileTimeToSystemTime(&kernelTime, &kernelSystemTime);
1118 return uv_translate_sys_error(GetLastError());
1121 ret = FileTimeToSystemTime(&userTime, &userSystemTime);
1123 return uv_translate_sys_error(GetLastError());
1126 ret = GetProcessMemoryInfo(GetCurrentProcess(),
1128 sizeof(memCounters));
1130 return uv_translate_sys_error(GetLastError());
1133 ret = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
1135 return uv_translate_sys_error(GetLastError());
1138 memset(uv_rusage, 0, sizeof(*uv_rusage));
1140 uv_rusage->ru_utime.tv_sec = userSystemTime.wHour * 3600 +
1141 userSystemTime.wMinute * 60 +
1142 userSystemTime.wSecond;
1143 uv_rusage->ru_utime.tv_usec = userSystemTime.wMilliseconds * 1000;
1145 uv_rusage->ru_stime.tv_sec = kernelSystemTime.wHour * 3600 +
1146 kernelSystemTime.wMinute * 60 +
1147 kernelSystemTime.wSecond;
1148 uv_rusage->ru_stime.tv_usec = kernelSystemTime.wMilliseconds * 1000;
1150 uv_rusage->ru_majflt = (uint64_t) memCounters.PageFaultCount;
1151 uv_rusage->ru_maxrss = (uint64_t) memCounters.PeakWorkingSetSize / 1024;
1153 uv_rusage->ru_oublock = (uint64_t) ioCounters.WriteOperationCount;
1154 uv_rusage->ru_inblock = (uint64_t) ioCounters.ReadOperationCount;
1160 int uv_os_homedir(char* buffer, size_t* size) {
1165 /* Check if the USERPROFILE environment variable is set first. The task of
1166 performing input validation on buffer and size is taken care of by
1168 r = uv_os_getenv("USERPROFILE", buffer, size);
1170 /* Don't return an error if USERPROFILE was not found. */
1174 /* USERPROFILE is not set, so call uv__getpwuid_r() */
1175 r = uv__getpwuid_r(&pwd);
1181 len = strlen(pwd.homedir);
1185 uv_os_free_passwd(&pwd);
1189 memcpy(buffer, pwd.homedir, len + 1);
1191 uv_os_free_passwd(&pwd);
1197 int uv_os_tmpdir(char* buffer, size_t* size) {
1202 if (buffer == NULL || size == NULL || *size == 0)
1206 len = GetTempPathW(0, NULL);
1208 return uv_translate_sys_error(GetLastError());
1210 /* Include space for terminating null char. */
1212 path = uv__malloc(len * sizeof(wchar_t));
1216 len = GetTempPathW(len, path);
1220 return uv_translate_sys_error(GetLastError());
1223 /* The returned directory should not have a trailing slash, unless it points
1224 * at a drive root, like c:\. Remove it if needed. */
1225 if (path[len - 1] == L'\\' &&
1226 !(len == 3 && path[1] == L':')) {
1231 /* Check how much space we need */
1232 bufsize = WideCharToMultiByte(CP_UTF8, 0, path, -1, NULL, 0, NULL, NULL);
1236 return uv_translate_sys_error(GetLastError());
1237 } else if (bufsize > *size) {
1243 /* Convert to UTF-8 */
1244 bufsize = WideCharToMultiByte(CP_UTF8,
1255 return uv_translate_sys_error(GetLastError());
1257 *size = bufsize - 1;
1262 void uv_os_free_passwd(uv_passwd_t* pwd) {
1266 uv__free(pwd->username);
1267 uv__free(pwd->homedir);
1268 pwd->username = NULL;
1269 pwd->homedir = NULL;
1274 * Converts a UTF-16 string into a UTF-8 one. The resulting string is
1277 * If utf16 is null terminated, utf16len can be set to -1, otherwise it must
1280 int uv__convert_utf16_to_utf8(const WCHAR* utf16, int utf16len, char** utf8) {
1286 /* Check how much space we need */
1287 bufsize = WideCharToMultiByte(CP_UTF8,
1297 return uv_translate_sys_error(GetLastError());
1299 /* Allocate the destination buffer adding an extra byte for the terminating
1300 * NULL. If utf16len is not -1 WideCharToMultiByte will not add it, so
1301 * we do it ourselves always, just in case. */
1302 *utf8 = uv__malloc(bufsize + 1);
1307 /* Convert to UTF-8 */
1308 bufsize = WideCharToMultiByte(CP_UTF8,
1320 return uv_translate_sys_error(GetLastError());
1323 (*utf8)[bufsize] = '\0';
1329 * Converts a UTF-8 string into a UTF-16 one. The resulting string is
1332 * If utf8 is null terminated, utf8len can be set to -1, otherwise it must
1335 int uv__convert_utf8_to_utf16(const char* utf8, int utf8len, WCHAR** utf16) {
1341 /* Check how much space we need */
1342 bufsize = MultiByteToWideChar(CP_UTF8, 0, utf8, utf8len, NULL, 0);
1345 return uv_translate_sys_error(GetLastError());
1347 /* Allocate the destination buffer adding an extra byte for the terminating
1348 * NULL. If utf8len is not -1 MultiByteToWideChar will not add it, so
1349 * we do it ourselves always, just in case. */
1350 *utf16 = uv__malloc(sizeof(WCHAR) * (bufsize + 1));
1355 /* Convert to UTF-16 */
1356 bufsize = MultiByteToWideChar(CP_UTF8, 0, utf8, utf8len, *utf16, bufsize);
1361 return uv_translate_sys_error(GetLastError());
1364 (*utf16)[bufsize] = L'\0';
1369 int uv__getpwuid_r(uv_passwd_t* pwd) {
1371 wchar_t username[UNLEN + 1];
1379 /* Get the home directory using GetUserProfileDirectoryW() */
1380 if (OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token) == 0)
1381 return uv_translate_sys_error(GetLastError());
1384 GetUserProfileDirectoryW(token, NULL, &bufsize);
1385 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
1388 return uv_translate_sys_error(r);
1391 path = uv__malloc(bufsize * sizeof(wchar_t));
1397 if (!GetUserProfileDirectoryW(token, path, &bufsize)) {
1401 return uv_translate_sys_error(r);
1406 /* Get the username using GetUserNameW() */
1407 bufsize = ARRAY_SIZE(username);
1408 if (!GetUserNameW(username, &bufsize)) {
1412 /* This should not be possible */
1413 if (r == ERROR_INSUFFICIENT_BUFFER)
1416 return uv_translate_sys_error(r);
1419 pwd->homedir = NULL;
1420 r = uv__convert_utf16_to_utf8(path, -1, &pwd->homedir);
1426 pwd->username = NULL;
1427 r = uv__convert_utf16_to_utf8(username, -1, &pwd->username);
1430 uv__free(pwd->homedir);
1442 int uv_os_get_passwd(uv_passwd_t* pwd) {
1443 return uv__getpwuid_r(pwd);
1447 int uv_os_environ(uv_env_item_t** envitems, int* count) {
1451 uv_env_item_t* envitem;
1456 env = GetEnvironmentStringsW();
1460 for (penv = env, i = 0; *penv != L'\0'; penv += wcslen(penv) + 1, i++);
1462 *envitems = uv__calloc(i, sizeof(**envitems));
1463 if (*envitems == NULL) {
1464 FreeEnvironmentStringsW(env);
1471 while (*penv != L'\0' && cnt < i) {
1475 if (uv__convert_utf16_to_utf8(penv, -1, &buf) != 0)
1478 /* Using buf + 1 here because we know that `buf` has length at least 1,
1479 * and some special environment variables on Windows start with a = sign. */
1480 ptr = strchr(buf + 1, '=');
1488 envitem = &(*envitems)[cnt];
1489 envitem->name = buf;
1490 envitem->value = ptr + 1;
1495 penv += wcslen(penv) + 1;
1498 FreeEnvironmentStringsW(env);
1504 FreeEnvironmentStringsW(env);
1506 for (i = 0; i < cnt; i++) {
1507 envitem = &(*envitems)[cnt];
1508 uv__free(envitem->name);
1510 uv__free(*envitems);
1518 int uv_os_getenv(const char* name, char* buffer, size_t* size) {
1519 wchar_t fastvar[512];
1527 if (name == NULL || buffer == NULL || size == NULL || *size == 0)
1530 r = uv__convert_utf8_to_utf16(name, -1, &name_w);
1536 varlen = ARRAY_SIZE(fastvar);
1539 SetLastError(ERROR_SUCCESS);
1540 len = GetEnvironmentVariableW(name_w, var, varlen);
1545 /* Try repeatedly because we might have been preempted by another thread
1546 * modifying the environment variable just as we're trying to read it.
1552 var = uv__malloc(varlen * sizeof(*var));
1565 if (r != ERROR_SUCCESS) {
1566 r = uv_translate_sys_error(r);
1571 /* Check how much space we need */
1572 bufsize = WideCharToMultiByte(CP_UTF8, 0, var, -1, NULL, 0, NULL, NULL);
1575 r = uv_translate_sys_error(GetLastError());
1577 } else if (bufsize > *size) {
1583 /* Convert to UTF-8 */
1584 bufsize = WideCharToMultiByte(CP_UTF8,
1594 r = uv_translate_sys_error(GetLastError());
1598 *size = bufsize - 1;
1613 int uv_os_setenv(const char* name, const char* value) {
1618 if (name == NULL || value == NULL)
1621 r = uv__convert_utf8_to_utf16(name, -1, &name_w);
1626 r = uv__convert_utf8_to_utf16(value, -1, &value_w);
1633 r = SetEnvironmentVariableW(name_w, value_w);
1638 return uv_translate_sys_error(GetLastError());
1644 int uv_os_unsetenv(const char* name) {
1651 r = uv__convert_utf8_to_utf16(name, -1, &name_w);
1656 r = SetEnvironmentVariableW(name_w, NULL);
1660 return uv_translate_sys_error(GetLastError());
1666 int uv_os_gethostname(char* buffer, size_t* size) {
1667 WCHAR buf[UV_MAXHOSTNAMESIZE];
1672 if (buffer == NULL || size == NULL || *size == 0)
1675 uv__once_init(); /* Initialize winsock */
1677 if (pGetHostNameW == NULL)
1680 if (pGetHostNameW(buf, UV_MAXHOSTNAMESIZE) != 0)
1681 return uv_translate_sys_error(WSAGetLastError());
1683 convert_result = uv__convert_utf16_to_utf8(buf, -1, &utf8_str);
1685 if (convert_result != 0)
1686 return convert_result;
1688 len = strlen(utf8_str);
1695 memcpy(buffer, utf8_str, len + 1);
1702 static int uv__get_handle(uv_pid_t pid, int access, HANDLE* handle) {
1706 *handle = GetCurrentProcess();
1708 *handle = OpenProcess(access, FALSE, pid);
1710 if (*handle == NULL) {
1713 if (r == ERROR_INVALID_PARAMETER)
1716 return uv_translate_sys_error(r);
1723 int uv_os_getpriority(uv_pid_t pid, int* priority) {
1727 if (priority == NULL)
1730 r = uv__get_handle(pid, PROCESS_QUERY_LIMITED_INFORMATION, &handle);
1735 r = GetPriorityClass(handle);
1738 r = uv_translate_sys_error(GetLastError());
1740 /* Map Windows priority classes to Unix nice values. */
1741 if (r == REALTIME_PRIORITY_CLASS)
1742 *priority = UV_PRIORITY_HIGHEST;
1743 else if (r == HIGH_PRIORITY_CLASS)
1744 *priority = UV_PRIORITY_HIGH;
1745 else if (r == ABOVE_NORMAL_PRIORITY_CLASS)
1746 *priority = UV_PRIORITY_ABOVE_NORMAL;
1747 else if (r == NORMAL_PRIORITY_CLASS)
1748 *priority = UV_PRIORITY_NORMAL;
1749 else if (r == BELOW_NORMAL_PRIORITY_CLASS)
1750 *priority = UV_PRIORITY_BELOW_NORMAL;
1751 else /* IDLE_PRIORITY_CLASS */
1752 *priority = UV_PRIORITY_LOW;
1757 CloseHandle(handle);
1762 int uv_os_setpriority(uv_pid_t pid, int priority) {
1767 /* Map Unix nice values to Windows priority classes. */
1768 if (priority < UV_PRIORITY_HIGHEST || priority > UV_PRIORITY_LOW)
1770 else if (priority < UV_PRIORITY_HIGH)
1771 priority_class = REALTIME_PRIORITY_CLASS;
1772 else if (priority < UV_PRIORITY_ABOVE_NORMAL)
1773 priority_class = HIGH_PRIORITY_CLASS;
1774 else if (priority < UV_PRIORITY_NORMAL)
1775 priority_class = ABOVE_NORMAL_PRIORITY_CLASS;
1776 else if (priority < UV_PRIORITY_BELOW_NORMAL)
1777 priority_class = NORMAL_PRIORITY_CLASS;
1778 else if (priority < UV_PRIORITY_LOW)
1779 priority_class = BELOW_NORMAL_PRIORITY_CLASS;
1781 priority_class = IDLE_PRIORITY_CLASS;
1783 r = uv__get_handle(pid, PROCESS_SET_INFORMATION, &handle);
1788 if (SetPriorityClass(handle, priority_class) == 0)
1789 r = uv_translate_sys_error(GetLastError());
1791 CloseHandle(handle);
1796 int uv_os_uname(uv_utsname_t* buffer) {
1797 /* Implementation loosely based on
1798 https://github.com/gagern/gnulib/blob/master/lib/uname.c */
1799 OSVERSIONINFOW os_info;
1800 SYSTEM_INFO system_info;
1802 WCHAR product_name_w[256];
1803 DWORD product_name_w_size;
1805 int processor_level;
1812 os_info.dwOSVersionInfoSize = sizeof(os_info);
1813 os_info.szCSDVersion[0] = L'\0';
1815 /* Try calling RtlGetVersion(), and fall back to the deprecated GetVersionEx()
1816 if RtlGetVersion() is not available. */
1817 if (pRtlGetVersion) {
1818 pRtlGetVersion(&os_info);
1820 /* Silence GetVersionEx() deprecation warning. */
1822 #pragma warning(suppress : 4996)
1824 if (GetVersionExW(&os_info) == 0) {
1825 r = uv_translate_sys_error(GetLastError());
1830 /* Populate the version field. */
1832 r = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
1833 L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1838 if (r == ERROR_SUCCESS) {
1839 product_name_w_size = sizeof(product_name_w);
1840 r = RegGetValueW(registry_key,
1845 (PVOID) product_name_w,
1846 &product_name_w_size);
1847 RegCloseKey(registry_key);
1849 if (r == ERROR_SUCCESS) {
1850 version_size = WideCharToMultiByte(CP_UTF8,
1855 sizeof(buffer->version),
1858 if (version_size == 0) {
1859 r = uv_translate_sys_error(GetLastError());
1865 /* Append service pack information to the version if present. */
1866 if (os_info.szCSDVersion[0] != L'\0') {
1867 if (version_size > 0)
1868 buffer->version[version_size - 1] = ' ';
1870 if (WideCharToMultiByte(CP_UTF8,
1872 os_info.szCSDVersion,
1874 buffer->version + version_size,
1875 sizeof(buffer->version) - version_size,
1878 r = uv_translate_sys_error(GetLastError());
1883 /* Populate the sysname field. */
1885 r = snprintf(buffer->sysname,
1886 sizeof(buffer->sysname),
1888 (unsigned int) os_info.dwMajorVersion,
1889 (unsigned int) os_info.dwMinorVersion);
1890 assert((size_t)r < sizeof(buffer->sysname));
1892 uv__strscpy(buffer->sysname, "Windows_NT", sizeof(buffer->sysname));
1895 /* Populate the release field. */
1896 r = snprintf(buffer->release,
1897 sizeof(buffer->release),
1899 (unsigned int) os_info.dwMajorVersion,
1900 (unsigned int) os_info.dwMinorVersion,
1901 (unsigned int) os_info.dwBuildNumber);
1902 assert((size_t)r < sizeof(buffer->release));
1904 /* Populate the machine field. */
1905 GetSystemInfo(&system_info);
1907 switch (system_info.wProcessorArchitecture) {
1908 case PROCESSOR_ARCHITECTURE_AMD64:
1909 uv__strscpy(buffer->machine, "x86_64", sizeof(buffer->machine));
1911 case PROCESSOR_ARCHITECTURE_IA64:
1912 uv__strscpy(buffer->machine, "ia64", sizeof(buffer->machine));
1914 case PROCESSOR_ARCHITECTURE_INTEL:
1915 uv__strscpy(buffer->machine, "i386", sizeof(buffer->machine));
1917 if (system_info.wProcessorLevel > 3) {
1918 processor_level = system_info.wProcessorLevel < 6 ?
1919 system_info.wProcessorLevel : 6;
1920 buffer->machine[1] = '0' + processor_level;
1924 case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
1925 uv__strscpy(buffer->machine, "i686", sizeof(buffer->machine));
1927 case PROCESSOR_ARCHITECTURE_MIPS:
1928 uv__strscpy(buffer->machine, "mips", sizeof(buffer->machine));
1930 case PROCESSOR_ARCHITECTURE_ALPHA:
1931 case PROCESSOR_ARCHITECTURE_ALPHA64:
1932 uv__strscpy(buffer->machine, "alpha", sizeof(buffer->machine));
1934 case PROCESSOR_ARCHITECTURE_PPC:
1935 uv__strscpy(buffer->machine, "powerpc", sizeof(buffer->machine));
1937 case PROCESSOR_ARCHITECTURE_SHX:
1938 uv__strscpy(buffer->machine, "sh", sizeof(buffer->machine));
1940 case PROCESSOR_ARCHITECTURE_ARM:
1941 uv__strscpy(buffer->machine, "arm", sizeof(buffer->machine));
1944 uv__strscpy(buffer->machine, "unknown", sizeof(buffer->machine));
1951 buffer->sysname[0] = '\0';
1952 buffer->release[0] = '\0';
1953 buffer->version[0] = '\0';
1954 buffer->machine[0] = '\0';
1958 int uv_gettimeofday(uv_timeval64_t* tv) {
1959 /* Based on https://doxygen.postgresql.org/gettimeofday_8c_source.html */
1960 const uint64_t epoch = (uint64_t) 116444736000000000ULL;
1962 ULARGE_INTEGER ularge;
1967 GetSystemTimeAsFileTime(&file_time);
1968 ularge.LowPart = file_time.dwLowDateTime;
1969 ularge.HighPart = file_time.dwHighDateTime;
1970 tv->tv_sec = (int64_t) ((ularge.QuadPart - epoch) / 10000000L);
1971 tv->tv_usec = (int32_t) (((ularge.QuadPart - epoch) % 10000000L) / 10);
1975 int uv__random_rtlgenrandom(void* buf, size_t buflen) {
1979 if (SystemFunction036(buf, buflen) == FALSE)
1985 void uv_sleep(unsigned int msec) {