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