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