]> git.sesse.net Git - stockfish/blob - src/misc.cpp
add clang-format
[stockfish] / src / misc.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
4
5   Stockfish 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 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish 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, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "misc.h"
20
21 #ifdef _WIN32
22     #if _WIN32_WINNT < 0x0601
23         #undef _WIN32_WINNT
24         #define _WIN32_WINNT 0x0601  // Force to include needed API prototypes
25     #endif
26
27     #ifndef NOMINMAX
28         #define NOMINMAX
29     #endif
30
31     #include <windows.h>
32 // The needed Windows API for processor groups could be missed from old Windows
33 // versions, so instead of calling them directly (forcing the linker to resolve
34 // the calls at compile time), try to load them at runtime. To do this we need
35 // first to define the corresponding function pointers.
36 extern "C" {
37 using fun1_t = bool (*)(LOGICAL_PROCESSOR_RELATIONSHIP,
38                         PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
39                         PDWORD);
40 using fun2_t = bool (*)(USHORT, PGROUP_AFFINITY);
41 using fun3_t = bool (*)(HANDLE, CONST GROUP_AFFINITY*, PGROUP_AFFINITY);
42 using fun4_t = bool (*)(USHORT, PGROUP_AFFINITY, USHORT, PUSHORT);
43 using fun5_t = WORD (*)();
44 using fun6_t = bool (*)(HANDLE, DWORD, PHANDLE);
45 using fun7_t = bool (*)(LPCSTR, LPCSTR, PLUID);
46 using fun8_t = bool (*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
47 }
48 #endif
49
50 #include <atomic>
51 #include <cmath>
52 #include <cstdlib>
53 #include <fstream>
54 #include <iomanip>
55 #include <iostream>
56 #include <mutex>
57 #include <sstream>
58 #include <string_view>
59
60 #include "types.h"
61
62 #if defined(__linux__) && !defined(__ANDROID__)
63     #include <sys/mman.h>
64 #endif
65
66 #if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) \
67   || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) \
68   || defined(__e2k__)
69     #define POSIXALIGNEDALLOC
70     #include <stdlib.h>
71 #endif
72
73 namespace Stockfish {
74
75 namespace {
76
77 // Version number or dev.
78 constexpr std::string_view version = "dev";
79
80 // Our fancy logging facility. The trick here is to replace cin.rdbuf() and
81 // cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
82 // can toggle the logging of std::cout and std:cin at runtime whilst preserving
83 // usual I/O functionality, all without changing a single line of code!
84 // Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
85
86 struct Tie: public std::streambuf {  // MSVC requires split streambuf for cin and cout
87
88     Tie(std::streambuf* b, std::streambuf* l) :
89         buf(b),
90         logBuf(l) {}
91
92     int sync() override { return logBuf->pubsync(), buf->pubsync(); }
93     int overflow(int c) override { return log(buf->sputc(char(c)), "<< "); }
94     int underflow() override { return buf->sgetc(); }
95     int uflow() override { return log(buf->sbumpc(), ">> "); }
96
97     std::streambuf *buf, *logBuf;
98
99     int log(int c, const char* prefix) {
100
101         static int last = '\n';  // Single log file
102
103         if (last == '\n')
104             logBuf->sputn(prefix, 3);
105
106         return last = logBuf->sputc(char(c));
107     }
108 };
109
110 class Logger {
111
112     Logger() :
113         in(std::cin.rdbuf(), file.rdbuf()),
114         out(std::cout.rdbuf(), file.rdbuf()) {}
115     ~Logger() { start(""); }
116
117     std::ofstream file;
118     Tie           in, out;
119
120    public:
121     static void start(const std::string& fname) {
122
123         static Logger l;
124
125         if (l.file.is_open())
126         {
127             std::cout.rdbuf(l.out.buf);
128             std::cin.rdbuf(l.in.buf);
129             l.file.close();
130         }
131
132         if (!fname.empty())
133         {
134             l.file.open(fname, std::ifstream::out);
135
136             if (!l.file.is_open())
137             {
138                 std::cerr << "Unable to open debug log file " << fname << std::endl;
139                 exit(EXIT_FAILURE);
140             }
141
142             std::cin.rdbuf(&l.in);
143             std::cout.rdbuf(&l.out);
144         }
145     }
146 };
147
148 }  // namespace
149
150
151 // engine_info() returns the full name of the current Stockfish version.
152 // For local dev compiles we try to append the commit sha and commit date
153 // from git if that fails only the local compilation date is set and "nogit" is specified:
154 // Stockfish dev-YYYYMMDD-SHA
155 // or
156 // Stockfish dev-YYYYMMDD-nogit
157 //
158 // For releases (non-dev builds) we only include the version number:
159 // Stockfish version
160
161 std::string engine_info(bool to_uci) {
162     std::stringstream ss;
163     ss << "Stockfish " << version << std::setfill('0');
164
165     if constexpr (version == "dev")
166     {
167         ss << "-";
168 #ifdef GIT_DATE
169         ss << stringify(GIT_DATE);
170 #else
171         constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
172         std::string                month, day, year;
173         std::stringstream          date(__DATE__);  // From compiler, format is "Sep 21 2008"
174
175         date >> month >> day >> year;
176         ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4)
177            << std::setw(2) << std::setfill('0') << day;
178 #endif
179
180         ss << "-";
181
182 #ifdef GIT_SHA
183         ss << stringify(GIT_SHA);
184 #else
185         ss << "nogit";
186 #endif
187     }
188
189     ss << (to_uci ? "\nid author " : " by ") << "the Stockfish developers (see AUTHORS file)";
190
191     return ss.str();
192 }
193
194
195 // compiler_info() returns a string trying to describe the compiler we use
196
197 std::string compiler_info() {
198
199 #define make_version_string(major, minor, patch) \
200     stringify(major) "." stringify(minor) "." stringify(patch)
201
202     // Predefined macros hell:
203     //
204     // __GNUC__                Compiler is GCC, Clang or ICX
205     // __clang__               Compiler is Clang or ICX
206     // __INTEL_LLVM_COMPILER   Compiler is ICX
207     // _MSC_VER                Compiler is MSVC
208     // _WIN32                  Building on Windows (any)
209     // _WIN64                  Building on Windows 64 bit
210
211     std::string compiler = "\nCompiled by                : ";
212
213 #if defined(__INTEL_LLVM_COMPILER)
214     compiler += "ICX ";
215     compiler += stringify(__INTEL_LLVM_COMPILER);
216 #elif defined(__clang__)
217     compiler += "clang++ ";
218     compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
219 #elif _MSC_VER
220     compiler += "MSVC ";
221     compiler += "(version ";
222     compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
223     compiler += ")";
224 #elif defined(__e2k__) && defined(__LCC__)
225     #define dot_ver2(n) \
226         compiler += char('.'); \
227         compiler += char('0' + (n) / 10); \
228         compiler += char('0' + (n) % 10);
229
230     compiler += "MCST LCC ";
231     compiler += "(version ";
232     compiler += std::to_string(__LCC__ / 100);
233     dot_ver2(__LCC__ % 100) dot_ver2(__LCC_MINOR__) compiler += ")";
234 #elif __GNUC__
235     compiler += "g++ (GNUC) ";
236     compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
237 #else
238     compiler += "Unknown compiler ";
239     compiler += "(unknown version)";
240 #endif
241
242 #if defined(__APPLE__)
243     compiler += " on Apple";
244 #elif defined(__CYGWIN__)
245     compiler += " on Cygwin";
246 #elif defined(__MINGW64__)
247     compiler += " on MinGW64";
248 #elif defined(__MINGW32__)
249     compiler += " on MinGW32";
250 #elif defined(__ANDROID__)
251     compiler += " on Android";
252 #elif defined(__linux__)
253     compiler += " on Linux";
254 #elif defined(_WIN64)
255     compiler += " on Microsoft Windows 64-bit";
256 #elif defined(_WIN32)
257     compiler += " on Microsoft Windows 32-bit";
258 #else
259     compiler += " on unknown system";
260 #endif
261
262     compiler += "\nCompilation architecture   : ";
263 #if defined(ARCH)
264     compiler += stringify(ARCH);
265 #else
266     compiler += "(undefined architecture)";
267 #endif
268
269     compiler += "\nCompilation settings       : ";
270     compiler += (Is64Bit ? "64bit" : "32bit");
271 #if defined(USE_VNNI)
272     compiler += " VNNI";
273 #endif
274 #if defined(USE_AVX512)
275     compiler += " AVX512";
276 #endif
277     compiler += (HasPext ? " BMI2" : "");
278 #if defined(USE_AVX2)
279     compiler += " AVX2";
280 #endif
281 #if defined(USE_SSE41)
282     compiler += " SSE41";
283 #endif
284 #if defined(USE_SSSE3)
285     compiler += " SSSE3";
286 #endif
287 #if defined(USE_SSE2)
288     compiler += " SSE2";
289 #endif
290     compiler += (HasPopCnt ? " POPCNT" : "");
291 #if defined(USE_NEON_DOTPROD)
292     compiler += " NEON_DOTPROD";
293 #elif defined(USE_NEON)
294     compiler += " NEON";
295 #endif
296
297 #if !defined(NDEBUG)
298     compiler += " DEBUG";
299 #endif
300
301     compiler += "\nCompiler __VERSION__ macro : ";
302 #ifdef __VERSION__
303     compiler += __VERSION__;
304 #else
305     compiler += "(undefined macro)";
306 #endif
307
308     compiler += "\n";
309
310     return compiler;
311 }
312
313
314 // Debug functions used mainly to collect run-time statistics
315 constexpr int MaxDebugSlots = 32;
316
317 namespace {
318
319 template<size_t N>
320 struct DebugInfo {
321     std::atomic<int64_t> data[N] = {0};
322
323     constexpr inline std::atomic<int64_t>& operator[](int index) { return data[index]; }
324 };
325
326 DebugInfo<2> hit[MaxDebugSlots];
327 DebugInfo<2> mean[MaxDebugSlots];
328 DebugInfo<3> stdev[MaxDebugSlots];
329 DebugInfo<6> correl[MaxDebugSlots];
330
331 }  // namespace
332
333 void dbg_hit_on(bool cond, int slot) {
334
335     ++hit[slot][0];
336     if (cond)
337         ++hit[slot][1];
338 }
339
340 void dbg_mean_of(int64_t value, int slot) {
341
342     ++mean[slot][0];
343     mean[slot][1] += value;
344 }
345
346 void dbg_stdev_of(int64_t value, int slot) {
347
348     ++stdev[slot][0];
349     stdev[slot][1] += value;
350     stdev[slot][2] += value * value;
351 }
352
353 void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
354
355     ++correl[slot][0];
356     correl[slot][1] += value1;
357     correl[slot][2] += value1 * value1;
358     correl[slot][3] += value2;
359     correl[slot][4] += value2 * value2;
360     correl[slot][5] += value1 * value2;
361 }
362
363 void dbg_print() {
364
365     int64_t n;
366     auto    E   = [&n](int64_t x) { return double(x) / n; };
367     auto    sqr = [](double x) { return x * x; };
368
369     for (int i = 0; i < MaxDebugSlots; ++i)
370         if ((n = hit[i][0]))
371             std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1]
372                       << " Hit Rate (%) " << 100.0 * E(hit[i][1]) << std::endl;
373
374     for (int i = 0; i < MaxDebugSlots; ++i)
375         if ((n = mean[i][0]))
376         {
377             std::cerr << "Mean #" << i << ": Total " << n << " Mean " << E(mean[i][1]) << std::endl;
378         }
379
380     for (int i = 0; i < MaxDebugSlots; ++i)
381         if ((n = stdev[i][0]))
382         {
383             double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
384             std::cerr << "Stdev #" << i << ": Total " << n << " Stdev " << r << std::endl;
385         }
386
387     for (int i = 0; i < MaxDebugSlots; ++i)
388         if ((n = correl[i][0]))
389         {
390             double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
391                      / (sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
392                         * sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
393             std::cerr << "Correl. #" << i << ": Total " << n << " Coefficient " << r << std::endl;
394         }
395 }
396
397
398 // Used to serialize access to std::cout to avoid multiple threads writing at
399 // the same time.
400
401 std::ostream& operator<<(std::ostream& os, SyncCout sc) {
402
403     static std::mutex m;
404
405     if (sc == IO_LOCK)
406         m.lock();
407
408     if (sc == IO_UNLOCK)
409         m.unlock();
410
411     return os;
412 }
413
414
415 // Trampoline helper to avoid moving Logger to misc.h
416 void start_logger(const std::string& fname) { Logger::start(fname); }
417
418
419 // prefetch() preloads the given address in L1/L2 cache. This is a non-blocking
420 // function that doesn't stall the CPU waiting for data to be loaded from memory,
421 // which can be quite slow.
422 #ifdef NO_PREFETCH
423
424 void prefetch(void*) {}
425
426 #else
427
428 void prefetch(void* addr) {
429
430     #if defined(_MSC_VER)
431     _mm_prefetch((char*) addr, _MM_HINT_T0);
432     #else
433     __builtin_prefetch(addr);
434     #endif
435 }
436
437 #endif
438
439
440 // std_aligned_alloc() is our wrapper for systems where the c++17 implementation
441 // does not guarantee the availability of aligned_alloc(). Memory allocated with
442 // std_aligned_alloc() must be freed with std_aligned_free().
443
444 void* std_aligned_alloc(size_t alignment, size_t size) {
445
446 #if defined(POSIXALIGNEDALLOC)
447     void* mem;
448     return posix_memalign(&mem, alignment, size) ? nullptr : mem;
449 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
450     return _mm_malloc(size, alignment);
451 #elif defined(_WIN32)
452     return _aligned_malloc(size, alignment);
453 #else
454     return std::aligned_alloc(alignment, size);
455 #endif
456 }
457
458 void std_aligned_free(void* ptr) {
459
460 #if defined(POSIXALIGNEDALLOC)
461     free(ptr);
462 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
463     _mm_free(ptr);
464 #elif defined(_WIN32)
465     _aligned_free(ptr);
466 #else
467     free(ptr);
468 #endif
469 }
470
471 // aligned_large_pages_alloc() will return suitably aligned memory, if possible using large pages.
472
473 #if defined(_WIN32)
474
475 static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
476
477     #if !defined(_WIN64)
478     return nullptr;
479     #else
480
481     HANDLE hProcessToken{};
482     LUID   luid{};
483     void*  mem = nullptr;
484
485     const size_t largePageSize = GetLargePageMinimum();
486     if (!largePageSize)
487         return nullptr;
488
489     // Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
490
491     HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
492
493     if (!hAdvapi32)
494         hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
495
496     auto fun6 = fun6_t((void (*)()) GetProcAddress(hAdvapi32, "OpenProcessToken"));
497     if (!fun6)
498         return nullptr;
499     auto fun7 = fun7_t((void (*)()) GetProcAddress(hAdvapi32, "LookupPrivilegeValueA"));
500     if (!fun7)
501         return nullptr;
502     auto fun8 = fun8_t((void (*)()) GetProcAddress(hAdvapi32, "AdjustTokenPrivileges"));
503     if (!fun8)
504         return nullptr;
505
506     // We need SeLockMemoryPrivilege, so try to enable it for the process
507     if (!fun6(  // OpenProcessToken()
508           GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
509         return nullptr;
510
511     if (fun7(  // LookupPrivilegeValue(nullptr, SE_LOCK_MEMORY_NAME, &luid)
512           nullptr, "SeLockMemoryPrivilege", &luid))
513     {
514         TOKEN_PRIVILEGES tp{};
515         TOKEN_PRIVILEGES prevTp{};
516         DWORD            prevTpLen = 0;
517
518         tp.PrivilegeCount           = 1;
519         tp.Privileges[0].Luid       = luid;
520         tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
521
522         // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges() succeeds,
523         // we still need to query GetLastError() to ensure that the privileges were actually obtained.
524         if (fun8(  // AdjustTokenPrivileges()
525               hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp, &prevTpLen)
526             && GetLastError() == ERROR_SUCCESS)
527         {
528             // Round up size to full pages and allocate
529             allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
530             mem       = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
531                                      PAGE_READWRITE);
532
533             // Privilege no longer needed, restore previous state
534             fun8(  // AdjustTokenPrivileges ()
535               hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
536         }
537     }
538
539     CloseHandle(hProcessToken);
540
541     return mem;
542
543     #endif
544 }
545
546 void* aligned_large_pages_alloc(size_t allocSize) {
547
548     // Try to allocate large pages
549     void* mem = aligned_large_pages_alloc_windows(allocSize);
550
551     // Fall back to regular, page-aligned, allocation if necessary
552     if (!mem)
553         mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
554
555     return mem;
556 }
557
558 #else
559
560 void* aligned_large_pages_alloc(size_t allocSize) {
561
562     #if defined(__linux__)
563     constexpr size_t alignment = 2 * 1024 * 1024;  // assumed 2MB page size
564     #else
565     constexpr size_t alignment = 4096;  // assumed small page size
566     #endif
567
568     // round up to multiples of alignment
569     size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
570     void*  mem  = std_aligned_alloc(alignment, size);
571     #if defined(MADV_HUGEPAGE)
572     madvise(mem, size, MADV_HUGEPAGE);
573     #endif
574     return mem;
575 }
576
577 #endif
578
579
580 // aligned_large_pages_free() will free the previously allocated ttmem
581
582 #if defined(_WIN32)
583
584 void aligned_large_pages_free(void* mem) {
585
586     if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
587     {
588         DWORD err = GetLastError();
589         std::cerr << "Failed to free large page memory. Error code: 0x" << std::hex << err
590                   << std::dec << std::endl;
591         exit(EXIT_FAILURE);
592     }
593 }
594
595 #else
596
597 void aligned_large_pages_free(void* mem) { std_aligned_free(mem); }
598
599 #endif
600
601
602 namespace WinProcGroup {
603
604 #ifndef _WIN32
605
606 void bindThisThread(size_t) {}
607
608 #else
609
610 // best_node() retrieves logical processor information using Windows specific
611 // API and returns the best node id for the thread with index idx. Original
612 // code from Texel by Peter Ă–sterlund.
613
614 static int best_node(size_t idx) {
615
616     int   threads      = 0;
617     int   nodes        = 0;
618     int   cores        = 0;
619     DWORD returnLength = 0;
620     DWORD byteOffset   = 0;
621
622     // Early exit if the needed API is not available at runtime
623     HMODULE k32  = GetModuleHandle(TEXT("Kernel32.dll"));
624     auto    fun1 = (fun1_t) (void (*)()) GetProcAddress(k32, "GetLogicalProcessorInformationEx");
625     if (!fun1)
626         return -1;
627
628     // First call to GetLogicalProcessorInformationEx() to get returnLength.
629     // We expect the call to fail due to null buffer.
630     if (fun1(RelationAll, nullptr, &returnLength))
631         return -1;
632
633     // Once we know returnLength, allocate the buffer
634     SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr;
635     ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) malloc(returnLength);
636
637     // Second call to GetLogicalProcessorInformationEx(), now we expect to succeed
638     if (!fun1(RelationAll, buffer, &returnLength))
639     {
640         free(buffer);
641         return -1;
642     }
643
644     while (byteOffset < returnLength)
645     {
646         if (ptr->Relationship == RelationNumaNode)
647             nodes++;
648
649         else if (ptr->Relationship == RelationProcessorCore)
650         {
651             cores++;
652             threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
653         }
654
655         assert(ptr->Size);
656         byteOffset += ptr->Size;
657         ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) (((char*) ptr) + ptr->Size);
658     }
659
660     free(buffer);
661
662     std::vector<int> groups;
663
664     // Run as many threads as possible on the same node until the core limit is
665     // reached, then move on to filling the next node.
666     for (int n = 0; n < nodes; n++)
667         for (int i = 0; i < cores / nodes; i++)
668             groups.push_back(n);
669
670     // In case a core has more than one logical processor (we assume 2) and we
671     // have still threads to allocate, then spread them evenly across available
672     // nodes.
673     for (int t = 0; t < threads - cores; t++)
674         groups.push_back(t % nodes);
675
676     // If we still have more threads than the total number of logical processors
677     // then return -1 and let the OS to decide what to do.
678     return idx < groups.size() ? groups[idx] : -1;
679 }
680
681
682 // bindThisThread() sets the group affinity of the current thread
683
684 void bindThisThread(size_t idx) {
685
686     // Use only local variables to be thread-safe
687     int node = best_node(idx);
688
689     if (node == -1)
690         return;
691
692     // Early exit if the needed API are not available at runtime
693     HMODULE k32  = GetModuleHandle(TEXT("Kernel32.dll"));
694     auto    fun2 = fun2_t((void (*)()) GetProcAddress(k32, "GetNumaNodeProcessorMaskEx"));
695     auto    fun3 = fun3_t((void (*)()) GetProcAddress(k32, "SetThreadGroupAffinity"));
696     auto    fun4 = fun4_t((void (*)()) GetProcAddress(k32, "GetNumaNodeProcessorMask2"));
697     auto    fun5 = fun5_t((void (*)()) GetProcAddress(k32, "GetMaximumProcessorGroupCount"));
698
699     if (!fun2 || !fun3)
700         return;
701
702     if (!fun4 || !fun5)
703     {
704         GROUP_AFFINITY affinity;
705         if (fun2(node, &affinity))                         // GetNumaNodeProcessorMaskEx
706             fun3(GetCurrentThread(), &affinity, nullptr);  // SetThreadGroupAffinity
707     }
708     else
709     {
710         // If a numa node has more than one processor group, we assume they are
711         // sized equal and we spread threads evenly across the groups.
712         USHORT elements, returnedElements;
713         elements                 = fun5();  // GetMaximumProcessorGroupCount
714         GROUP_AFFINITY* affinity = (GROUP_AFFINITY*) malloc(elements * sizeof(GROUP_AFFINITY));
715         if (fun4(node, affinity, elements, &returnedElements))  // GetNumaNodeProcessorMask2
716             fun3(GetCurrentThread(), &affinity[idx % returnedElements],
717                  nullptr);  // SetThreadGroupAffinity
718         free(affinity);
719     }
720 }
721
722 #endif
723
724 }  // namespace WinProcGroup
725
726 #ifdef _WIN32
727     #include <direct.h>
728     #define GETCWD _getcwd
729 #else
730     #include <unistd.h>
731     #define GETCWD getcwd
732 #endif
733
734 namespace CommandLine {
735
736 std::string argv0;             // path+name of the executable binary, as given by argv[0]
737 std::string binaryDirectory;   // path of the executable directory
738 std::string workingDirectory;  // path of the working directory
739
740 void init([[maybe_unused]] int argc, char* argv[]) {
741     std::string pathSeparator;
742
743     // extract the path+name of the executable binary
744     argv0 = argv[0];
745
746 #ifdef _WIN32
747     pathSeparator = "\\";
748     #ifdef _MSC_VER
749     // Under windows argv[0] may not have the extension. Also _get_pgmptr() had
750     // issues in some Windows 10 versions, so check returned values carefully.
751     char* pgmptr = nullptr;
752     if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
753         argv0 = pgmptr;
754     #endif
755 #else
756     pathSeparator = "/";
757 #endif
758
759     // extract the working directory
760     workingDirectory = "";
761     char  buff[40000];
762     char* cwd = GETCWD(buff, 40000);
763     if (cwd)
764         workingDirectory = cwd;
765
766     // extract the binary directory path from argv0
767     binaryDirectory = argv0;
768     size_t pos      = binaryDirectory.find_last_of("\\/");
769     if (pos == std::string::npos)
770         binaryDirectory = "." + pathSeparator;
771     else
772         binaryDirectory.resize(pos + 1);
773
774     // pattern replacement: "./" at the start of path is replaced by the working directory
775     if (binaryDirectory.find("." + pathSeparator) == 0)
776         binaryDirectory.replace(0, 1, workingDirectory);
777 }
778
779
780 }  // namespace CommandLine
781
782 }  // namespace Stockfish